var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __export = (target, all) => { for (var name260 in all) __defProp(target, name260, { get: all[name260], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __decorateClass = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp(target, key, result); return result; }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.constants.js var ToGammaSpace, ToLinearSpace, PHI, Epsilon; var init_math_constants = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.constants.js"() { ToGammaSpace = 1 / 2.2; ToLinearSpace = 2.2; PHI = (1 + Math.sqrt(5)) / 2; Epsilon = 1e-3; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/arrayTools.js function BuildArray(size, itemBuilder) { const a = []; for (let i = 0; i < size; ++i) { a.push(itemBuilder()); } return a; } function BuildTuple(size, itemBuilder) { return BuildArray(size, itemBuilder); } function ObserveArrayFunction(object, functionName, callback) { const oldFunction = object[functionName]; if (typeof oldFunction !== "function") { return null; } const newFunction = /* @__PURE__ */ __name(function() { const previousLength = object.length; const returnValue = newFunction.previous.apply(object, arguments); callback(functionName, previousLength); return returnValue; }, "newFunction"); oldFunction.next = newFunction; newFunction.previous = oldFunction; object[functionName] = newFunction; return () => { const previous = newFunction.previous; if (!previous) { return; } const next = newFunction.next; if (next) { previous.next = next; next.previous = previous; } else { previous.next = void 0; object[functionName] = previous; } newFunction.next = void 0; newFunction.previous = void 0; }; } function _ObserveArray(array, callback) { const unObserveFunctions = observedArrayFunctions.map((name260) => { return ObserveArrayFunction(array, name260, callback); }); return () => { for (const unObserveFunction of unObserveFunctions) { unObserveFunction?.(); } }; } var observedArrayFunctions; var init_arrayTools = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/arrayTools.js"() { __name(BuildArray, "BuildArray"); __name(BuildTuple, "BuildTuple"); __name(ObserveArrayFunction, "ObserveArrayFunction"); observedArrayFunctions = ["push", "splice", "pop", "shift", "unshift"]; __name(_ObserveArray, "_ObserveArray"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/typeStore.js function RegisterClass(className2, type) { RegisteredTypes[className2] = type; } function GetClass(fqdn) { return RegisteredTypes[fqdn]; } function GetClassName(obj) { for (const key in RegisteredTypes) { if (obj instanceof RegisteredTypes[key] && !key.includes("Abstract")) { return key; } } return "Unknown"; } var RegisteredTypes; var init_typeStore = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/typeStore.js"() { RegisteredTypes = {}; __name(RegisterClass, "RegisterClass"); __name(GetClass, "GetClass"); __name(GetClassName, "GetClassName"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/performanceConfigurator.js var PerformanceConfigurator; var init_performanceConfigurator = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/performanceConfigurator.js"() { PerformanceConfigurator = class _PerformanceConfigurator { static { __name(this, "PerformanceConfigurator"); } /** * @internal */ static SetMatrixPrecision(use64bits) { _PerformanceConfigurator.MatrixTrackPrecisionChange = false; if (use64bits && !_PerformanceConfigurator.MatrixUse64Bits) { if (_PerformanceConfigurator.MatrixTrackedMatrices) { for (let m = 0; m < _PerformanceConfigurator.MatrixTrackedMatrices.length; ++m) { const matrix = _PerformanceConfigurator.MatrixTrackedMatrices[m]; const values = matrix._m; matrix._m = new Array(16); for (let i = 0; i < 16; ++i) { matrix._m[i] = values[i]; } } } } _PerformanceConfigurator.MatrixUse64Bits = use64bits; _PerformanceConfigurator.MatrixCurrentType = _PerformanceConfigurator.MatrixUse64Bits ? Array : Float32Array; _PerformanceConfigurator.MatrixTrackedMatrices = null; } }; PerformanceConfigurator.MatrixUse64Bits = false; PerformanceConfigurator.MatrixTrackPrecisionChange = true; PerformanceConfigurator.MatrixCurrentType = Float32Array; PerformanceConfigurator.MatrixTrackedMatrices = []; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/observable.js var IsWeakRefSupported, EventState, Observer, Observable; var init_observable = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/observable.js"() { IsWeakRefSupported = typeof WeakRef !== "undefined"; EventState = class { static { __name(this, "EventState"); } /** * Create a new EventState * @param mask defines the mask associated with this state * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true * @param target defines the original target of the state * @param currentTarget defines the current target of the state */ constructor(mask, skipNextObservers = false, target, currentTarget) { this.initialize(mask, skipNextObservers, target, currentTarget); } /** * Initialize the current event state * @param mask defines the mask associated with this state * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true * @param target defines the original target of the state * @param currentTarget defines the current target of the state * @returns the current event state */ initialize(mask, skipNextObservers = false, target, currentTarget) { this.mask = mask; this.skipNextObservers = skipNextObservers; this.target = target; this.currentTarget = currentTarget; return this; } }; Observer = class { static { __name(this, "Observer"); } /** * Creates a new observer * @param callback defines the callback to call when the observer is notified * @param mask defines the mask of the observer (used to filter notifications) * @param scope defines the current scope used to restore the JS context */ constructor(callback, mask, scope = null) { this.callback = callback; this.mask = mask; this.scope = scope; this._willBeUnregistered = false; this.unregisterOnNextCall = false; this._remove = null; } /** * Remove the observer from its observable * This can be used instead of using the observable's remove function. * @param defer if true, the removal will be deferred to avoid callback skipping (default: false) */ remove(defer = false) { if (this._remove) { this._remove(defer); } } }; Observable = class _Observable { static { __name(this, "Observable"); } /** * Create an observable from a Promise. * @param promise a promise to observe for fulfillment. * @param onErrorObservable an observable to notify if a promise was rejected. * @returns the new Observable */ static FromPromise(promise, onErrorObservable) { const observable = new _Observable(); promise.then((ret) => { observable.notifyObservers(ret); }).catch((err) => { if (onErrorObservable) { onErrorObservable.notifyObservers(err); } else { throw err; } }); return observable; } /** * Gets the list of observers * Note that observers that were recently deleted may still be present in the list because they are only really deleted on the next javascript tick! */ get observers() { return this._observers; } /** * Creates a new observable * @param onObserverAdded defines a callback to call when a new observer is added * @param notifyIfTriggered If set to true the observable will notify when an observer was added if the observable was already triggered. */ constructor(onObserverAdded, notifyIfTriggered = false) { this.notifyIfTriggered = notifyIfTriggered; this._observers = new Array(); this._numObserversMarkedAsDeleted = 0; this._hasNotified = false; this._eventState = new EventState(0); if (onObserverAdded) { this._onObserverAdded = onObserverAdded; } } add(callback, mask = -1, insertFirst = false, scope = null, unregisterOnFirstCall = false) { if (!callback) { return null; } const observer = new Observer(callback, mask, scope); observer.unregisterOnNextCall = unregisterOnFirstCall; if (insertFirst) { this._observers.unshift(observer); } else { this._observers.push(observer); } if (this._onObserverAdded) { this._onObserverAdded(observer); } if (this._hasNotified && this.notifyIfTriggered) { if (this._lastNotifiedValue !== void 0) { this.notifyObserver(observer, this._lastNotifiedValue); } } const observableWeakRef = IsWeakRefSupported ? new WeakRef(this) : { deref: /* @__PURE__ */ __name(() => this, "deref") }; observer._remove = (defer = false) => { const observable = observableWeakRef.deref(); if (observable) { defer ? observable.remove(observer) : observable._remove(observer); } }; return observer; } addOnce(callback) { return this.add(callback, void 0, void 0, void 0, true); } /** * Remove an Observer from the Observable object * @param observer the instance of the Observer to remove * @returns false if it doesn't belong to this Observable */ remove(observer) { if (!observer) { return false; } observer._remove = null; const index = this._observers.indexOf(observer); if (index !== -1) { this._deferUnregister(observer); return true; } return false; } /** * Remove a callback from the Observable object * @param callback the callback to remove * @param scope optional scope. If used only the callbacks with this scope will be removed * @returns false if it doesn't belong to this Observable */ removeCallback(callback, scope) { for (let index = 0; index < this._observers.length; index++) { const observer = this._observers[index]; if (observer._willBeUnregistered) { continue; } if (observer.callback === callback && (!scope || scope === observer.scope)) { this._deferUnregister(observer); return true; } } return false; } /** * @internal */ _deferUnregister(observer) { if (observer._willBeUnregistered) { return; } this._numObserversMarkedAsDeleted++; observer.unregisterOnNextCall = false; observer._willBeUnregistered = true; setTimeout(() => { this._remove(observer); }, 0); } // This should only be called when not iterating over _observers to avoid callback skipping. // Removes an observer from the _observer Array. _remove(observer, updateCounter = true) { if (!observer) { return false; } const index = this._observers.indexOf(observer); if (index !== -1) { if (updateCounter) { this._numObserversMarkedAsDeleted--; } this._observers.splice(index, 1); return true; } return false; } /** * Moves the observable to the top of the observer list making it get called first when notified * @param observer the observer to move */ makeObserverTopPriority(observer) { this._remove(observer, false); this._observers.unshift(observer); } /** * Moves the observable to the bottom of the observer list making it get called last when notified * @param observer the observer to move */ makeObserverBottomPriority(observer) { this._remove(observer, false); this._observers.push(observer); } /** * Notify all Observers by calling their respective callback with the given data * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute * @param eventData defines the data to send to all observers * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified) * @param target defines the original target of the state * @param currentTarget defines the current target of the state * @param userInfo defines any user info to send to observers * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true) */ notifyObservers(eventData, mask = -1, target, currentTarget, userInfo) { if (this.notifyIfTriggered) { this._hasNotified = true; this._lastNotifiedValue = eventData; } if (!this._observers.length) { return true; } const state = this._eventState; state.mask = mask; state.target = target; state.currentTarget = currentTarget; state.skipNextObservers = false; state.lastReturnValue = eventData; state.userInfo = userInfo; for (const obs of this._observers) { if (obs._willBeUnregistered) { continue; } if (obs.mask & mask) { if (obs.unregisterOnNextCall) { this._deferUnregister(obs); } if (obs.scope) { state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]); } else { state.lastReturnValue = obs.callback(eventData, state); } } if (state.skipNextObservers) { return false; } } return true; } /** * Notify a specific observer * @param observer defines the observer to notify * @param eventData defines the data to be sent to each callback * @param mask is used to filter observers defaults to -1 */ notifyObserver(observer, eventData, mask = -1) { if (this.notifyIfTriggered) { this._hasNotified = true; this._lastNotifiedValue = eventData; } if (observer._willBeUnregistered) { return; } const state = this._eventState; state.mask = mask; state.skipNextObservers = false; if (observer.unregisterOnNextCall) { this._deferUnregister(observer); } observer.callback(eventData, state); } /** * Gets a boolean indicating if the observable has at least one observer * @returns true is the Observable has at least one Observer registered */ hasObservers() { return this._observers.length - this._numObserversMarkedAsDeleted > 0; } /** * Clear the list of observers */ clear() { while (this._observers.length) { const o = this._observers.pop(); if (o) { o._remove = null; } } this._onObserverAdded = null; this._numObserversMarkedAsDeleted = 0; this.cleanLastNotifiedState(); } /** * Clean the last notified state - both the internal last value and the has-notified flag */ cleanLastNotifiedState() { this._hasNotified = false; this._lastNotifiedValue = void 0; } /** * Clone the current observable * @returns a new observable */ clone() { const result = new _Observable(); result._observers = this._observers.slice(0); return result; } /** * Does this observable handles observer registered with a given mask * @param mask defines the mask to be tested * @returns whether or not one observer registered with the given mask is handled **/ hasSpecificMask(mask = -1) { for (const obs of this._observers) { if (obs.mask & mask || obs.mask === mask) { return true; } } return false; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/engineStore.js var EngineStore; var init_engineStore = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/engineStore.js"() { init_observable(); EngineStore = class { static { __name(this, "EngineStore"); } /** * Gets the latest created engine */ static get LastCreatedEngine() { if (this.Instances.length === 0) { return null; } return this.Instances[this.Instances.length - 1]; } /** * Gets the latest created scene */ static get LastCreatedScene() { return this._LastCreatedScene; } }; EngineStore.Instances = []; EngineStore.OnEnginesDisposedObservable = new Observable(); EngineStore._LastCreatedScene = null; EngineStore.UseFallbackTexture = true; EngineStore.FallbackTexture = ""; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.scalar.functions.js function ExtractAsInt(value) { return parseInt(value.toString().replace(/\W/g, "")); } function WithinEpsilon(a, b, epsilon = 1401298e-51) { return Math.abs(a - b) <= epsilon; } function OutsideRange(num, min, max, epsilon = 1401298e-51) { return num < min - epsilon || num > max + epsilon; } function RandomRange(min, max) { if (min === max) { return min; } return Math.random() * (max - min) + min; } function Lerp(start, end, amount) { return start + (end - start) * amount; } function LerpAngle(start, end, amount) { let num = Repeat(end - start, 360); if (num > 180) { num -= 360; } return start + num * Clamp(amount); } function InverseLerp(a, b, value) { let result = 0; if (a != b) { result = Clamp((value - a) / (b - a)); } else { result = 0; } return result; } function Hermite(value1, tangent1, value2, tangent2, amount) { const squared = amount * amount; const cubed = amount * squared; const part1 = 2 * cubed - 3 * squared + 1; const part2 = -2 * cubed + 3 * squared; const part3 = cubed - 2 * squared + amount; const part4 = cubed - squared; return value1 * part1 + value2 * part2 + tangent1 * part3 + tangent2 * part4; } function Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { const t2 = time * time; return (t2 - time) * 6 * value1 + (3 * t2 - 4 * time + 1) * tangent1 + (-t2 + time) * 6 * value2 + (3 * t2 - 2 * time) * tangent2; } function Clamp(value, min = 0, max = 1) { return Math.min(max, Math.max(min, value)); } function NormalizeRadians(angle) { angle -= Math.PI * 2 * Math.floor((angle + Math.PI) / (Math.PI * 2)); return angle; } function ToHex(i) { const str = i.toString(16); if (i <= 15) { return ("0" + str).toUpperCase(); } return str.toUpperCase(); } function ILog2(value) { if (Math.log2) { return Math.floor(Math.log2(value)); } if (value < 0) { return NaN; } else if (value === 0) { return -Infinity; } let n = 0; if (value < 1) { while (value < 1) { n++; value = value * 2; } n = -n; } else if (value > 1) { while (value > 1) { n++; value = Math.floor(value / 2); } } return n; } function Repeat(value, length) { return value - Math.floor(value / length) * length; } function Normalize(value, min, max) { return (value - min) / (max - min); } function Denormalize(normalized, min, max) { return normalized * (max - min) + min; } function DeltaAngle(current, target) { let num = Repeat(target - current, 360); if (num > 180) { num -= 360; } return num; } function PingPong(tx, length) { const t = Repeat(tx, length * 2); return length - Math.abs(t - length); } function SmoothStep(from, to, tx) { let t = Clamp(tx); t = -2 * t * t * t + 3 * t * t; return to * t + from * (1 - t); } function MoveTowards(current, target, maxDelta) { let result = 0; if (Math.abs(target - current) <= maxDelta) { result = target; } else { result = current + Math.sign(target - current) * maxDelta; } return result; } function MoveTowardsAngle(current, target, maxDelta) { const num = DeltaAngle(current, target); let result = 0; if (-maxDelta < num && num < maxDelta) { result = target; } else { target = current + num; result = MoveTowards(current, target, maxDelta); } return result; } function RangeToPercent(number, min, max) { return (number - min) / (max - min); } function PercentToRange(percent, min, max) { return (max - min) * percent + min; } function HighestCommonFactor(a, b) { const r = a % b; if (r === 0) { return b; } return HighestCommonFactor(b, r); } var init_math_scalar_functions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.scalar.functions.js"() { __name(ExtractAsInt, "ExtractAsInt"); __name(WithinEpsilon, "WithinEpsilon"); __name(OutsideRange, "OutsideRange"); __name(RandomRange, "RandomRange"); __name(Lerp, "Lerp"); __name(LerpAngle, "LerpAngle"); __name(InverseLerp, "InverseLerp"); __name(Hermite, "Hermite"); __name(Hermite1stDerivative, "Hermite1stDerivative"); __name(Clamp, "Clamp"); __name(NormalizeRadians, "NormalizeRadians"); __name(ToHex, "ToHex"); __name(ILog2, "ILog2"); __name(Repeat, "Repeat"); __name(Normalize, "Normalize"); __name(Denormalize, "Denormalize"); __name(DeltaAngle, "DeltaAngle"); __name(PingPong, "PingPong"); __name(SmoothStep, "SmoothStep"); __name(MoveTowards, "MoveTowards"); __name(MoveTowardsAngle, "MoveTowardsAngle"); __name(RangeToPercent, "RangeToPercent"); __name(PercentToRange, "PercentToRange"); __name(HighestCommonFactor, "HighestCommonFactor"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/ThinMaths/thinMath.matrix.functions.js function SetMatrixData(result, m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15) { const mat = result.asArray(); mat[0] = m0; mat[1] = m1; mat[2] = m2; mat[3] = m3; mat[4] = m4; mat[5] = m5; mat[6] = m6; mat[7] = m7; mat[8] = m8; mat[9] = m9; mat[10] = m10; mat[11] = m11; mat[12] = m12; mat[13] = m13; mat[14] = m14; mat[15] = m15; MarkAsDirty(result); } function MarkAsDirty(matrix) { matrix.updateFlag = MatrixManagement._UpdateFlagSeed++; } function IdentityMatrixToRef(result) { SetMatrixData(result, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } function TranslationMatrixToRef(x, y, z, result) { SetMatrixData(result, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1); } function ScalingMatrixToRef(x, y, z, result) { SetMatrixData(result, x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1); } function MultiplyMatricesToArray(a, b, output, offset = 0) { const m = a.asArray(); const otherM = b.asArray(); const tm0 = m[0], tm1 = m[1], tm2 = m[2], tm3 = m[3]; const tm4 = m[4], tm5 = m[5], tm6 = m[6], tm7 = m[7]; const tm8 = m[8], tm9 = m[9], tm10 = m[10], tm11 = m[11]; const tm12 = m[12], tm13 = m[13], tm14 = m[14], tm15 = m[15]; const om0 = otherM[0], om1 = otherM[1], om2 = otherM[2], om3 = otherM[3]; const om4 = otherM[4], om5 = otherM[5], om6 = otherM[6], om7 = otherM[7]; const om8 = otherM[8], om9 = otherM[9], om10 = otherM[10], om11 = otherM[11]; const om12 = otherM[12], om13 = otherM[13], om14 = otherM[14], om15 = otherM[15]; output[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12; output[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13; output[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14; output[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15; output[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12; output[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13; output[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14; output[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15; output[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12; output[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13; output[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14; output[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15; output[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12; output[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13; output[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14; output[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15; } function MultiplyMatricesToRef(a, b, result, offset = 0) { MultiplyMatricesToArray(a, b, result.asArray(), offset); MarkAsDirty(result); } function CopyMatrixToRef(matrix, target) { CopyMatrixToArray(matrix, target.asArray()); MarkAsDirty(target); } function CopyMatrixToArray(matrix, array, offset = 0) { const source = matrix.asArray(); array[offset] = source[0]; array[offset + 1] = source[1]; array[offset + 2] = source[2]; array[offset + 3] = source[3]; array[offset + 4] = source[4]; array[offset + 5] = source[5]; array[offset + 6] = source[6]; array[offset + 7] = source[7]; array[offset + 8] = source[8]; array[offset + 9] = source[9]; array[offset + 10] = source[10]; array[offset + 11] = source[11]; array[offset + 12] = source[12]; array[offset + 13] = source[13]; array[offset + 14] = source[14]; array[offset + 15] = source[15]; } function InvertMatrixToRef(source, target) { const result = InvertMatrixToArray(source, target.asArray()); if (result) { MarkAsDirty(target); } return result; } function InvertMatrixToArray(source, target) { const m = source.asArray(); const m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3]; const m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7]; const m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11]; const m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15]; const det_22_33 = m22 * m33 - m32 * m23; const det_21_33 = m21 * m33 - m31 * m23; const det_21_32 = m21 * m32 - m31 * m22; const det_20_33 = m20 * m33 - m30 * m23; const det_20_32 = m20 * m32 - m22 * m30; const det_20_31 = m20 * m31 - m30 * m21; const cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32); const cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32); const cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31); const cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31); const det = m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03; if (det === 0) { return false; } const detInv = 1 / det; const det_12_33 = m12 * m33 - m32 * m13; const det_11_33 = m11 * m33 - m31 * m13; const det_11_32 = m11 * m32 - m31 * m12; const det_10_33 = m10 * m33 - m30 * m13; const det_10_32 = m10 * m32 - m30 * m12; const det_10_31 = m10 * m31 - m30 * m11; const det_12_23 = m12 * m23 - m22 * m13; const det_11_23 = m11 * m23 - m21 * m13; const det_11_22 = m11 * m22 - m21 * m12; const det_10_23 = m10 * m23 - m20 * m13; const det_10_22 = m10 * m22 - m20 * m12; const det_10_21 = m10 * m21 - m20 * m11; const cofact_10 = -(m01 * det_22_33 - m02 * det_21_33 + m03 * det_21_32); const cofact_11 = +(m00 * det_22_33 - m02 * det_20_33 + m03 * det_20_32); const cofact_12 = -(m00 * det_21_33 - m01 * det_20_33 + m03 * det_20_31); const cofact_13 = +(m00 * det_21_32 - m01 * det_20_32 + m02 * det_20_31); const cofact_20 = +(m01 * det_12_33 - m02 * det_11_33 + m03 * det_11_32); const cofact_21 = -(m00 * det_12_33 - m02 * det_10_33 + m03 * det_10_32); const cofact_22 = +(m00 * det_11_33 - m01 * det_10_33 + m03 * det_10_31); const cofact_23 = -(m00 * det_11_32 - m01 * det_10_32 + m02 * det_10_31); const cofact_30 = -(m01 * det_12_23 - m02 * det_11_23 + m03 * det_11_22); const cofact_31 = +(m00 * det_12_23 - m02 * det_10_23 + m03 * det_10_22); const cofact_32 = -(m00 * det_11_23 - m01 * det_10_23 + m03 * det_10_21); const cofact_33 = +(m00 * det_11_22 - m01 * det_10_22 + m02 * det_10_21); target[0] = cofact_00 * detInv; target[1] = cofact_10 * detInv; target[2] = cofact_20 * detInv; target[3] = cofact_30 * detInv; target[4] = cofact_01 * detInv; target[5] = cofact_11 * detInv; target[6] = cofact_21 * detInv; target[7] = cofact_31 * detInv; target[8] = cofact_02 * detInv; target[9] = cofact_12 * detInv; target[10] = cofact_22 * detInv; target[11] = cofact_32 * detInv; target[12] = cofact_03 * detInv; target[13] = cofact_13 * detInv; target[14] = cofact_23 * detInv; target[15] = cofact_33 * detInv; return true; } var MatrixManagement; var init_thinMath_matrix_functions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/ThinMaths/thinMath.matrix.functions.js"() { MatrixManagement = class { static { __name(this, "MatrixManagement"); } }; MatrixManagement._UpdateFlagSeed = 0; __name(SetMatrixData, "SetMatrixData"); __name(MarkAsDirty, "MarkAsDirty"); __name(IdentityMatrixToRef, "IdentityMatrixToRef"); __name(TranslationMatrixToRef, "TranslationMatrixToRef"); __name(ScalingMatrixToRef, "ScalingMatrixToRef"); __name(MultiplyMatricesToArray, "MultiplyMatricesToArray"); __name(MultiplyMatricesToRef, "MultiplyMatricesToRef"); __name(CopyMatrixToRef, "CopyMatrixToRef"); __name(CopyMatrixToArray, "CopyMatrixToArray"); __name(InvertMatrixToRef, "InvertMatrixToRef"); __name(InvertMatrixToArray, "InvertMatrixToArray"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.vector.js var ExtractAsInt2, Vector2, Vector3, Vector4, Quaternion, Matrix, MathTmp, TmpVectors, mtxConvertNDCToHalfZRange; var init_math_vector = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.vector.js"() { init_math_constants(); init_arrayTools(); init_typeStore(); init_performanceConfigurator(); init_engineStore(); init_math_scalar_functions(); init_thinMath_matrix_functions(); ExtractAsInt2 = /* @__PURE__ */ __name((value) => { return parseInt(value.toString().replace(/\W/g, "")); }, "ExtractAsInt"); Vector2 = class _Vector2 { static { __name(this, "Vector2"); } /** * Creates a new Vector2 from the given x and y coordinates * @param x defines the first coordinate * @param y defines the second coordinate */ constructor(x = 0, y = 0) { this.x = x; this.y = y; } /** * Gets a string with the Vector2 coordinates * @returns a string with the Vector2 coordinates */ toString() { return `{X: ${this.x} Y: ${this.y}}`; } /** * Gets class name * @returns the string "Vector2" */ getClassName() { return "Vector2"; } /** * Gets current vector hash code * @returns the Vector2 hash code as a number */ getHashCode() { const x = ExtractAsInt2(this.x); const y = ExtractAsInt2(this.y); let hash = x; hash = hash * 397 ^ y; return hash; } // Operators /** * Sets the Vector2 coordinates in the given array or Float32Array from the given index. * Example Playground https://playground.babylonjs.com/#QYBWV4#15 * @param array defines the source array * @param index defines the offset in source array * @returns the current Vector2 */ toArray(array, index = 0) { array[index] = this.x; array[index + 1] = this.y; return this; } /** * Update the current vector from an array * Example Playground https://playground.babylonjs.com/#QYBWV4#39 * @param array defines the destination array * @param offset defines the offset in the destination array * @returns the current Vector2 */ fromArray(array, offset = 0) { _Vector2.FromArrayToRef(array, offset, this); return this; } /** * Copy the current vector to an array * Example Playground https://playground.babylonjs.com/#QYBWV4#40 * @returns a new array with 2 elements: the Vector2 coordinates. */ asArray() { return [this.x, this.y]; } /** * Sets the Vector2 coordinates with the given Vector2 coordinates * Example Playground https://playground.babylonjs.com/#QYBWV4#24 * @param source defines the source Vector2 * @returns the current updated Vector2 */ copyFrom(source) { this.x = source.x; this.y = source.y; return this; } /** * Sets the Vector2 coordinates with the given floats * Example Playground https://playground.babylonjs.com/#QYBWV4#25 * @param x defines the first coordinate * @param y defines the second coordinate * @returns the current updated Vector2 */ copyFromFloats(x, y) { this.x = x; this.y = y; return this; } /** * Sets the Vector2 coordinates with the given floats * Example Playground https://playground.babylonjs.com/#QYBWV4#62 * @param x defines the first coordinate * @param y defines the second coordinate * @returns the current updated Vector2 */ set(x, y) { return this.copyFromFloats(x, y); } /** * Copies the given float to the current Vector2 coordinates * @param v defines the x and y coordinates of the operand * @returns the current updated Vector2 */ setAll(v) { return this.copyFromFloats(v, v); } /** * Add another vector with the current one * Example Playground https://playground.babylonjs.com/#QYBWV4#11 * @param otherVector defines the other vector * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates */ add(otherVector) { return new _Vector2(this.x + otherVector.x, this.y + otherVector.y); } /** * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates * Example Playground https://playground.babylonjs.com/#QYBWV4#12 * @param otherVector defines the other vector * @param result defines the target vector * @returns result input */ addToRef(otherVector, result) { result.x = this.x + otherVector.x; result.y = this.y + otherVector.y; return result; } /** * Set the Vector2 coordinates by adding the given Vector2 coordinates * Example Playground https://playground.babylonjs.com/#QYBWV4#13 * @param otherVector defines the other vector * @returns the current updated Vector2 */ addInPlace(otherVector) { this.x += otherVector.x; this.y += otherVector.y; return this; } /** * Adds the given coordinates to the current Vector2 * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @returns the current updated Vector2 */ addInPlaceFromFloats(x, y) { this.x += x; this.y += y; return this; } /** * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates * Example Playground https://playground.babylonjs.com/#QYBWV4#14 * @param otherVector defines the other vector * @returns a new Vector2 */ addVector3(otherVector) { return new _Vector2(this.x + otherVector.x, this.y + otherVector.y); } /** * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2 * Example Playground https://playground.babylonjs.com/#QYBWV4#61 * @param otherVector defines the other vector * @returns a new Vector2 */ subtract(otherVector) { return new _Vector2(this.x - otherVector.x, this.y - otherVector.y); } /** * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates. * Example Playground https://playground.babylonjs.com/#QYBWV4#63 * @param otherVector defines the other vector * @param result defines the target vector * @returns result input */ subtractToRef(otherVector, result) { result.x = this.x - otherVector.x; result.y = this.y - otherVector.y; return result; } /** * Sets the current Vector2 coordinates by subtracting from it the given one coordinates * Example Playground https://playground.babylonjs.com/#QYBWV4#88 * @param otherVector defines the other vector * @returns the current updated Vector2 */ subtractInPlace(otherVector) { this.x -= otherVector.x; this.y -= otherVector.y; return this; } /** * Multiplies in place the current Vector2 coordinates by the given ones * Example Playground https://playground.babylonjs.com/#QYBWV4#43 * @param otherVector defines the other vector * @returns the current updated Vector2 */ multiplyInPlace(otherVector) { this.x *= otherVector.x; this.y *= otherVector.y; return this; } /** * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates * Example Playground https://playground.babylonjs.com/#QYBWV4#42 * @param otherVector defines the other vector * @returns a new Vector2 */ multiply(otherVector) { return new _Vector2(this.x * otherVector.x, this.y * otherVector.y); } /** * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates * Example Playground https://playground.babylonjs.com/#QYBWV4#44 * @param otherVector defines the other vector * @param result defines the target vector * @returns result input */ multiplyToRef(otherVector, result) { result.x = this.x * otherVector.x; result.y = this.y * otherVector.y; return result; } /** * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats * Example Playground https://playground.babylonjs.com/#QYBWV4#89 * @param x defines the first coordinate * @param y defines the second coordinate * @returns a new Vector2 */ multiplyByFloats(x, y) { return new _Vector2(this.x * x, this.y * y); } /** * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates * Example Playground https://playground.babylonjs.com/#QYBWV4#27 * @param otherVector defines the other vector * @returns a new Vector2 */ divide(otherVector) { return new _Vector2(this.x / otherVector.x, this.y / otherVector.y); } /** * Sets the "result" coordinates with the Vector2 divided by the given one coordinates * Example Playground https://playground.babylonjs.com/#QYBWV4#30 * @param otherVector defines the other vector * @param result defines the target vector * @returns result input */ divideToRef(otherVector, result) { result.x = this.x / otherVector.x; result.y = this.y / otherVector.y; return result; } /** * Divides the current Vector2 coordinates by the given ones * Example Playground https://playground.babylonjs.com/#QYBWV4#28 * @param otherVector defines the other vector * @returns the current updated Vector2 */ divideInPlace(otherVector) { this.x = this.x / otherVector.x; this.y = this.y / otherVector.y; return this; } /** * Updates the current Vector2 with the minimal coordinate values between its and the given vector ones * @param other defines the second operand * @returns the current updated Vector2 */ minimizeInPlace(other) { return this.minimizeInPlaceFromFloats(other.x, other.y); } /** * Updates the current Vector2 with the maximal coordinate values between its and the given vector ones. * @param other defines the second operand * @returns the current updated Vector2 */ maximizeInPlace(other) { return this.maximizeInPlaceFromFloats(other.x, other.y); } /** * Updates the current Vector2 with the minimal coordinate values between its and the given coordinates * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @returns the current updated Vector2 */ minimizeInPlaceFromFloats(x, y) { this.x = Math.min(x, this.x); this.y = Math.min(y, this.y); return this; } /** * Updates the current Vector2 with the maximal coordinate values between its and the given coordinates. * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @returns the current updated Vector2 */ maximizeInPlaceFromFloats(x, y) { this.x = Math.max(x, this.x); this.y = Math.max(y, this.y); return this; } /** * Returns a new Vector2 set with the subtraction of the given floats from the current Vector2 coordinates * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @returns the resulting Vector2 */ subtractFromFloats(x, y) { return new _Vector2(this.x - x, this.y - y); } /** * Subtracts the given floats from the current Vector2 coordinates and set the given vector "result" with this result * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param result defines the Vector2 object where to store the result * @returns the result */ subtractFromFloatsToRef(x, y, result) { result.x = this.x - x; result.y = this.y - y; return result; } /** * Gets a new Vector2 with current Vector2 negated coordinates * @returns a new Vector2 */ negate() { return new _Vector2(-this.x, -this.y); } /** * Negate this vector in place * Example Playground https://playground.babylonjs.com/#QYBWV4#23 * @returns this */ negateInPlace() { this.x *= -1; this.y *= -1; return this; } /** * Negate the current Vector2 and stores the result in the given vector "result" coordinates * Example Playground https://playground.babylonjs.com/#QYBWV4#41 * @param result defines the Vector2 object where to store the result * @returns the result */ negateToRef(result) { result.x = -this.x; result.y = -this.y; return result; } /** * Multiply the Vector2 coordinates by * Example Playground https://playground.babylonjs.com/#QYBWV4#59 * @param scale defines the scaling factor * @returns the current updated Vector2 */ scaleInPlace(scale) { this.x *= scale; this.y *= scale; return this; } /** * Returns a new Vector2 scaled by "scale" from the current Vector2 * Example Playground https://playground.babylonjs.com/#QYBWV4#52 * @param scale defines the scaling factor * @returns a new Vector2 */ scale(scale) { return new _Vector2(this.x * scale, this.y * scale); } /** * Scale the current Vector2 values by a factor to a given Vector2 * Example Playground https://playground.babylonjs.com/#QYBWV4#57 * @param scale defines the scale factor * @param result defines the Vector2 object where to store the result * @returns result input */ scaleToRef(scale, result) { result.x = this.x * scale; result.y = this.y * scale; return result; } /** * Scale the current Vector2 values by a factor and add the result to a given Vector2 * Example Playground https://playground.babylonjs.com/#QYBWV4#58 * @param scale defines the scale factor * @param result defines the Vector2 object where to store the result * @returns result input */ scaleAndAddToRef(scale, result) { result.x += this.x * scale; result.y += this.y * scale; return result; } /** * Gets a boolean if two vectors are equals * Example Playground https://playground.babylonjs.com/#QYBWV4#31 * @param otherVector defines the other vector * @returns true if the given vector coordinates strictly equal the current Vector2 ones */ equals(otherVector) { return otherVector && this.x === otherVector.x && this.y === otherVector.y; } /** * Gets a boolean if two vectors are equals (using an epsilon value) * Example Playground https://playground.babylonjs.com/#QYBWV4#32 * @param otherVector defines the other vector * @param epsilon defines the minimal distance to consider equality * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon. */ equalsWithEpsilon(otherVector, epsilon = Epsilon) { return otherVector && WithinEpsilon(this.x, otherVector.x, epsilon) && WithinEpsilon(this.y, otherVector.y, epsilon); } /** * Returns true if the current Vector2 coordinates equals the given floats * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @returns true if both vectors are equal */ equalsToFloats(x, y) { return this.x === x && this.y === y; } /** * Gets a new Vector2 from current Vector2 floored values * Example Playground https://playground.babylonjs.com/#QYBWV4#35 * eg (1.2, 2.31) returns (1, 2) * @returns a new Vector2 */ floor() { return new _Vector2(Math.floor(this.x), Math.floor(this.y)); } /** * Gets the current Vector2's floored values and stores them in result * @param result the Vector2 to store the result in * @returns the result Vector2 */ floorToRef(result) { result.x = Math.floor(this.x); result.y = Math.floor(this.y); return result; } /** * Gets a new Vector2 from current Vector2 fractional values * Example Playground https://playground.babylonjs.com/#QYBWV4#34 * eg (1.2, 2.31) returns (0.2, 0.31) * @returns a new Vector2 */ fract() { return new _Vector2(this.x - Math.floor(this.x), this.y - Math.floor(this.y)); } /** * Gets the current Vector2's fractional values and stores them in result * @param result the Vector2 to store the result in * @returns the result Vector2 */ fractToRef(result) { result.x = this.x - Math.floor(this.x); result.y = this.y - Math.floor(this.y); return result; } /** * Gets a new Vector2 rotated by the given angle * @param angle defines the rotation angle * @returns a new Vector2 */ rotate(angle) { return this.rotateToRef(angle, new _Vector2()); } /** * Rotate the current vector into a given result vector * Example Playground https://playground.babylonjs.com/#QYBWV4#49 * @param angle defines the rotation angle * @param result defines the result vector where to store the rotated vector * @returns result input */ rotateToRef(angle, result) { const cos = Math.cos(angle); const sin = Math.sin(angle); result.x = cos * this.x - sin * this.y; result.y = sin * this.x + cos * this.y; return result; } // Properties /** * Gets the length of the vector * @returns the vector length (float) */ length() { return Math.sqrt(this.x * this.x + this.y * this.y); } /** * Gets the vector squared length * @returns the vector squared length (float) */ lengthSquared() { return this.x * this.x + this.y * this.y; } // Methods /** * Normalize the vector * Example Playground https://playground.babylonjs.com/#QYBWV4#48 * @returns the current updated Vector2 */ normalize() { return this.normalizeFromLength(this.length()); } /** * Normalize the current Vector2 with the given input length. * Please note that this is an in place operation. * @param len the length of the vector * @returns the current updated Vector2 */ normalizeFromLength(len) { if (len === 0 || len === 1) { return this; } return this.scaleInPlace(1 / len); } /** * Normalize the current Vector2 to a new vector * @returns the new Vector2 */ normalizeToNew() { const normalized = new _Vector2(); this.normalizeToRef(normalized); return normalized; } /** * Normalize the current Vector2 to the reference * @param result define the Vector to update * @returns the updated Vector2 */ normalizeToRef(result) { const len = this.length(); if (len === 0) { result.x = this.x; result.y = this.y; } return this.scaleToRef(1 / len, result); } /** * Gets a new Vector2 copied from the Vector2 * Example Playground https://playground.babylonjs.com/#QYBWV4#20 * @returns a new Vector2 */ clone() { return new _Vector2(this.x, this.y); } /** * Gets the dot product of the current vector and the vector "otherVector" * @param otherVector defines second vector * @returns the dot product (float) */ dot(otherVector) { return this.x * otherVector.x + this.y * otherVector.y; } // Statics /** * Gets a new Vector2(0, 0) * @returns a new Vector2 */ static Zero() { return new _Vector2(0, 0); } /** * Gets a new Vector2(1, 1) * @returns a new Vector2 */ static One() { return new _Vector2(1, 1); } /** * Returns a new Vector2 with random values between min and max * @param min the minimum random value * @param max the maximum random value * @returns a Vector2 with random values between min and max */ static Random(min = 0, max = 1) { return new _Vector2(RandomRange(min, max), RandomRange(min, max)); } /** * Sets a Vector2 with random values between min and max * @param min the minimum random value * @param max the maximum random value * @param ref the ref to store the values in * @returns the ref with random values between min and max */ static RandomToRef(min = 0, max = 1, ref) { return ref.copyFromFloats(RandomRange(min, max), RandomRange(min, max)); } /** * Gets a zero Vector2 that must not be updated */ static get ZeroReadOnly() { return _Vector2._ZeroReadOnly; } /** * Gets a new Vector2 set from the given index element of the given array * Example Playground https://playground.babylonjs.com/#QYBWV4#79 * @param array defines the data source * @param offset defines the offset in the data source * @returns a new Vector2 */ static FromArray(array, offset = 0) { return new _Vector2(array[offset], array[offset + 1]); } /** * Sets "result" from the given index element of the given array * Example Playground https://playground.babylonjs.com/#QYBWV4#80 * @param array defines the data source * @param offset defines the offset in the data source * @param result defines the target vector * @returns result input */ static FromArrayToRef(array, offset, result) { result.x = array[offset]; result.y = array[offset + 1]; return result; } /** * Sets the given vector "result" with the given floats. * @param x defines the x coordinate of the source * @param y defines the y coordinate of the source * @param result defines the Vector2 where to store the result * @returns the result vector */ static FromFloatsToRef(x, y, result) { result.copyFromFloats(x, y); return result; } /** * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2 * Example Playground https://playground.babylonjs.com/#QYBWV4#65 * @param value1 defines 1st point of control * @param value2 defines 2nd point of control * @param value3 defines 3rd point of control * @param value4 defines 4th point of control * @param amount defines the interpolation factor * @returns a new Vector2 */ static CatmullRom(value1, value2, value3, value4, amount) { const squared = amount * amount; const cubed = amount * squared; const x = 0.5 * (2 * value2.x + (-value1.x + value3.x) * amount + (2 * value1.x - 5 * value2.x + 4 * value3.x - value4.x) * squared + (-value1.x + 3 * value2.x - 3 * value3.x + value4.x) * cubed); const y = 0.5 * (2 * value2.y + (-value1.y + value3.y) * amount + (2 * value1.y - 5 * value2.y + 4 * value3.y - value4.y) * squared + (-value1.y + 3 * value2.y - 3 * value3.y + value4.y) * cubed); return new _Vector2(x, y); } /** * Sets reference with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max". * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate * @param value defines the value to clamp * @param min defines the lower limit * @param max defines the upper limit * @param ref the reference * @returns the reference */ static ClampToRef(value, min, max, ref) { ref.x = Clamp(value.x, min.x, max.x); ref.y = Clamp(value.y, min.y, max.y); return ref; } /** * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max". * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate * Example Playground https://playground.babylonjs.com/#QYBWV4#76 * @param value defines the value to clamp * @param min defines the lower limit * @param max defines the upper limit * @returns a new Vector2 */ static Clamp(value, min, max) { const x = Clamp(value.x, min.x, max.x); const y = Clamp(value.y, min.y, max.y); return new _Vector2(x, y); } /** * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2" * Example Playground https://playground.babylonjs.com/#QYBWV4#81 * @param value1 defines the 1st control point * @param tangent1 defines the outgoing tangent * @param value2 defines the 2nd control point * @param tangent2 defines the incoming tangent * @param amount defines the interpolation factor * @returns a new Vector2 */ static Hermite(value1, tangent1, value2, tangent2, amount) { const squared = amount * amount; const cubed = amount * squared; const part1 = 2 * cubed - 3 * squared + 1; const part2 = -2 * cubed + 3 * squared; const part3 = cubed - 2 * squared + amount; const part4 = cubed - squared; const x = value1.x * part1 + value2.x * part2 + tangent1.x * part3 + tangent2.x * part4; const y = value1.y * part1 + value2.y * part2 + tangent1.y * part3 + tangent2.y * part4; return new _Vector2(x, y); } /** * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2". * Example Playground https://playground.babylonjs.com/#QYBWV4#82 * @param value1 defines the first control point * @param tangent1 defines the first tangent * @param value2 defines the second control point * @param tangent2 defines the second tangent * @param time define where the derivative must be done * @returns 1st derivative */ static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { return this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, new _Vector2()); } /** * Returns a new Vector2 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2". * Example Playground https://playground.babylonjs.com/#QYBWV4#83 * @param value1 defines the first control point * @param tangent1 defines the first tangent * @param value2 defines the second control point * @param tangent2 defines the second tangent * @param time define where the derivative must be done * @param result define where the derivative will be stored * @returns result input */ static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { const t2 = time * time; result.x = (t2 - time) * 6 * value1.x + (3 * t2 - 4 * time + 1) * tangent1.x + (-t2 + time) * 6 * value2.x + (3 * t2 - 2 * time) * tangent2.x; result.y = (t2 - time) * 6 * value1.y + (3 * t2 - 4 * time + 1) * tangent1.y + (-t2 + time) * 6 * value2.y + (3 * t2 - 2 * time) * tangent2.y; return result; } /** * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end". * Example Playground https://playground.babylonjs.com/#QYBWV4#84 * @param start defines the start vector * @param end defines the end vector * @param amount defines the interpolation factor * @returns a new Vector2 */ static Lerp(start, end, amount) { return _Vector2.LerpToRef(start, end, amount, new _Vector2()); } /** * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end" * @param start defines the start value * @param end defines the end value * @param amount max defines amount between both (between 0 and 1) * @param result defines the Vector2 where to store the result * @returns result input */ static LerpToRef(start, end, amount, result) { result.x = start.x + (end.x - start.x) * amount; result.y = start.y + (end.y - start.y) * amount; return result; } /** * Gets the dot product of the vector "left" and the vector "right" * Example Playground https://playground.babylonjs.com/#QYBWV4#90 * @param left defines first vector * @param right defines second vector * @returns the dot product (float) */ static Dot(left, right) { return left.x * right.x + left.y * right.y; } /** * Returns a new Vector2 equal to the normalized given vector * Example Playground https://playground.babylonjs.com/#QYBWV4#46 * @param vector defines the vector to normalize * @returns a new Vector2 */ static Normalize(vector) { return _Vector2.NormalizeToRef(vector, new _Vector2()); } /** * Normalize a given vector into a second one * Example Playground https://playground.babylonjs.com/#QYBWV4#50 * @param vector defines the vector to normalize * @param result defines the vector where to store the result * @returns result input */ static NormalizeToRef(vector, result) { vector.normalizeToRef(result); return result; } /** * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors * Example Playground https://playground.babylonjs.com/#QYBWV4#86 * @param left defines 1st vector * @param right defines 2nd vector * @returns a new Vector2 */ static Minimize(left, right) { const x = left.x < right.x ? left.x : right.x; const y = left.y < right.y ? left.y : right.y; return new _Vector2(x, y); } /** * Gets a new Vector2 set with the maximal coordinate values from the "left" and "right" vectors * Example Playground https://playground.babylonjs.com/#QYBWV4#86 * @param left defines 1st vector * @param right defines 2nd vector * @returns a new Vector2 */ static Maximize(left, right) { const x = left.x > right.x ? left.x : right.x; const y = left.y > right.y ? left.y : right.y; return new _Vector2(x, y); } /** * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix * Example Playground https://playground.babylonjs.com/#QYBWV4#17 * @param vector defines the vector to transform * @param transformation defines the matrix to apply * @returns a new Vector2 */ static Transform(vector, transformation) { return _Vector2.TransformToRef(vector, transformation, new _Vector2()); } /** * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates * Example Playground https://playground.babylonjs.com/#QYBWV4#19 * @param vector defines the vector to transform * @param transformation defines the matrix to apply * @param result defines the target vector * @returns result input */ static TransformToRef(vector, transformation, result) { const m = transformation.m; const x = vector.x * m[0] + vector.y * m[4] + m[12]; const y = vector.x * m[1] + vector.y * m[5] + m[13]; result.x = x; result.y = y; return result; } /** * Determines if a given vector is included in a triangle * Example Playground https://playground.babylonjs.com/#QYBWV4#87 * @param p defines the vector to test * @param p0 defines 1st triangle point * @param p1 defines 2nd triangle point * @param p2 defines 3rd triangle point * @returns true if the point "p" is in the triangle defined by the vectors "p0", "p1", "p2" */ static PointInTriangle(p, p0, p1, p2) { const a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y); const sign = a < 0 ? -1 : 1; const s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign; const t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign; return s > 0 && t > 0 && s + t < 2 * a * sign; } /** * Gets the distance between the vectors "value1" and "value2" * Example Playground https://playground.babylonjs.com/#QYBWV4#71 * @param value1 defines first vector * @param value2 defines second vector * @returns the distance between vectors */ static Distance(value1, value2) { return Math.sqrt(_Vector2.DistanceSquared(value1, value2)); } /** * Returns the squared distance between the vectors "value1" and "value2" * Example Playground https://playground.babylonjs.com/#QYBWV4#72 * @param value1 defines first vector * @param value2 defines second vector * @returns the squared distance between vectors */ static DistanceSquared(value1, value2) { const x = value1.x - value2.x; const y = value1.y - value2.y; return x * x + y * y; } /** * Gets a new Vector2 located at the center of the vectors "value1" and "value2" * Example Playground https://playground.babylonjs.com/#QYBWV4#86 * Example Playground https://playground.babylonjs.com/#QYBWV4#66 * @param value1 defines first vector * @param value2 defines second vector * @returns a new Vector2 */ static Center(value1, value2) { return _Vector2.CenterToRef(value1, value2, new _Vector2()); } /** * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref" * Example Playground https://playground.babylonjs.com/#QYBWV4#66 * @param value1 defines first vector * @param value2 defines second vector * @param ref defines third vector * @returns ref */ static CenterToRef(value1, value2, ref) { return ref.copyFromFloats((value1.x + value2.x) / 2, (value1.y + value2.y) / 2); } /** * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB". * Example Playground https://playground.babylonjs.com/#QYBWV4#77 * @param p defines the middle point * @param segA defines one point of the segment * @param segB defines the other point of the segment * @returns the shortest distance */ static DistanceOfPointFromSegment(p, segA, segB) { const l2 = _Vector2.DistanceSquared(segA, segB); if (l2 === 0) { return _Vector2.Distance(p, segA); } const v = segB.subtract(segA); const t = Math.max(0, Math.min(1, _Vector2.Dot(p.subtract(segA), v) / l2)); const proj = segA.add(v.multiplyByFloats(t, t)); return _Vector2.Distance(p, proj); } }; Vector2._V8PerformanceHack = new Vector2(0.5, 0.5); Vector2._ZeroReadOnly = Vector2.Zero(); Vector2; Object.defineProperties(Vector2.prototype, { dimension: { value: [2] }, rank: { value: 1 } }); Vector3 = class _Vector3 { static { __name(this, "Vector3"); } /** Gets or sets the x coordinate */ get x() { return this._x; } set x(value) { this._x = value; this._isDirty = true; } /** Gets or sets the y coordinate */ get y() { return this._y; } set y(value) { this._y = value; this._isDirty = true; } /** Gets or sets the z coordinate */ get z() { return this._z; } set z(value) { this._z = value; this._isDirty = true; } /** * Creates a new Vector3 object from the given x, y, z (floats) coordinates. * @param x defines the first coordinates (on X axis) * @param y defines the second coordinates (on Y axis) * @param z defines the third coordinates (on Z axis) */ constructor(x = 0, y = 0, z = 0) { this._isDirty = true; this._x = x; this._y = y; this._z = z; } /** * Creates a string representation of the Vector3 * Example Playground https://playground.babylonjs.com/#R1F8YU#67 * @returns a string with the Vector3 coordinates. */ toString() { return `{X: ${this._x} Y: ${this._y} Z: ${this._z}}`; } /** * Gets the class name * @returns the string "Vector3" */ getClassName() { return "Vector3"; } /** * Creates the Vector3 hash code * @returns a number which tends to be unique between Vector3 instances */ getHashCode() { const x = ExtractAsInt2(this._x); const y = ExtractAsInt2(this._y); const z = ExtractAsInt2(this._z); let hash = x; hash = hash * 397 ^ y; hash = hash * 397 ^ z; return hash; } // Operators /** * Creates an array containing three elements : the coordinates of the Vector3 * Example Playground https://playground.babylonjs.com/#R1F8YU#10 * @returns a new array of numbers */ asArray() { return [this._x, this._y, this._z]; } /** * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3 * Example Playground https://playground.babylonjs.com/#R1F8YU#65 * @param array defines the destination array * @param index defines the offset in the destination array * @returns the current Vector3 */ toArray(array, index = 0) { array[index] = this._x; array[index + 1] = this._y; array[index + 2] = this._z; return this; } /** * Update the current vector from an array * Example Playground https://playground.babylonjs.com/#R1F8YU#24 * @param array defines the destination array * @param offset defines the offset in the destination array * @returns the current Vector3 */ fromArray(array, offset = 0) { _Vector3.FromArrayToRef(array, offset, this); return this; } /** * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation) * Example Playground https://playground.babylonjs.com/#R1F8YU#66 * @returns a new Quaternion object, computed from the Vector3 coordinates */ toQuaternion() { return Quaternion.RotationYawPitchRoll(this._y, this._x, this._z); } /** * Adds the given vector to the current Vector3 * Example Playground https://playground.babylonjs.com/#R1F8YU#4 * @param otherVector defines the second operand * @returns the current updated Vector3 */ addInPlace(otherVector) { this._x += otherVector._x; this._y += otherVector._y; this._z += otherVector._z; this._isDirty = true; return this; } /** * Adds the given coordinates to the current Vector3 * Example Playground https://playground.babylonjs.com/#R1F8YU#5 * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @returns the current updated Vector3 */ addInPlaceFromFloats(x, y, z) { this._x += x; this._y += y; this._z += z; this._isDirty = true; return this; } /** * Gets a new Vector3, result of the addition the current Vector3 and the given vector * Example Playground https://playground.babylonjs.com/#R1F8YU#3 * @param otherVector defines the second operand * @returns the resulting Vector3 */ add(otherVector) { return new _Vector3(this._x + otherVector._x, this._y + otherVector._y, this._z + otherVector._z); } /** * Adds the current Vector3 to the given one and stores the result in the vector "result" * Example Playground https://playground.babylonjs.com/#R1F8YU#6 * @param otherVector defines the second operand * @param result defines the Vector3 object where to store the result * @returns the result */ addToRef(otherVector, result) { result._x = this._x + otherVector._x; result._y = this._y + otherVector._y; result._z = this._z + otherVector._z; result._isDirty = true; return result; } /** * Subtract the given vector from the current Vector3 * Example Playground https://playground.babylonjs.com/#R1F8YU#61 * @param otherVector defines the second operand * @returns the current updated Vector3 */ subtractInPlace(otherVector) { this._x -= otherVector._x; this._y -= otherVector._y; this._z -= otherVector._z; this._isDirty = true; return this; } /** * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3 * Example Playground https://playground.babylonjs.com/#R1F8YU#60 * @param otherVector defines the second operand * @returns the resulting Vector3 */ subtract(otherVector) { return new _Vector3(this._x - otherVector._x, this._y - otherVector._y, this._z - otherVector._z); } /** * Subtracts the given vector from the current Vector3 and stores the result in the vector "result". * Example Playground https://playground.babylonjs.com/#R1F8YU#63 * @param otherVector defines the second operand * @param result defines the Vector3 object where to store the result * @returns the result */ subtractToRef(otherVector, result) { return this.subtractFromFloatsToRef(otherVector._x, otherVector._y, otherVector._z, result); } /** * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates * Example Playground https://playground.babylonjs.com/#R1F8YU#62 * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @returns the resulting Vector3 */ subtractFromFloats(x, y, z) { return new _Vector3(this._x - x, this._y - y, this._z - z); } /** * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result * Example Playground https://playground.babylonjs.com/#R1F8YU#64 * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @param result defines the Vector3 object where to store the result * @returns the result */ subtractFromFloatsToRef(x, y, z, result) { result._x = this._x - x; result._y = this._y - y; result._z = this._z - z; result._isDirty = true; return result; } /** * Gets a new Vector3 set with the current Vector3 negated coordinates * Example Playground https://playground.babylonjs.com/#R1F8YU#35 * @returns a new Vector3 */ negate() { return new _Vector3(-this._x, -this._y, -this._z); } /** * Negate this vector in place * Example Playground https://playground.babylonjs.com/#R1F8YU#36 * @returns this */ negateInPlace() { this._x *= -1; this._y *= -1; this._z *= -1; this._isDirty = true; return this; } /** * Negate the current Vector3 and stores the result in the given vector "result" coordinates * Example Playground https://playground.babylonjs.com/#R1F8YU#37 * @param result defines the Vector3 object where to store the result * @returns the result */ negateToRef(result) { result._x = this._x * -1; result._y = this._y * -1; result._z = this._z * -1; result._isDirty = true; return result; } /** * Multiplies the Vector3 coordinates by the float "scale" * Example Playground https://playground.babylonjs.com/#R1F8YU#56 * @param scale defines the multiplier factor * @returns the current updated Vector3 */ scaleInPlace(scale) { this._x *= scale; this._y *= scale; this._z *= scale; this._isDirty = true; return this; } /** * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale" * Example Playground https://playground.babylonjs.com/#R1F8YU#53 * @param scale defines the multiplier factor * @returns a new Vector3 */ scale(scale) { return new _Vector3(this._x * scale, this._y * scale, this._z * scale); } /** * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates * Example Playground https://playground.babylonjs.com/#R1F8YU#57 * @param scale defines the multiplier factor * @param result defines the Vector3 object where to store the result * @returns the result */ scaleToRef(scale, result) { result._x = this._x * scale; result._y = this._y * scale; result._z = this._z * scale; result._isDirty = true; return result; } /** * Creates a vector normal (perpendicular) to the current Vector3 and stores the result in the given vector * Out of the infinite possibilities the normal chosen is the one formed by rotating the current vector * 90 degrees about an axis which lies perpendicular to the current vector * and its projection on the xz plane. In the case of a current vector in the xz plane * the normal is calculated to be along the y axis. * Example Playground https://playground.babylonjs.com/#R1F8YU#230 * Example Playground https://playground.babylonjs.com/#R1F8YU#231 * @param result defines the Vector3 object where to store the resultant normal * @returns the result */ getNormalToRef(result) { const radius = this.length(); let theta = Math.acos(this._y / radius); const phi = Math.atan2(this._z, this._x); if (theta > Math.PI / 2) { theta -= Math.PI / 2; } else { theta += Math.PI / 2; } const x = radius * Math.sin(theta) * Math.cos(phi); const y = radius * Math.cos(theta); const z = radius * Math.sin(theta) * Math.sin(phi); result.set(x, y, z); return result; } /** * Rotates the vector using the given unit quaternion and stores the new vector in result * Example Playground https://playground.babylonjs.com/#R1F8YU#9 * @param q the unit quaternion representing the rotation * @param result the output vector * @returns the result */ applyRotationQuaternionToRef(q, result) { const vx = this._x, vy = this._y, vz = this._z; const qx = q._x, qy = q._y, qz = q._z, qw = q._w; const tx = 2 * (qy * vz - qz * vy); const ty = 2 * (qz * vx - qx * vz); const tz = 2 * (qx * vy - qy * vx); result._x = vx + qw * tx + qy * tz - qz * ty; result._y = vy + qw * ty + qz * tx - qx * tz; result._z = vz + qw * tz + qx * ty - qy * tx; result._isDirty = true; return result; } /** * Rotates the vector in place using the given unit quaternion * Example Playground https://playground.babylonjs.com/#R1F8YU#8 * @param q the unit quaternion representing the rotation * @returns the current updated Vector3 */ applyRotationQuaternionInPlace(q) { return this.applyRotationQuaternionToRef(q, this); } /** * Rotates the vector using the given unit quaternion and returns the new vector * Example Playground https://playground.babylonjs.com/#R1F8YU#7 * @param q the unit quaternion representing the rotation * @returns a new Vector3 */ applyRotationQuaternion(q) { return this.applyRotationQuaternionToRef(q, new _Vector3()); } /** * Scale the current Vector3 values by a factor and add the result to a given Vector3 * Example Playground https://playground.babylonjs.com/#R1F8YU#55 * @param scale defines the scale factor * @param result defines the Vector3 object where to store the result * @returns result input */ scaleAndAddToRef(scale, result) { result._x += this._x * scale; result._y += this._y * scale; result._z += this._z * scale; result._isDirty = true; return result; } /** * Projects the current point Vector3 to a plane along a ray starting from a specified origin and passing through the current point Vector3. * Example Playground https://playground.babylonjs.com/#R1F8YU#48 * @param plane defines the plane to project to * @param origin defines the origin of the projection ray * @returns the projected vector3 */ projectOnPlane(plane, origin) { return this.projectOnPlaneToRef(plane, origin, new _Vector3()); } /** * Projects the current point Vector3 to a plane along a ray starting from a specified origin and passing through the current point Vector3. * Example Playground https://playground.babylonjs.com/#R1F8YU#49 * @param plane defines the plane to project to * @param origin defines the origin of the projection ray * @param result defines the Vector3 where to store the result * @returns result input */ projectOnPlaneToRef(plane, origin, result) { const n = plane.normal; const d = plane.d; const V = MathTmp.Vector3[0]; this.subtractToRef(origin, V); V.normalize(); const denom = _Vector3.Dot(V, n); if (Math.abs(denom) < 1e-10) { result.setAll(Infinity); } else { const t = -(_Vector3.Dot(origin, n) + d) / denom; const scaledV = V.scaleInPlace(t); origin.addToRef(scaledV, result); } return result; } /** * Returns true if the current Vector3 and the given vector coordinates are strictly equal * Example Playground https://playground.babylonjs.com/#R1F8YU#19 * @param otherVector defines the second operand * @returns true if both vectors are equals */ equals(otherVector) { return otherVector && this._x === otherVector._x && this._y === otherVector._y && this._z === otherVector._z; } /** * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon * Example Playground https://playground.babylonjs.com/#R1F8YU#21 * @param otherVector defines the second operand * @param epsilon defines the minimal distance to define values as equals * @returns true if both vectors are distant less than epsilon */ equalsWithEpsilon(otherVector, epsilon = Epsilon) { return otherVector && WithinEpsilon(this._x, otherVector._x, epsilon) && WithinEpsilon(this._y, otherVector._y, epsilon) && WithinEpsilon(this._z, otherVector._z, epsilon); } /** * Returns true if the current Vector3 coordinates equals the given floats * Example Playground https://playground.babylonjs.com/#R1F8YU#20 * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @returns true if both vectors are equal */ equalsToFloats(x, y, z) { return this._x === x && this._y === y && this._z === z; } /** * Multiplies the current Vector3 coordinates by the given ones * Example Playground https://playground.babylonjs.com/#R1F8YU#32 * @param otherVector defines the second operand * @returns the current updated Vector3 */ multiplyInPlace(otherVector) { this._x *= otherVector._x; this._y *= otherVector._y; this._z *= otherVector._z; this._isDirty = true; return this; } /** * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector * Example Playground https://playground.babylonjs.com/#R1F8YU#31 * @param otherVector defines the second operand * @returns the new Vector3 */ multiply(otherVector) { return this.multiplyByFloats(otherVector._x, otherVector._y, otherVector._z); } /** * Multiplies the current Vector3 by the given one and stores the result in the given vector "result" * Example Playground https://playground.babylonjs.com/#R1F8YU#33 * @param otherVector defines the second operand * @param result defines the Vector3 object where to store the result * @returns the result */ multiplyToRef(otherVector, result) { result._x = this._x * otherVector._x; result._y = this._y * otherVector._y; result._z = this._z * otherVector._z; result._isDirty = true; return result; } /** * Returns a new Vector3 set with the result of the multiplication of the current Vector3 coordinates by the given floats * Example Playground https://playground.babylonjs.com/#R1F8YU#34 * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @returns the new Vector3 */ multiplyByFloats(x, y, z) { return new _Vector3(this._x * x, this._y * y, this._z * z); } /** * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones * Example Playground https://playground.babylonjs.com/#R1F8YU#16 * @param otherVector defines the second operand * @returns the new Vector3 */ divide(otherVector) { return new _Vector3(this._x / otherVector._x, this._y / otherVector._y, this._z / otherVector._z); } /** * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result" * Example Playground https://playground.babylonjs.com/#R1F8YU#18 * @param otherVector defines the second operand * @param result defines the Vector3 object where to store the result * @returns the result */ divideToRef(otherVector, result) { result._x = this._x / otherVector._x; result._y = this._y / otherVector._y; result._z = this._z / otherVector._z; result._isDirty = true; return result; } /** * Divides the current Vector3 coordinates by the given ones. * Example Playground https://playground.babylonjs.com/#R1F8YU#17 * @param otherVector defines the second operand * @returns the current updated Vector3 */ divideInPlace(otherVector) { this._x = this._x / otherVector._x; this._y = this._y / otherVector._y; this._z = this._z / otherVector._z; this._isDirty = true; return this; } /** * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones * Example Playground https://playground.babylonjs.com/#R1F8YU#29 * @param other defines the second operand * @returns the current updated Vector3 */ minimizeInPlace(other) { return this.minimizeInPlaceFromFloats(other._x, other._y, other._z); } /** * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones. * Example Playground https://playground.babylonjs.com/#R1F8YU#27 * @param other defines the second operand * @returns the current updated Vector3 */ maximizeInPlace(other) { return this.maximizeInPlaceFromFloats(other._x, other._y, other._z); } /** * Updates the current Vector3 with the minimal coordinate values between its and the given coordinates * Example Playground https://playground.babylonjs.com/#R1F8YU#30 * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @returns the current updated Vector3 */ minimizeInPlaceFromFloats(x, y, z) { if (x < this._x) { this.x = x; } if (y < this._y) { this.y = y; } if (z < this._z) { this.z = z; } return this; } /** * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates. * Example Playground https://playground.babylonjs.com/#R1F8YU#28 * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @returns the current updated Vector3 */ maximizeInPlaceFromFloats(x, y, z) { if (x > this._x) { this.x = x; } if (y > this._y) { this.y = y; } if (z > this._z) { this.z = z; } return this; } /** * Due to float precision, scale of a mesh could be uniform but float values are off by a small fraction * Check if is non uniform within a certain amount of decimal places to account for this * @param epsilon the amount the values can differ * @returns if the vector is non uniform to a certain number of decimal places */ isNonUniformWithinEpsilon(epsilon) { const absX = Math.abs(this._x); const absY = Math.abs(this._y); if (!WithinEpsilon(absX, absY, epsilon)) { return true; } const absZ = Math.abs(this._z); if (!WithinEpsilon(absX, absZ, epsilon)) { return true; } if (!WithinEpsilon(absY, absZ, epsilon)) { return true; } return false; } /** * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same */ get isNonUniform() { const absX = Math.abs(this._x); const absY = Math.abs(this._y); if (absX !== absY) { return true; } const absZ = Math.abs(this._z); if (absX !== absZ) { return true; } return false; } /** * Gets the current Vector3's floored values and stores them in result * @param result the vector to store the result in * @returns the result vector */ floorToRef(result) { result._x = Math.floor(this._x); result._y = Math.floor(this._y); result._z = Math.floor(this._z); result._isDirty = true; return result; } /** * Gets a new Vector3 from current Vector3 floored values * Example Playground https://playground.babylonjs.com/#R1F8YU#22 * @returns a new Vector3 */ floor() { return new _Vector3(Math.floor(this._x), Math.floor(this._y), Math.floor(this._z)); } /** * Gets the current Vector3's fractional values and stores them in result * @param result the vector to store the result in * @returns the result vector */ fractToRef(result) { result._x = this._x - Math.floor(this._x); result._y = this._y - Math.floor(this._y); result._z = this._z - Math.floor(this._z); result._isDirty = true; return result; } /** * Gets a new Vector3 from current Vector3 fractional values * Example Playground https://playground.babylonjs.com/#R1F8YU#23 * @returns a new Vector3 */ fract() { return new _Vector3(this._x - Math.floor(this._x), this._y - Math.floor(this._y), this._z - Math.floor(this._z)); } // Properties /** * Gets the length of the Vector3 * Example Playground https://playground.babylonjs.com/#R1F8YU#25 * @returns the length of the Vector3 */ length() { return Math.sqrt(this.lengthSquared()); } /** * Gets the squared length of the Vector3 * Example Playground https://playground.babylonjs.com/#R1F8YU#26 * @returns squared length of the Vector3 */ lengthSquared() { return this._x * this._x + this._y * this._y + this._z * this._z; } /** * Gets a boolean indicating if the vector contains a zero in one of its components * Example Playground https://playground.babylonjs.com/#R1F8YU#1 */ get hasAZeroComponent() { return this._x * this._y * this._z === 0; } /** * Normalize the current Vector3. * Please note that this is an in place operation. * Example Playground https://playground.babylonjs.com/#R1F8YU#122 * @returns the current updated Vector3 */ normalize() { return this.normalizeFromLength(this.length()); } /** * Reorders the x y z properties of the vector in place * Example Playground https://playground.babylonjs.com/#R1F8YU#44 * @param order new ordering of the properties (eg. for vector 1,2,3 with "ZYX" will produce 3,2,1) * @returns the current updated vector */ reorderInPlace(order) { order = order.toLowerCase(); if (order === "xyz") { return this; } const tem = MathTmp.Vector3[0].copyFrom(this); this.x = tem[order[0]]; this.y = tem[order[1]]; this.z = tem[order[2]]; return this; } /** * Rotates the vector around 0,0,0 by a quaternion * Example Playground https://playground.babylonjs.com/#R1F8YU#47 * @param quaternion the rotation quaternion * @param result vector to store the result * @returns the resulting vector */ rotateByQuaternionToRef(quaternion, result) { quaternion.toRotationMatrix(MathTmp.Matrix[0]); _Vector3.TransformCoordinatesToRef(this, MathTmp.Matrix[0], result); return result; } /** * Rotates a vector around a given point * Example Playground https://playground.babylonjs.com/#R1F8YU#46 * @param quaternion the rotation quaternion * @param point the point to rotate around * @param result vector to store the result * @returns the resulting vector */ rotateByQuaternionAroundPointToRef(quaternion, point, result) { this.subtractToRef(point, MathTmp.Vector3[0]); MathTmp.Vector3[0].rotateByQuaternionToRef(quaternion, MathTmp.Vector3[0]); point.addToRef(MathTmp.Vector3[0], result); return result; } /** * Returns a new Vector3 as the cross product of the current vector and the "other" one * The cross product is then orthogonal to both current and "other" * Example Playground https://playground.babylonjs.com/#R1F8YU#14 * @param other defines the right operand * @returns the cross product */ cross(other) { return _Vector3.CrossToRef(this, other, new _Vector3()); } /** * Normalize the current Vector3 with the given input length. * Please note that this is an in place operation. * Example Playground https://playground.babylonjs.com/#R1F8YU#123 * @param len the length of the vector * @returns the current updated Vector3 */ normalizeFromLength(len) { if (len === 0 || len === 1) { return this; } return this.scaleInPlace(1 / len); } /** * Normalize the current Vector3 to a new vector * Example Playground https://playground.babylonjs.com/#R1F8YU#124 * @returns the new Vector3 */ normalizeToNew() { return this.normalizeToRef(new _Vector3()); } /** * Normalize the current Vector3 to the reference * Example Playground https://playground.babylonjs.com/#R1F8YU#125 * @param result define the Vector3 to update * @returns the updated Vector3 */ normalizeToRef(result) { const len = this.length(); if (len === 0 || len === 1) { result._x = this._x; result._y = this._y; result._z = this._z; result._isDirty = true; return result; } return this.scaleToRef(1 / len, result); } /** * Creates a new Vector3 copied from the current Vector3 * Example Playground https://playground.babylonjs.com/#R1F8YU#11 * @returns the new Vector3 */ clone() { return new _Vector3(this._x, this._y, this._z); } /** * Copies the given vector coordinates to the current Vector3 ones * Example Playground https://playground.babylonjs.com/#R1F8YU#12 * @param source defines the source Vector3 * @returns the current updated Vector3 */ copyFrom(source) { return this.copyFromFloats(source._x, source._y, source._z); } /** * Copies the given floats to the current Vector3 coordinates * Example Playground https://playground.babylonjs.com/#R1F8YU#13 * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @returns the current updated Vector3 */ copyFromFloats(x, y, z) { this._x = x; this._y = y; this._z = z; this._isDirty = true; return this; } /** * Copies the given floats to the current Vector3 coordinates * Example Playground https://playground.babylonjs.com/#R1F8YU#58 * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @returns the current updated Vector3 */ set(x, y, z) { return this.copyFromFloats(x, y, z); } /** * Copies the given float to the current Vector3 coordinates * Example Playground https://playground.babylonjs.com/#R1F8YU#59 * @param v defines the x, y and z coordinates of the operand * @returns the current updated Vector3 */ setAll(v) { this._x = this._y = this._z = v; this._isDirty = true; return this; } // Statics /** * Get the clip factor between two vectors * Example Playground https://playground.babylonjs.com/#R1F8YU#126 * @param vector0 defines the first operand * @param vector1 defines the second operand * @param axis defines the axis to use * @param size defines the size along the axis * @returns the clip factor */ static GetClipFactor(vector0, vector1, axis, size) { const d0 = _Vector3.Dot(vector0, axis); const d1 = _Vector3.Dot(vector1, axis); return (d0 - size) / (d0 - d1); } /** * Get angle between two vectors * Example Playground https://playground.babylonjs.com/#R1F8YU#86 * @param vector0 the starting point * @param vector1 the ending point * @param normal direction of the normal * @returns the angle between vector0 and vector1 */ static GetAngleBetweenVectors(vector0, vector1, normal) { const v0 = vector0.normalizeToRef(MathTmp.Vector3[1]); const v1 = vector1.normalizeToRef(MathTmp.Vector3[2]); let dot = _Vector3.Dot(v0, v1); dot = Clamp(dot, -1, 1); const angle = Math.acos(dot); const n = MathTmp.Vector3[3]; _Vector3.CrossToRef(v0, v1, n); if (_Vector3.Dot(n, normal) > 0) { return isNaN(angle) ? 0 : angle; } return isNaN(angle) ? -Math.PI : -Math.acos(dot); } /** * Get angle between two vectors projected on a plane * Example Playground https://playground.babylonjs.com/#R1F8YU#87 * Expectation compute time: 0.01 ms (median) and 0.02 ms (percentile 95%) * @param vector0 angle between vector0 and vector1 * @param vector1 angle between vector0 and vector1 * @param normal Normal of the projection plane * @returns the angle in radians (float) between vector0 and vector1 projected on the plane with the specified normal */ static GetAngleBetweenVectorsOnPlane(vector0, vector1, normal) { MathTmp.Vector3[0].copyFrom(vector0); const v0 = MathTmp.Vector3[0]; MathTmp.Vector3[1].copyFrom(vector1); const v1 = MathTmp.Vector3[1]; MathTmp.Vector3[2].copyFrom(normal); const vNormal = MathTmp.Vector3[2]; const right = MathTmp.Vector3[3]; const forward = MathTmp.Vector3[4]; v0.normalize(); v1.normalize(); vNormal.normalize(); _Vector3.CrossToRef(vNormal, v0, right); _Vector3.CrossToRef(right, vNormal, forward); const angle = Math.atan2(_Vector3.Dot(v1, right), _Vector3.Dot(v1, forward)); return NormalizeRadians(angle); } /** * Gets the rotation that aligns the roll axis (Y) to the line joining the start point to the target point and stores it in the ref Vector3 * Example PG https://playground.babylonjs.com/#R1F8YU#189 * @param start the starting point * @param target the target point * @param ref the vector3 to store the result * @returns ref in the form (pitch, yaw, 0) */ static PitchYawRollToMoveBetweenPointsToRef(start, target, ref) { const diff = TmpVectors.Vector3[0]; target.subtractToRef(start, diff); ref._y = Math.atan2(diff.x, diff.z) || 0; ref._x = Math.atan2(Math.sqrt(diff.x ** 2 + diff.z ** 2), diff.y) || 0; ref._z = 0; ref._isDirty = true; return ref; } /** * Gets the rotation that aligns the roll axis (Y) to the line joining the start point to the target point * Example PG https://playground.babylonjs.com/#R1F8YU#188 * @param start the starting point * @param target the target point * @returns the rotation in the form (pitch, yaw, 0) */ static PitchYawRollToMoveBetweenPoints(start, target) { const ref = _Vector3.Zero(); return _Vector3.PitchYawRollToMoveBetweenPointsToRef(start, target, ref); } /** * Slerp between two vectors. See also `SmoothToRef` * Slerp is a spherical linear interpolation * giving a slow in and out effect * Example Playground 1 https://playground.babylonjs.com/#R1F8YU#108 * Example Playground 2 https://playground.babylonjs.com/#R1F8YU#109 * @param vector0 Start vector * @param vector1 End vector * @param slerp amount (will be clamped between 0 and 1) * @param result The slerped vector * @returns The slerped vector */ static SlerpToRef(vector0, vector1, slerp, result) { slerp = Clamp(slerp, 0, 1); const vector0Dir = MathTmp.Vector3[0]; const vector1Dir = MathTmp.Vector3[1]; vector0Dir.copyFrom(vector0); const vector0Length = vector0Dir.length(); vector0Dir.normalizeFromLength(vector0Length); vector1Dir.copyFrom(vector1); const vector1Length = vector1Dir.length(); vector1Dir.normalizeFromLength(vector1Length); const dot = _Vector3.Dot(vector0Dir, vector1Dir); let scale0; let scale1; if (dot < 1 - Epsilon) { const omega = Math.acos(dot); const invSin = 1 / Math.sin(omega); scale0 = Math.sin((1 - slerp) * omega) * invSin; scale1 = Math.sin(slerp * omega) * invSin; } else { scale0 = 1 - slerp; scale1 = slerp; } vector0Dir.scaleInPlace(scale0); vector1Dir.scaleInPlace(scale1); result.copyFrom(vector0Dir).addInPlace(vector1Dir); result.scaleInPlace(Lerp(vector0Length, vector1Length, slerp)); return result; } /** * Smooth interpolation between two vectors using Slerp * Example Playground https://playground.babylonjs.com/#R1F8YU#110 * @param source source vector * @param goal goal vector * @param deltaTime current interpolation frame * @param lerpTime total interpolation time * @param result the smoothed vector * @returns the smoothed vector */ static SmoothToRef(source, goal, deltaTime, lerpTime, result) { _Vector3.SlerpToRef(source, goal, lerpTime === 0 ? 1 : deltaTime / lerpTime, result); return result; } /** * Returns a new Vector3 set from the index "offset" of the given array * Example Playground https://playground.babylonjs.com/#R1F8YU#83 * @param array defines the source array * @param offset defines the offset in the source array * @returns the new Vector3 */ static FromArray(array, offset = 0) { return new _Vector3(array[offset], array[offset + 1], array[offset + 2]); } /** * Returns a new Vector3 set from the index "offset" of the given Float32Array * @param array defines the source array * @param offset defines the offset in the source array * @returns the new Vector3 * @deprecated Please use FromArray instead. */ static FromFloatArray(array, offset) { return _Vector3.FromArray(array, offset); } /** * Sets the given vector "result" with the element values from the index "offset" of the given array * Example Playground https://playground.babylonjs.com/#R1F8YU#84 * @param array defines the source array * @param offset defines the offset in the source array * @param result defines the Vector3 where to store the result * @returns result input */ static FromArrayToRef(array, offset, result) { result._x = array[offset]; result._y = array[offset + 1]; result._z = array[offset + 2]; result._isDirty = true; return result; } /** * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array * @param array defines the source array * @param offset defines the offset in the source array * @param result defines the Vector3 where to store the result * @deprecated Please use FromArrayToRef instead. * @returns result input */ static FromFloatArrayToRef(array, offset, result) { return _Vector3.FromArrayToRef(array, offset, result); } /** * Sets the given vector "result" with the given floats. * Example Playground https://playground.babylonjs.com/#R1F8YU#85 * @param x defines the x coordinate of the source * @param y defines the y coordinate of the source * @param z defines the z coordinate of the source * @param result defines the Vector3 where to store the result * @returns the result vector */ static FromFloatsToRef(x, y, z, result) { result.copyFromFloats(x, y, z); return result; } /** * Returns a new Vector3 set to (0.0, 0.0, 0.0) * @returns a new empty Vector3 */ static Zero() { return new _Vector3(0, 0, 0); } /** * Returns a new Vector3 set to (1.0, 1.0, 1.0) * @returns a new Vector3 */ static One() { return new _Vector3(1, 1, 1); } /** * Returns a new Vector3 set to (0.0, 1.0, 0.0) * Example Playground https://playground.babylonjs.com/#R1F8YU#71 * @returns a new up Vector3 */ static Up() { return new _Vector3(0, 1, 0); } /** * Gets an up Vector3 that must not be updated */ static get UpReadOnly() { return _Vector3._UpReadOnly; } /** * Gets a down Vector3 that must not be updated */ static get DownReadOnly() { return _Vector3._DownReadOnly; } /** * Gets a right Vector3 that must not be updated */ static get RightReadOnly() { return _Vector3._RightReadOnly; } /** * Gets a left Vector3 that must not be updated */ static get LeftReadOnly() { return _Vector3._LeftReadOnly; } /** * Gets a forward Vector3 that must not be updated */ static get LeftHandedForwardReadOnly() { return _Vector3._LeftHandedForwardReadOnly; } /** * Gets a forward Vector3 that must not be updated */ static get RightHandedForwardReadOnly() { return _Vector3._RightHandedForwardReadOnly; } /** * Gets a backward Vector3 that must not be updated */ static get LeftHandedBackwardReadOnly() { return _Vector3._LeftHandedBackwardReadOnly; } /** * Gets a backward Vector3 that must not be updated */ static get RightHandedBackwardReadOnly() { return _Vector3._RightHandedBackwardReadOnly; } /** * Gets a zero Vector3 that must not be updated */ static get ZeroReadOnly() { return _Vector3._ZeroReadOnly; } /** * Gets a one Vector3 that must not be updated */ static get OneReadOnly() { return _Vector3._OneReadOnly; } /** * Returns a new Vector3 set to (0.0, -1.0, 0.0) * Example Playground https://playground.babylonjs.com/#R1F8YU#71 * @returns a new down Vector3 */ static Down() { return new _Vector3(0, -1, 0); } /** * Returns a new Vector3 set to (0.0, 0.0, 1.0) * Example Playground https://playground.babylonjs.com/#R1F8YU#71 * @param rightHandedSystem is the scene right-handed (negative z) * @returns a new forward Vector3 */ static Forward(rightHandedSystem = false) { return new _Vector3(0, 0, rightHandedSystem ? -1 : 1); } /** * Returns a new Vector3 set to (0.0, 0.0, -1.0) * Example Playground https://playground.babylonjs.com/#R1F8YU#71 * @param rightHandedSystem is the scene right-handed (negative-z) * @returns a new Backward Vector3 */ static Backward(rightHandedSystem = false) { return new _Vector3(0, 0, rightHandedSystem ? 1 : -1); } /** * Returns a new Vector3 set to (1.0, 0.0, 0.0) * Example Playground https://playground.babylonjs.com/#R1F8YU#71 * @returns a new right Vector3 */ static Right() { return new _Vector3(1, 0, 0); } /** * Returns a new Vector3 set to (-1.0, 0.0, 0.0) * Example Playground https://playground.babylonjs.com/#R1F8YU#71 * @returns a new left Vector3 */ static Left() { return new _Vector3(-1, 0, 0); } /** * Returns a new Vector3 with random values between min and max * @param min the minimum random value * @param max the maximum random value * @returns a Vector3 with random values between min and max */ static Random(min = 0, max = 1) { return new _Vector3(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max)); } /** * Sets a Vector3 with random values between min and max * @param min the minimum random value * @param max the maximum random value * @param ref the ref to store the values in * @returns the ref with random values between min and max */ static RandomToRef(min = 0, max = 1, ref) { return ref.copyFromFloats(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max)); } /** * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector. * This method computes transformed coordinates only, not transformed direction vectors (ie. it takes translation in account) * Example Playground https://playground.babylonjs.com/#R1F8YU#111 * @param vector defines the Vector3 to transform * @param transformation defines the transformation matrix * @returns the transformed Vector3 */ static TransformCoordinates(vector, transformation) { const result = _Vector3.Zero(); _Vector3.TransformCoordinatesToRef(vector, transformation, result); return result; } /** * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector * This method computes transformed coordinates only, not transformed direction vectors (ie. it takes translation in account) * Example Playground https://playground.babylonjs.com/#R1F8YU#113 * @param vector defines the Vector3 to transform * @param transformation defines the transformation matrix * @param result defines the Vector3 where to store the result * @returns result input */ static TransformCoordinatesToRef(vector, transformation, result) { _Vector3.TransformCoordinatesFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result); return result; } /** * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z) * This method computes transformed coordinates only, not transformed direction vectors * Example Playground https://playground.babylonjs.com/#R1F8YU#115 * @param x define the x coordinate of the source vector * @param y define the y coordinate of the source vector * @param z define the z coordinate of the source vector * @param transformation defines the transformation matrix * @param result defines the Vector3 where to store the result * @returns result input */ static TransformCoordinatesFromFloatsToRef(x, y, z, transformation, result) { const m = transformation.m; const rx = x * m[0] + y * m[4] + z * m[8] + m[12]; const ry = x * m[1] + y * m[5] + z * m[9] + m[13]; const rz = x * m[2] + y * m[6] + z * m[10] + m[14]; const rw = 1 / (x * m[3] + y * m[7] + z * m[11] + m[15]); result._x = rx * rw; result._y = ry * rw; result._z = rz * rw; result._isDirty = true; return result; } /** * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector * This methods computes transformed normalized direction vectors only (ie. it does not apply translation) * Example Playground https://playground.babylonjs.com/#R1F8YU#112 * @param vector defines the Vector3 to transform * @param transformation defines the transformation matrix * @returns the new Vector3 */ static TransformNormal(vector, transformation) { const result = _Vector3.Zero(); _Vector3.TransformNormalToRef(vector, transformation, result); return result; } /** * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector * This methods computes transformed normalized direction vectors only (ie. it does not apply translation) * Example Playground https://playground.babylonjs.com/#R1F8YU#114 * @param vector defines the Vector3 to transform * @param transformation defines the transformation matrix * @param result defines the Vector3 where to store the result * @returns result input */ static TransformNormalToRef(vector, transformation, result) { this.TransformNormalFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result); return result; } /** * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z) * This methods computes transformed normalized direction vectors only (ie. it does not apply translation) * Example Playground https://playground.babylonjs.com/#R1F8YU#116 * @param x define the x coordinate of the source vector * @param y define the y coordinate of the source vector * @param z define the z coordinate of the source vector * @param transformation defines the transformation matrix * @param result defines the Vector3 where to store the result * @returns result input */ static TransformNormalFromFloatsToRef(x, y, z, transformation, result) { const m = transformation.m; result._x = x * m[0] + y * m[4] + z * m[8]; result._y = x * m[1] + y * m[5] + z * m[9]; result._z = x * m[2] + y * m[6] + z * m[10]; result._isDirty = true; return result; } /** * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4" * Example Playground https://playground.babylonjs.com/#R1F8YU#69 * @param value1 defines the first control point * @param value2 defines the second control point * @param value3 defines the third control point * @param value4 defines the fourth control point * @param amount defines the amount on the spline to use * @returns the new Vector3 */ static CatmullRom(value1, value2, value3, value4, amount) { const squared = amount * amount; const cubed = amount * squared; const x = 0.5 * (2 * value2._x + (-value1._x + value3._x) * amount + (2 * value1._x - 5 * value2._x + 4 * value3._x - value4._x) * squared + (-value1._x + 3 * value2._x - 3 * value3._x + value4._x) * cubed); const y = 0.5 * (2 * value2._y + (-value1._y + value3._y) * amount + (2 * value1._y - 5 * value2._y + 4 * value3._y - value4._y) * squared + (-value1._y + 3 * value2._y - 3 * value3._y + value4._y) * cubed); const z = 0.5 * (2 * value2._z + (-value1._z + value3._z) * amount + (2 * value1._z - 5 * value2._z + 4 * value3._z - value4._z) * squared + (-value1._z + 3 * value2._z - 3 * value3._z + value4._z) * cubed); return new _Vector3(x, y, z); } /** * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max" * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one * Example Playground https://playground.babylonjs.com/#R1F8YU#76 * @param value defines the current value * @param min defines the lower range value * @param max defines the upper range value * @returns the new Vector3 */ static Clamp(value, min, max) { const result = new _Vector3(); _Vector3.ClampToRef(value, min, max, result); return result; } /** * Sets the given vector "result" with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max" * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one * Example Playground https://playground.babylonjs.com/#R1F8YU#77 * @param value defines the current value * @param min defines the lower range value * @param max defines the upper range value * @param result defines the Vector3 where to store the result * @returns result input */ static ClampToRef(value, min, max, result) { let x = value._x; x = x > max._x ? max._x : x; x = x < min._x ? min._x : x; let y = value._y; y = y > max._y ? max._y : y; y = y < min._y ? min._y : y; let z = value._z; z = z > max._z ? max._z : z; z = z < min._z ? min._z : z; result.copyFromFloats(x, y, z); return result; } /** * Checks if a given vector is inside a specific range * Example Playground https://playground.babylonjs.com/#R1F8YU#75 * @param v defines the vector to test * @param min defines the minimum range * @param max defines the maximum range */ static CheckExtends(v, min, max) { min.minimizeInPlace(v); max.maximizeInPlace(v); } /** * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2" * Example Playground https://playground.babylonjs.com/#R1F8YU#89 * @param value1 defines the first control point * @param tangent1 defines the first tangent vector * @param value2 defines the second control point * @param tangent2 defines the second tangent vector * @param amount defines the amount on the interpolation spline (between 0 and 1) * @returns the new Vector3 */ static Hermite(value1, tangent1, value2, tangent2, amount) { const squared = amount * amount; const cubed = amount * squared; const part1 = 2 * cubed - 3 * squared + 1; const part2 = -2 * cubed + 3 * squared; const part3 = cubed - 2 * squared + amount; const part4 = cubed - squared; const x = value1._x * part1 + value2._x * part2 + tangent1._x * part3 + tangent2._x * part4; const y = value1._y * part1 + value2._y * part2 + tangent1._y * part3 + tangent2._y * part4; const z = value1._z * part1 + value2._z * part2 + tangent1._z * part3 + tangent2._z * part4; return new _Vector3(x, y, z); } /** * Returns a new Vector3 which is the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2". * Example Playground https://playground.babylonjs.com/#R1F8YU#90 * @param value1 defines the first control point * @param tangent1 defines the first tangent * @param value2 defines the second control point * @param tangent2 defines the second tangent * @param time define where the derivative must be done * @returns 1st derivative */ static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { const result = new _Vector3(); this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result); return result; } /** * Update a Vector3 with the 1st derivative of the Hermite spline defined by the vectors "value1", "value2", "tangent1", "tangent2". * Example Playground https://playground.babylonjs.com/#R1F8YU#91 * @param value1 defines the first control point * @param tangent1 defines the first tangent * @param value2 defines the second control point * @param tangent2 defines the second tangent * @param time define where the derivative must be done * @param result define where to store the derivative * @returns result input */ static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { const t2 = time * time; result._x = (t2 - time) * 6 * value1._x + (3 * t2 - 4 * time + 1) * tangent1._x + (-t2 + time) * 6 * value2._x + (3 * t2 - 2 * time) * tangent2._x; result._y = (t2 - time) * 6 * value1._y + (3 * t2 - 4 * time + 1) * tangent1._y + (-t2 + time) * 6 * value2._y + (3 * t2 - 2 * time) * tangent2._y; result._z = (t2 - time) * 6 * value1._z + (3 * t2 - 4 * time + 1) * tangent1._z + (-t2 + time) * 6 * value2._z + (3 * t2 - 2 * time) * tangent2._z; result._isDirty = true; return result; } /** * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end" * Example Playground https://playground.babylonjs.com/#R1F8YU#95 * @param start defines the start value * @param end defines the end value * @param amount max defines amount between both (between 0 and 1) * @returns the new Vector3 */ static Lerp(start, end, amount) { const result = new _Vector3(0, 0, 0); _Vector3.LerpToRef(start, end, amount, result); return result; } /** * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end" * Example Playground https://playground.babylonjs.com/#R1F8YU#93 * @param start defines the start value * @param end defines the end value * @param amount max defines amount between both (between 0 and 1) * @param result defines the Vector3 where to store the result * @returns result input */ static LerpToRef(start, end, amount, result) { result._x = start._x + (end._x - start._x) * amount; result._y = start._y + (end._y - start._y) * amount; result._z = start._z + (end._z - start._z) * amount; result._isDirty = true; return result; } /** * Returns the dot product (float) between the vectors "left" and "right" * Example Playground https://playground.babylonjs.com/#R1F8YU#82 * @param left defines the left operand * @param right defines the right operand * @returns the dot product */ static Dot(left, right) { return left._x * right._x + left._y * right._y + left._z * right._z; } /** * Returns the dot product (float) between the current vectors and "otherVector" * @param otherVector defines the right operand * @returns the dot product */ dot(otherVector) { return this._x * otherVector._x + this._y * otherVector._y + this._z * otherVector._z; } /** * Returns a new Vector3 as the cross product of the vectors "left" and "right" * The cross product is then orthogonal to both "left" and "right" * Example Playground https://playground.babylonjs.com/#R1F8YU#15 * @param left defines the left operand * @param right defines the right operand * @returns the cross product */ static Cross(left, right) { const result = new _Vector3(); _Vector3.CrossToRef(left, right, result); return result; } /** * Sets the given vector "result" with the cross product of "left" and "right" * The cross product is then orthogonal to both "left" and "right" * Example Playground https://playground.babylonjs.com/#R1F8YU#78 * @param left defines the left operand * @param right defines the right operand * @param result defines the Vector3 where to store the result * @returns result input */ static CrossToRef(left, right, result) { const x = left._y * right._z - left._z * right._y; const y = left._z * right._x - left._x * right._z; const z = left._x * right._y - left._y * right._x; result.copyFromFloats(x, y, z); return result; } /** * Returns a new Vector3 as the normalization of the given vector * Example Playground https://playground.babylonjs.com/#R1F8YU#98 * @param vector defines the Vector3 to normalize * @returns the new Vector3 */ static Normalize(vector) { const result = _Vector3.Zero(); _Vector3.NormalizeToRef(vector, result); return result; } /** * Sets the given vector "result" with the normalization of the given first vector * Example Playground https://playground.babylonjs.com/#R1F8YU#98 * @param vector defines the Vector3 to normalize * @param result defines the Vector3 where to store the result * @returns result input */ static NormalizeToRef(vector, result) { vector.normalizeToRef(result); return result; } /** * Project a Vector3 onto screen space * Example Playground https://playground.babylonjs.com/#R1F8YU#101 * @param vector defines the Vector3 to project * @param world defines the world matrix to use * @param transform defines the transform (view x projection) matrix to use * @param viewport defines the screen viewport to use * @returns the new Vector3 */ static Project(vector, world, transform, viewport) { const result = new _Vector3(); _Vector3.ProjectToRef(vector, world, transform, viewport, result); return result; } /** * Project a Vector3 onto screen space to reference * Example Playground https://playground.babylonjs.com/#R1F8YU#102 * @param vector defines the Vector3 to project * @param world defines the world matrix to use * @param transform defines the transform (view x projection) matrix to use * @param viewport defines the screen viewport to use * @param result the vector in which the screen space will be stored * @returns result input */ static ProjectToRef(vector, world, transform, viewport, result) { const cw = viewport.width; const ch = viewport.height; const cx = viewport.x; const cy = viewport.y; const viewportMatrix = MathTmp.Matrix[1]; const isNDCHalfZRange = EngineStore.LastCreatedEngine?.isNDCHalfZRange; const zScale = isNDCHalfZRange ? 1 : 0.5; const zOffset = isNDCHalfZRange ? 0 : 0.5; Matrix.FromValuesToRef(cw / 2, 0, 0, 0, 0, -ch / 2, 0, 0, 0, 0, zScale, 0, cx + cw / 2, ch / 2 + cy, zOffset, 1, viewportMatrix); const matrix = MathTmp.Matrix[0]; world.multiplyToRef(transform, matrix); matrix.multiplyToRef(viewportMatrix, matrix); _Vector3.TransformCoordinatesToRef(vector, matrix, result); return result; } /** * Reflects a vector off the plane defined by a normalized normal * @param inDirection defines the vector direction * @param normal defines the normal - Must be normalized * @returns the resulting vector */ static Reflect(inDirection, normal) { return this.ReflectToRef(inDirection, normal, new _Vector3()); } /** * Reflects a vector off the plane defined by a normalized normal to reference * @param inDirection defines the vector direction * @param normal defines the normal - Must be normalized * @param ref defines the Vector3 where to store the result * @returns the resulting vector */ static ReflectToRef(inDirection, normal, ref) { const tmp = TmpVectors.Vector3[0]; tmp.copyFrom(normal).scaleInPlace(2 * _Vector3.Dot(inDirection, normal)); return ref.copyFrom(inDirection).subtractInPlace(tmp); } /** * Unproject from screen space to object space * Example Playground https://playground.babylonjs.com/#R1F8YU#121 * @param source defines the screen space Vector3 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 transform defines the transform (view x projection) matrix to use * @returns the new Vector3 */ static UnprojectFromTransform(source, viewportWidth, viewportHeight, world, transform) { return this.Unproject(source, viewportWidth, viewportHeight, world, transform, Matrix.IdentityReadOnly); } /** * Unproject from screen space to object space * Example Playground https://playground.babylonjs.com/#R1F8YU#117 * @param source defines the screen space Vector3 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 * @returns the new Vector3 */ static Unproject(source, viewportWidth, viewportHeight, world, view, projection) { const result = new _Vector3(); _Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result); return result; } /** * Unproject from screen space to object space * Example Playground https://playground.babylonjs.com/#R1F8YU#119 * @param source defines the screen space Vector3 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 * @param result defines the Vector3 where to store the result * @returns result input */ static UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result) { _Vector3.UnprojectFloatsToRef(source._x, source._y, source._z, viewportWidth, viewportHeight, world, view, projection, result); return result; } /** * Unproject from screen space to object space * Example Playground https://playground.babylonjs.com/#R1F8YU#120 * @param sourceX defines the screen space x coordinate to use * @param sourceY defines the screen space y coordinate to use * @param sourceZ defines the screen space z 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 * @param result defines the Vector3 where to store the result * @returns result input */ static UnprojectFloatsToRef(sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) { const matrix = MathTmp.Matrix[0]; world.multiplyToRef(view, matrix); matrix.multiplyToRef(projection, matrix); matrix.invert(); const screenSource = MathTmp.Vector3[0]; screenSource.x = sourceX / viewportWidth * 2 - 1; screenSource.y = -(sourceY / viewportHeight * 2 - 1); if (EngineStore.LastCreatedEngine?.isNDCHalfZRange) { screenSource.z = sourceZ; } else { screenSource.z = 2 * sourceZ - 1; } _Vector3.TransformCoordinatesToRef(screenSource, matrix, result); return result; } /** * Gets the minimal coordinate values between two Vector3 * Example Playground https://playground.babylonjs.com/#R1F8YU#97 * @param left defines the first operand * @param right defines the second operand * @returns the new Vector3 */ static Minimize(left, right) { const min = new _Vector3(); min.copyFrom(left); min.minimizeInPlace(right); return min; } /** * Gets the maximal coordinate values between two Vector3 * Example Playground https://playground.babylonjs.com/#R1F8YU#96 * @param left defines the first operand * @param right defines the second operand * @returns the new Vector3 */ static Maximize(left, right) { const max = new _Vector3(); max.copyFrom(left); max.maximizeInPlace(right); return max; } /** * Returns the distance between the vectors "value1" and "value2" * Example Playground https://playground.babylonjs.com/#R1F8YU#81 * @param value1 defines the first operand * @param value2 defines the second operand * @returns the distance */ static Distance(value1, value2) { return Math.sqrt(_Vector3.DistanceSquared(value1, value2)); } /** * Returns the squared distance between the vectors "value1" and "value2" * Example Playground https://playground.babylonjs.com/#R1F8YU#80 * @param value1 defines the first operand * @param value2 defines the second operand * @returns the squared distance */ static DistanceSquared(value1, value2) { const x = value1._x - value2._x; const y = value1._y - value2._y; const z = value1._z - value2._z; return x * x + y * y + z * z; } /** * Projects "vector" on the triangle determined by its extremities "p0", "p1" and "p2", stores the result in "ref" * and returns the distance to the projected point. * Example Playground https://playground.babylonjs.com/#R1F8YU#104 * From http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.104.4264&rep=rep1&type=pdf * * @param vector the vector to get distance from * @param p0 extremity of the triangle * @param p1 extremity of the triangle * @param p2 extremity of the triangle * @param ref variable to store the result to * @returns The distance between "ref" and "vector" */ static ProjectOnTriangleToRef(vector, p0, p1, p2, ref) { const p1p0 = MathTmp.Vector3[0]; const p2p0 = MathTmp.Vector3[1]; const p2p1 = MathTmp.Vector3[2]; const normal = MathTmp.Vector3[3]; const vectorp0 = MathTmp.Vector3[4]; p1.subtractToRef(p0, p1p0); p2.subtractToRef(p0, p2p0); p2.subtractToRef(p1, p2p1); const p1p0L = p1p0.length(); const p2p0L = p2p0.length(); const p2p1L = p2p1.length(); if (p1p0L < Epsilon || p2p0L < Epsilon || p2p1L < Epsilon) { ref.copyFrom(p0); return _Vector3.Distance(vector, p0); } vector.subtractToRef(p0, vectorp0); _Vector3.CrossToRef(p1p0, p2p0, normal); const nl = normal.length(); if (nl < Epsilon) { ref.copyFrom(p0); return _Vector3.Distance(vector, p0); } normal.normalizeFromLength(nl); let l = vectorp0.length(); if (l < Epsilon) { ref.copyFrom(p0); return 0; } vectorp0.normalizeFromLength(l); const cosA = _Vector3.Dot(normal, vectorp0); const projVector = MathTmp.Vector3[5]; const proj = MathTmp.Vector3[6]; projVector.copyFrom(normal).scaleInPlace(-l * cosA); proj.copyFrom(vector).addInPlace(projVector); const v0 = MathTmp.Vector3[4]; const v1 = MathTmp.Vector3[5]; const v2 = MathTmp.Vector3[7]; const tmp = MathTmp.Vector3[8]; v0.copyFrom(p1p0).scaleInPlace(1 / p1p0L); tmp.copyFrom(p2p0).scaleInPlace(1 / p2p0L); v0.addInPlace(tmp).scaleInPlace(-1); v1.copyFrom(p1p0).scaleInPlace(-1 / p1p0L); tmp.copyFrom(p2p1).scaleInPlace(1 / p2p1L); v1.addInPlace(tmp).scaleInPlace(-1); v2.copyFrom(p2p1).scaleInPlace(-1 / p2p1L); tmp.copyFrom(p2p0).scaleInPlace(-1 / p2p0L); v2.addInPlace(tmp).scaleInPlace(-1); const projP = MathTmp.Vector3[9]; let dot; projP.copyFrom(proj).subtractInPlace(p0); _Vector3.CrossToRef(v0, projP, tmp); dot = _Vector3.Dot(tmp, normal); const s0 = dot; projP.copyFrom(proj).subtractInPlace(p1); _Vector3.CrossToRef(v1, projP, tmp); dot = _Vector3.Dot(tmp, normal); const s1 = dot; projP.copyFrom(proj).subtractInPlace(p2); _Vector3.CrossToRef(v2, projP, tmp); dot = _Vector3.Dot(tmp, normal); const s2 = dot; const edge = MathTmp.Vector3[10]; let e0, e1; if (s0 > 0 && s1 < 0) { edge.copyFrom(p1p0); e0 = p0; e1 = p1; } else if (s1 > 0 && s2 < 0) { edge.copyFrom(p2p1); e0 = p1; e1 = p2; } else { edge.copyFrom(p2p0).scaleInPlace(-1); e0 = p2; e1 = p0; } const tmp2 = MathTmp.Vector3[9]; const tmp3 = MathTmp.Vector3[4]; e0.subtractToRef(proj, tmp); e1.subtractToRef(proj, tmp2); _Vector3.CrossToRef(tmp, tmp2, tmp3); const isOutside = _Vector3.Dot(tmp3, normal) < 0; if (!isOutside) { ref.copyFrom(proj); return Math.abs(l * cosA); } const r = MathTmp.Vector3[5]; _Vector3.CrossToRef(edge, tmp3, r); r.normalize(); const e0proj = MathTmp.Vector3[9]; e0proj.copyFrom(e0).subtractInPlace(proj); const e0projL = e0proj.length(); if (e0projL < Epsilon) { ref.copyFrom(e0); return _Vector3.Distance(vector, e0); } e0proj.normalizeFromLength(e0projL); const cosG = _Vector3.Dot(r, e0proj); const triProj = MathTmp.Vector3[7]; triProj.copyFrom(proj).addInPlace(r.scaleInPlace(e0projL * cosG)); tmp.copyFrom(triProj).subtractInPlace(e0); l = edge.length(); edge.normalizeFromLength(l); let t = _Vector3.Dot(tmp, edge) / Math.max(l, Epsilon); t = Clamp(t, 0, 1); triProj.copyFrom(e0).addInPlace(edge.scaleInPlace(t * l)); ref.copyFrom(triProj); return _Vector3.Distance(vector, triProj); } /** * Returns a new Vector3 located at the center between "value1" and "value2" * Example Playground https://playground.babylonjs.com/#R1F8YU#72 * @param value1 defines the first operand * @param value2 defines the second operand * @returns the new Vector3 */ static Center(value1, value2) { return _Vector3.CenterToRef(value1, value2, _Vector3.Zero()); } /** * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref" * Example Playground https://playground.babylonjs.com/#R1F8YU#73 * @param value1 defines first vector * @param value2 defines second vector * @param ref defines third vector * @returns ref */ static CenterToRef(value1, value2, ref) { return ref.copyFromFloats((value1._x + value2._x) / 2, (value1._y + value2._y) / 2, (value1._z + value2._z) / 2); } /** * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system), * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply * to something in order to rotate it from its local system to the given target system * Note: axis1, axis2 and axis3 are normalized during this operation * Example Playground https://playground.babylonjs.com/#R1F8YU#106 * @param axis1 defines the first axis * @param axis2 defines the second axis * @param axis3 defines the third axis * @returns a new Vector3 * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/target_align */ static RotationFromAxis(axis1, axis2, axis3) { const rotation = new _Vector3(); _Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation); return rotation; } /** * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3 * Example Playground https://playground.babylonjs.com/#R1F8YU#107 * @param axis1 defines the first axis * @param axis2 defines the second axis * @param axis3 defines the third axis * @param ref defines the Vector3 where to store the result * @returns result input */ static RotationFromAxisToRef(axis1, axis2, axis3, ref) { const quat = MathTmp.Quaternion[0]; Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat); quat.toEulerAnglesToRef(ref); return ref; } }; Vector3._V8PerformanceHack = new Vector3(0.5, 0.5, 0.5); Vector3._UpReadOnly = Vector3.Up(); Vector3._DownReadOnly = Vector3.Down(); Vector3._LeftHandedForwardReadOnly = Vector3.Forward(false); Vector3._RightHandedForwardReadOnly = Vector3.Forward(true); Vector3._LeftHandedBackwardReadOnly = Vector3.Backward(false); Vector3._RightHandedBackwardReadOnly = Vector3.Backward(true); Vector3._RightReadOnly = Vector3.Right(); Vector3._LeftReadOnly = Vector3.Left(); Vector3._ZeroReadOnly = Vector3.Zero(); Vector3._OneReadOnly = Vector3.One(); Vector3; Object.defineProperties(Vector3.prototype, { dimension: { value: [3] }, rank: { value: 1 } }); Vector4 = class _Vector4 { static { __name(this, "Vector4"); } // --------------------------------- // Getters / setters (same pattern as Vector3) // --------------------------------- /** Gets or sets the x coordinate */ get x() { return this._x; } set x(value) { this._x = value; this._isDirty = true; } /** Gets or sets the y coordinate */ get y() { return this._y; } set y(value) { this._y = value; this._isDirty = true; } /** Gets or sets the z coordinate */ get z() { return this._z; } set z(value) { this._z = value; this._isDirty = true; } /** Gets or sets the w coordinate */ get w() { return this._w; } set w(value) { this._w = value; this._isDirty = true; } /** * Creates a Vector4 object from the given floats. * @param x x value of the vector * @param y y value of the vector * @param z z value of the vector * @param w w value of the vector */ constructor(x = 0, y = 0, z = 0, w = 0) { this._isDirty = true; this._x = x; this._y = y; this._z = z; this._w = w; } /** * Returns the string with the Vector4 coordinates. * @returns a string containing all the vector values */ toString() { return `{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`; } /** * Returns the string "Vector4". * @returns "Vector4" */ getClassName() { return "Vector4"; } /** * Returns the Vector4 hash code. * @returns a unique hash code */ getHashCode() { const x = ExtractAsInt2(this._x); const y = ExtractAsInt2(this._y); const z = ExtractAsInt2(this._z); const w = ExtractAsInt2(this._w); let hash = x; hash = hash * 397 ^ y; hash = hash * 397 ^ z; hash = hash * 397 ^ w; return hash; } // Operators /** * Returns a new array populated with 4 elements : the Vector4 coordinates. * @returns the resulting array */ asArray() { return [this._x, this._y, this._z, this._w]; } /** * Populates the given array from the given index with the Vector4 coordinates. * @param array array to populate * @param index index of the array to start at (default: 0) * @returns the Vector4. */ toArray(array, index) { if (index === void 0) { index = 0; } array[index] = this._x; array[index + 1] = this._y; array[index + 2] = this._z; array[index + 3] = this._w; return this; } /** * Update the current vector from an array * @param array defines the destination array * @param offset defines the offset in the destination array * @returns the current Vector3 */ fromArray(array, offset = 0) { _Vector4.FromArrayToRef(array, offset, this); return this; } /** * Adds the given vector to the current Vector4. * @param otherVector the vector to add * @returns the updated Vector4. */ addInPlace(otherVector) { this.x += otherVector._x; this.y += otherVector._y; this.z += otherVector._z; this.w += otherVector._w; return this; } /** * Adds the given coordinates to the current Vector4 * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @param w defines the w coordinate of the operand * @returns the current updated Vector4 */ addInPlaceFromFloats(x, y, z, w) { this.x += x; this.y += y; this.z += z; this.w += w; return this; } /** * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one. * @param otherVector the vector to add * @returns the resulting vector */ add(otherVector) { return new _Vector4(this._x + otherVector.x, this._y + otherVector.y, this._z + otherVector.z, this._w + otherVector.w); } /** * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one. * @param otherVector the vector to add * @param result the vector to store the result * @returns result input */ addToRef(otherVector, result) { result.x = this._x + otherVector.x; result.y = this._y + otherVector.y; result.z = this._z + otherVector.z; result.w = this._w + otherVector.w; return result; } /** * Subtract in place the given vector from the current Vector4. * @param otherVector the vector to subtract * @returns the updated Vector4. */ subtractInPlace(otherVector) { this.x -= otherVector.x; this.y -= otherVector.y; this.z -= otherVector.z; this.w -= otherVector.w; return this; } /** * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4. * @param otherVector the vector to add * @returns the new vector with the result */ subtract(otherVector) { return new _Vector4(this._x - otherVector.x, this._y - otherVector.y, this._z - otherVector.z, this._w - otherVector.w); } /** * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4. * @param otherVector the vector to subtract * @param result the vector to store the result * @returns result input */ subtractToRef(otherVector, result) { result.x = this._x - otherVector.x; result.y = this._y - otherVector.y; result.z = this._z - otherVector.z; result.w = this._w - otherVector.w; return result; } /** * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates. * @param x value to subtract * @param y value to subtract * @param z value to subtract * @param w value to subtract * @returns new vector containing the result */ subtractFromFloats(x, y, z, w) { return new _Vector4(this._x - x, this._y - y, this._z - z, this._w - w); } /** * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates. * @param x value to subtract * @param y value to subtract * @param z value to subtract * @param w value to subtract * @param result the vector to store the result in * @returns result input */ subtractFromFloatsToRef(x, y, z, w, result) { result.x = this._x - x; result.y = this._y - y; result.z = this._z - z; result.w = this._w - w; return result; } /** * Returns a new Vector4 set with the current Vector4 negated coordinates. * @returns a new vector with the negated values */ negate() { return new _Vector4(-this._x, -this._y, -this._z, -this._w); } /** * Negate this vector in place * @returns this */ negateInPlace() { this.x *= -1; this.y *= -1; this.z *= -1; this.w *= -1; return this; } /** * Negate the current Vector4 and stores the result in the given vector "result" coordinates * @param result defines the Vector3 object where to store the result * @returns the result */ negateToRef(result) { result.x = -this._x; result.y = -this._y; result.z = -this._z; result.w = -this._w; return result; } /** * Multiplies the current Vector4 coordinates by scale (float). * @param scale the number to scale with * @returns the updated Vector4. */ scaleInPlace(scale) { this.x *= scale; this.y *= scale; this.z *= scale; this.w *= scale; return this; } /** * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float). * @param scale the number to scale with * @returns a new vector with the result */ scale(scale) { return new _Vector4(this._x * scale, this._y * scale, this._z * scale, this._w * scale); } /** * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float). * @param scale the number to scale with * @param result a vector to store the result in * @returns result input */ scaleToRef(scale, result) { result.x = this._x * scale; result.y = this._y * scale; result.z = this._z * scale; result.w = this._w * scale; return result; } /** * Scale the current Vector4 values by a factor and add the result to a given Vector4 * @param scale defines the scale factor * @param result defines the Vector4 object where to store the result * @returns result input */ scaleAndAddToRef(scale, result) { result.x += this._x * scale; result.y += this._y * scale; result.z += this._z * scale; result.w += this._w * scale; return result; } /** * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones. * @param otherVector the vector to compare against * @returns true if they are equal */ equals(otherVector) { return otherVector && this._x === otherVector.x && this._y === otherVector.y && this._z === otherVector.z && this._w === otherVector.w; } /** * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones. * @param otherVector vector to compare against * @param epsilon (Default: very small number) * @returns true if they are equal */ equalsWithEpsilon(otherVector, epsilon = Epsilon) { return otherVector && WithinEpsilon(this._x, otherVector.x, epsilon) && WithinEpsilon(this._y, otherVector.y, epsilon) && WithinEpsilon(this._z, otherVector.z, epsilon) && WithinEpsilon(this._w, otherVector.w, epsilon); } /** * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates. * @param x x value to compare against * @param y y value to compare against * @param z z value to compare against * @param w w value to compare against * @returns true if equal */ equalsToFloats(x, y, z, w) { return this._x === x && this._y === y && this._z === z && this._w === w; } /** * Multiplies in place the current Vector4 by the given one. * @param otherVector vector to multiple with * @returns the updated Vector4. */ multiplyInPlace(otherVector) { this.x *= otherVector.x; this.y *= otherVector.y; this.z *= otherVector.z; this.w *= otherVector.w; return this; } /** * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one. * @param otherVector vector to multiple with * @returns resulting new vector */ multiply(otherVector) { return new _Vector4(this._x * otherVector.x, this._y * otherVector.y, this._z * otherVector.z, this._w * otherVector.w); } /** * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one. * @param otherVector vector to multiple with * @param result vector to store the result * @returns result input */ multiplyToRef(otherVector, result) { result.x = this._x * otherVector.x; result.y = this._y * otherVector.y; result.z = this._z * otherVector.z; result.w = this._w * otherVector.w; return result; } /** * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates. * @param x x value multiply with * @param y y value multiply with * @param z z value multiply with * @param w w value multiply with * @returns resulting new vector */ multiplyByFloats(x, y, z, w) { return new _Vector4(this._x * x, this._y * y, this._z * z, this._w * w); } /** * Returns a new Vector4 set with the division result of the current Vector4 by the given one. * @param otherVector vector to devide with * @returns resulting new vector */ divide(otherVector) { return new _Vector4(this._x / otherVector.x, this._y / otherVector.y, this._z / otherVector.z, this._w / otherVector.w); } /** * Updates the given vector "result" with the division result of the current Vector4 by the given one. * @param otherVector vector to devide with * @param result vector to store the result * @returns result input */ divideToRef(otherVector, result) { result.x = this._x / otherVector.x; result.y = this._y / otherVector.y; result.z = this._z / otherVector.z; result.w = this._w / otherVector.w; return result; } /** * Divides the current Vector3 coordinates by the given ones. * @param otherVector vector to devide with * @returns the updated Vector3. */ divideInPlace(otherVector) { return this.divideToRef(otherVector, this); } /** * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones * @param other defines the second operand * @returns the current updated Vector4 */ minimizeInPlace(other) { if (other.x < this._x) { this.x = other.x; } if (other.y < this._y) { this.y = other.y; } if (other.z < this._z) { this.z = other.z; } if (other.w < this._w) { this.w = other.w; } return this; } /** * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones * @param other defines the second operand * @returns the current updated Vector4 */ maximizeInPlace(other) { if (other.x > this._x) { this.x = other.x; } if (other.y > this._y) { this.y = other.y; } if (other.z > this._z) { this.z = other.z; } if (other.w > this._w) { this.w = other.w; } return this; } /** * Updates the current Vector4 with the minimal coordinate values between its and the given coordinates * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @param w defines the w coordinate of the operand * @returns the current updated Vector4 */ minimizeInPlaceFromFloats(x, y, z, w) { this.x = Math.min(x, this._x); this.y = Math.min(y, this._y); this.z = Math.min(z, this._z); this.w = Math.min(w, this._w); return this; } /** * Updates the current Vector4 with the maximal coordinate values between its and the given coordinates. * @param x defines the x coordinate of the operand * @param y defines the y coordinate of the operand * @param z defines the z coordinate of the operand * @param w defines the w coordinate of the operand * @returns the current updated Vector4 */ maximizeInPlaceFromFloats(x, y, z, w) { this.x = Math.max(x, this._x); this.y = Math.max(y, this._y); this.z = Math.max(z, this._z); this.w = Math.max(w, this._w); return this; } /** * Gets the current Vector4's floored values and stores them in result * @param result the vector to store the result in * @returns the result vector */ floorToRef(result) { result.x = Math.floor(this._x); result.y = Math.floor(this._y); result.z = Math.floor(this._z); result.w = Math.floor(this._w); return result; } /** * Gets a new Vector4 from current Vector4 floored values * @returns a new Vector4 */ floor() { return new _Vector4(Math.floor(this._x), Math.floor(this._y), Math.floor(this._z), Math.floor(this._w)); } /** * Gets the current Vector4's fractional values and stores them in result * @param result the vector to store the result in * @returns the result vector */ fractToRef(result) { result.x = this._x - Math.floor(this._x); result.y = this._y - Math.floor(this._y); result.z = this._z - Math.floor(this._z); result.w = this._w - Math.floor(this._w); return result; } /** * Gets a new Vector4 from current Vector4 fractional values * @returns a new Vector4 */ fract() { return new _Vector4(this._x - Math.floor(this._x), this._y - Math.floor(this._y), this._z - Math.floor(this._z), this._w - Math.floor(this._w)); } // Properties /** * Returns the Vector4 length (float). * @returns the length */ length() { return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); } /** * Returns the Vector4 squared length (float). * @returns the length squared */ lengthSquared() { return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; } // Methods /** * Normalizes in place the Vector4. * @returns the updated Vector4. */ normalize() { return this.normalizeFromLength(this.length()); } /** * Normalize the current Vector4 with the given input length. * Please note that this is an in place operation. * @param len the length of the vector * @returns the current updated Vector4 */ normalizeFromLength(len) { if (len === 0 || len === 1) { return this; } return this.scaleInPlace(1 / len); } /** * Normalize the current Vector4 to a new vector * @returns the new Vector4 */ normalizeToNew() { return this.normalizeToRef(new _Vector4()); } /** * Normalize the current Vector4 to the reference * @param reference define the Vector4 to update * @returns the updated Vector4 */ normalizeToRef(reference) { const len = this.length(); if (len === 0 || len === 1) { reference.x = this._x; reference.y = this._y; reference.z = this._z; reference.w = this._w; return reference; } return this.scaleToRef(1 / len, reference); } /** * Returns a new Vector3 from the Vector4 (x, y, z) coordinates. * @returns this converted to a new vector3 */ toVector3() { return new Vector3(this._x, this._y, this._z); } /** * Returns a new Vector4 copied from the current one. * @returns the new cloned vector */ clone() { return new _Vector4(this._x, this._y, this._z, this._w); } /** * Updates the current Vector4 with the given one coordinates. * @param source the source vector to copy from * @returns the updated Vector4. */ copyFrom(source) { this.x = source.x; this.y = source.y; this.z = source.z; this.w = source.w; return this; } /** * Updates the current Vector4 coordinates with the given floats. * @param x float to copy from * @param y float to copy from * @param z float to copy from * @param w float to copy from * @returns the updated Vector4. */ copyFromFloats(x, y, z, w) { this.x = x; this.y = y; this.z = z; this.w = w; return this; } /** * Updates the current Vector4 coordinates with the given floats. * @param x float to set from * @param y float to set from * @param z float to set from * @param w float to set from * @returns the updated Vector4. */ set(x, y, z, w) { return this.copyFromFloats(x, y, z, w); } /** * Copies the given float to the current Vector4 coordinates * @param v defines the x, y, z and w coordinates of the operand * @returns the current updated Vector4 */ setAll(v) { this.x = this.y = this.z = this.w = v; return this; } /** * Returns the dot product (float) between the current vectors and "otherVector" * @param otherVector defines the right operand * @returns the dot product */ dot(otherVector) { return this._x * otherVector.x + this._y * otherVector.y + this._z * otherVector.z + this._w * otherVector.w; } // Statics /** * Returns a new Vector4 set from the starting index of the given array. * @param array the array to pull values from * @param offset the offset into the array to start at * @returns the new vector */ static FromArray(array, offset) { if (!offset) { offset = 0; } return new _Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]); } /** * Updates the given vector "result" from the starting index of the given array. * @param array the array to pull values from * @param offset the offset into the array to start at * @param result the vector to store the result in * @returns result input */ static FromArrayToRef(array, offset, result) { result.x = array[offset]; result.y = array[offset + 1]; result.z = array[offset + 2]; result.w = array[offset + 3]; return result; } /** * Updates the given vector "result" from the starting index of the given Float32Array. * @param array the array to pull values from * @param offset the offset into the array to start at * @param result the vector to store the result in * @returns result input */ static FromFloatArrayToRef(array, offset, result) { _Vector4.FromArrayToRef(array, offset, result); return result; } /** * Updates the given vector "result" coordinates from the given floats. * @param x float to set from * @param y float to set from * @param z float to set from * @param w float to set from * @param result the vector to the floats in * @returns result input */ static FromFloatsToRef(x, y, z, w, result) { result.x = x; result.y = y; result.z = z; result.w = w; return result; } /** * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0) * @returns the new vector */ static Zero() { return new _Vector4(0, 0, 0, 0); } /** * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0) * @returns the new vector */ static One() { return new _Vector4(1, 1, 1, 1); } /** * Returns a new Vector4 with random values between min and max * @param min the minimum random value * @param max the maximum random value * @returns a Vector4 with random values between min and max */ static Random(min = 0, max = 1) { return new _Vector4(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max), RandomRange(min, max)); } /** * Sets a Vector4 with random values between min and max * @param min the minimum random value * @param max the maximum random value * @param ref the ref to store the values in * @returns the ref with random values between min and max */ static RandomToRef(min = 0, max = 1, ref) { ref.x = RandomRange(min, max); ref.y = RandomRange(min, max); ref.z = RandomRange(min, max); ref.w = RandomRange(min, max); return ref; } /** * Returns a new Vector4 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max" * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one * @param value defines the current value * @param min defines the lower range value * @param max defines the upper range value * @returns the new Vector4 */ static Clamp(value, min, max) { return _Vector4.ClampToRef(value, min, max, new _Vector4()); } /** * Sets the given vector "result" with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max" * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one * @param value defines the current value * @param min defines the lower range value * @param max defines the upper range value * @param result defines the Vector4 where to store the result * @returns result input */ static ClampToRef(value, min, max, result) { result.x = Clamp(value.x, min.x, max.x); result.y = Clamp(value.y, min.y, max.y); result.z = Clamp(value.z, min.z, max.z); result.w = Clamp(value.w, min.w, max.w); return result; } /** * Checks if a given vector is inside a specific range * Example Playground https://playground.babylonjs.com/#R1F8YU#75 * @param v defines the vector to test * @param min defines the minimum range * @param max defines the maximum range */ static CheckExtends(v, min, max) { min.minimizeInPlace(v); max.maximizeInPlace(v); } /** * Gets a zero Vector4 that must not be updated */ static get ZeroReadOnly() { return _Vector4._ZeroReadOnly; } /** * Returns a new normalized Vector4 from the given one. * @param vector the vector to normalize * @returns the vector */ static Normalize(vector) { return _Vector4.NormalizeToRef(vector, new _Vector4()); } /** * Updates the given vector "result" from the normalization of the given one. * @param vector the vector to normalize * @param result the vector to store the result in * @returns result input */ static NormalizeToRef(vector, result) { vector.normalizeToRef(result); return result; } /** * Returns a vector with the minimum values from the left and right vectors * @param left left vector to minimize * @param right right vector to minimize * @returns a new vector with the minimum of the left and right vector values */ static Minimize(left, right) { const min = new _Vector4(); min.copyFrom(left); min.minimizeInPlace(right); return min; } /** * Returns a vector with the maximum values from the left and right vectors * @param left left vector to maximize * @param right right vector to maximize * @returns a new vector with the maximum of the left and right vector values */ static Maximize(left, right) { const max = new _Vector4(); max.copyFrom(left); max.maximizeInPlace(right); return max; } /** * Returns the distance (float) between the vectors "value1" and "value2". * @param value1 value to calulate the distance between * @param value2 value to calulate the distance between * @returns the distance between the two vectors */ static Distance(value1, value2) { return Math.sqrt(_Vector4.DistanceSquared(value1, value2)); } /** * Returns the squared distance (float) between the vectors "value1" and "value2". * @param value1 value to calulate the distance between * @param value2 value to calulate the distance between * @returns the distance between the two vectors squared */ static DistanceSquared(value1, value2) { const x = value1.x - value2.x; const y = value1.y - value2.y; const z = value1.z - value2.z; const w = value1.w - value2.w; return x * x + y * y + z * z + w * w; } /** * Returns a new Vector4 located at the center between the vectors "value1" and "value2". * @param value1 value to calulate the center between * @param value2 value to calulate the center between * @returns the center between the two vectors */ static Center(value1, value2) { return _Vector4.CenterToRef(value1, value2, new _Vector4()); } /** * Gets the center of the vectors "value1" and "value2" and stores the result in the vector "ref" * @param value1 defines first vector * @param value2 defines second vector * @param ref defines third vector * @returns ref */ static CenterToRef(value1, value2, ref) { ref.x = (value1.x + value2.x) / 2; ref.y = (value1.y + value2.y) / 2; ref.z = (value1.z + value2.z) / 2; ref.w = (value1.w + value2.w) / 2; return ref; } /** * Returns a new Vector4 set with the result of the transformation by the given matrix of the given vector. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account) * The difference with Vector3.TransformCoordinates is that the w component is not used to divide the other coordinates but is returned in the w coordinate instead * @param vector defines the Vector3 to transform * @param transformation defines the transformation matrix * @returns the transformed Vector4 */ static TransformCoordinates(vector, transformation) { return _Vector4.TransformCoordinatesToRef(vector, transformation, new _Vector4()); } /** * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account) * The difference with Vector3.TransformCoordinatesToRef is that the w component is not used to divide the other coordinates but is returned in the w coordinate instead * @param vector defines the Vector3 to transform * @param transformation defines the transformation matrix * @param result defines the Vector4 where to store the result * @returns result input */ static TransformCoordinatesToRef(vector, transformation, result) { _Vector4.TransformCoordinatesFromFloatsToRef(vector._x, vector._y, vector._z, transformation, result); return result; } /** * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z) * This method computes tranformed coordinates only, not transformed direction vectors * The difference with Vector3.TransformCoordinatesFromFloatsToRef is that the w component is not used to divide the other coordinates but is returned in the w coordinate instead * @param x define the x coordinate of the source vector * @param y define the y coordinate of the source vector * @param z define the z coordinate of the source vector * @param transformation defines the transformation matrix * @param result defines the Vector4 where to store the result * @returns result input */ static TransformCoordinatesFromFloatsToRef(x, y, z, transformation, result) { const m = transformation.m; const rx = x * m[0] + y * m[4] + z * m[8] + m[12]; const ry = x * m[1] + y * m[5] + z * m[9] + m[13]; const rz = x * m[2] + y * m[6] + z * m[10] + m[14]; const rw = x * m[3] + y * m[7] + z * m[11] + m[15]; result.x = rx; result.y = ry; result.z = rz; result.w = rw; return result; } /** * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector. * This methods computes transformed normalized direction vectors only. * @param vector the vector to transform * @param transformation the transformation matrix to apply * @returns the new vector */ static TransformNormal(vector, transformation) { return _Vector4.TransformNormalToRef(vector, transformation, new _Vector4()); } /** * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector. * This methods computes transformed normalized direction vectors only. * @param vector the vector to transform * @param transformation the transformation matrix to apply * @param result the vector to store the result in * @returns result input */ static TransformNormalToRef(vector, transformation, result) { const m = transformation.m; const x = vector.x * m[0] + vector.y * m[4] + vector.z * m[8]; const y = vector.x * m[1] + vector.y * m[5] + vector.z * m[9]; const z = vector.x * m[2] + vector.y * m[6] + vector.z * m[10]; result.x = x; result.y = y; result.z = z; result.w = vector.w; return result; } /** * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w). * This methods computes transformed normalized direction vectors only. * @param x value to transform * @param y value to transform * @param z value to transform * @param w value to transform * @param transformation the transformation matrix to apply * @param result the vector to store the results in * @returns result input */ static TransformNormalFromFloatsToRef(x, y, z, w, transformation, result) { const m = transformation.m; result.x = x * m[0] + y * m[4] + z * m[8]; result.y = x * m[1] + y * m[5] + z * m[9]; result.z = x * m[2] + y * m[6] + z * m[10]; result.w = w; return result; } /** * Creates a new Vector4 from a Vector3 * @param source defines the source data * @param w defines the 4th component (default is 0) * @returns a new Vector4 */ static FromVector3(source, w = 0) { return new _Vector4(source._x, source._y, source._z, w); } /** * Returns the dot product (float) between the vectors "left" and "right" * @param left defines the left operand * @param right defines the right operand * @returns the dot product */ static Dot(left, right) { return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w; } }; Vector4._V8PerformanceHack = new Vector4(0.5, 0.5, 0.5, 0.5); Vector4._ZeroReadOnly = Vector4.Zero(); Vector4; Object.defineProperties(Vector4.prototype, { dimension: { value: [4] }, rank: { value: 1 } }); Quaternion = class _Quaternion { static { __name(this, "Quaternion"); } /** Gets or sets the x coordinate */ get x() { return this._x; } set x(value) { this._x = value; this._isDirty = true; } /** Gets or sets the y coordinate */ get y() { return this._y; } set y(value) { this._y = value; this._isDirty = true; } /** Gets or sets the z coordinate */ get z() { return this._z; } set z(value) { this._z = value; this._isDirty = true; } /** Gets or sets the w coordinate */ get w() { return this._w; } set w(value) { this._w = value; this._isDirty = true; } /** * Creates a new Quaternion from the given floats * @param x defines the first component (0 by default) * @param y defines the second component (0 by default) * @param z defines the third component (0 by default) * @param w defines the fourth component (1.0 by default) */ constructor(x = 0, y = 0, z = 0, w = 1) { this._isDirty = true; this._x = x; this._y = y; this._z = z; this._w = w; } /** * Gets a string representation for the current quaternion * @returns a string with the Quaternion coordinates */ toString() { return `{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`; } /** * Gets the class name of the quaternion * @returns the string "Quaternion" */ getClassName() { return "Quaternion"; } /** * Gets a hash code for this quaternion * @returns the quaternion hash code */ getHashCode() { const x = ExtractAsInt2(this._x); const y = ExtractAsInt2(this._y); const z = ExtractAsInt2(this._z); const w = ExtractAsInt2(this._w); let hash = x; hash = hash * 397 ^ y; hash = hash * 397 ^ z; hash = hash * 397 ^ w; return hash; } /** * Copy the quaternion to an array * Example Playground https://playground.babylonjs.com/#L49EJ7#13 * @returns a new array populated with 4 elements from the quaternion coordinates */ asArray() { return [this._x, this._y, this._z, this._w]; } /** * Stores from the starting index in the given array the Quaternion successive values * Example Playground https://playground.babylonjs.com/#L49EJ7#59 * @param array defines the array where to store the x,y,z,w components * @param index defines an optional index in the target array to define where to start storing values * @returns the current Quaternion object */ toArray(array, index = 0) { array[index] = this._x; array[index + 1] = this._y; array[index + 2] = this._z; array[index + 3] = this._w; return this; } fromArray(array, index = 0) { return _Quaternion.FromArrayToRef(array, index, this); } /** * Check if two quaternions are equals * Example Playground https://playground.babylonjs.com/#L49EJ7#38 * @param otherQuaternion defines the second operand * @returns true if the current quaternion and the given one coordinates are strictly equals */ equals(otherQuaternion) { return otherQuaternion && this._x === otherQuaternion._x && this._y === otherQuaternion._y && this._z === otherQuaternion._z && this._w === otherQuaternion._w; } /** * Gets a boolean if two quaternions are equals (using an epsilon value) * Example Playground https://playground.babylonjs.com/#L49EJ7#37 * @param otherQuaternion defines the other quaternion * @param epsilon defines the minimal distance to consider equality * @returns true if the given quaternion coordinates are close to the current ones by a distance of epsilon. */ equalsWithEpsilon(otherQuaternion, epsilon = Epsilon) { return otherQuaternion && WithinEpsilon(this._x, otherQuaternion._x, epsilon) && WithinEpsilon(this._y, otherQuaternion._y, epsilon) && WithinEpsilon(this._z, otherQuaternion._z, epsilon) && WithinEpsilon(this._w, otherQuaternion._w, epsilon); } /** * Gets a boolean if two quaternions are equals (using an epsilon value), taking care of double cover : https://www.reedbeta.com/blog/why-quaternions-double-cover/ * @param otherQuaternion defines the other quaternion * @param epsilon defines the minimal distance to consider equality * @returns true if the given quaternion coordinates are close to the current ones by a distance of epsilon. */ isApprox(otherQuaternion, epsilon = Epsilon) { return otherQuaternion && (WithinEpsilon(this._x, otherQuaternion._x, epsilon) && WithinEpsilon(this._y, otherQuaternion._y, epsilon) && WithinEpsilon(this._z, otherQuaternion._z, epsilon) && WithinEpsilon(this._w, otherQuaternion._w, epsilon) || WithinEpsilon(this._x, -otherQuaternion._x, epsilon) && WithinEpsilon(this._y, -otherQuaternion._y, epsilon) && WithinEpsilon(this._z, -otherQuaternion._z, epsilon) && WithinEpsilon(this._w, -otherQuaternion._w, epsilon)); } /** * Clone the current quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#12 * @returns a new quaternion copied from the current one */ clone() { return new _Quaternion(this._x, this._y, this._z, this._w); } /** * Copy a quaternion to the current one * Example Playground https://playground.babylonjs.com/#L49EJ7#86 * @param other defines the other quaternion * @returns the updated current quaternion */ copyFrom(other) { this._x = other._x; this._y = other._y; this._z = other._z; this._w = other._w; this._isDirty = true; return this; } /** * Updates the current quaternion with the given float coordinates * Example Playground https://playground.babylonjs.com/#L49EJ7#87 * @param x defines the x coordinate * @param y defines the y coordinate * @param z defines the z coordinate * @param w defines the w coordinate * @returns the updated current quaternion */ copyFromFloats(x, y, z, w) { this._x = x; this._y = y; this._z = z; this._w = w; this._isDirty = true; return this; } /** * Updates the current quaternion from the given float coordinates * Example Playground https://playground.babylonjs.com/#L49EJ7#56 * @param x defines the x coordinate * @param y defines the y coordinate * @param z defines the z coordinate * @param w defines the w coordinate * @returns the updated current quaternion */ set(x, y, z, w) { return this.copyFromFloats(x, y, z, w); } setAll(value) { return this.copyFromFloats(value, value, value, value); } /** * Adds two quaternions * Example Playground https://playground.babylonjs.com/#L49EJ7#10 * @param other defines the second operand * @returns a new quaternion as the addition result of the given one and the current quaternion */ add(other) { return new _Quaternion(this._x + other._x, this._y + other._y, this._z + other._z, this._w + other._w); } /** * Add a quaternion to the current one * Example Playground https://playground.babylonjs.com/#L49EJ7#11 * @param other defines the quaternion to add * @returns the current quaternion */ addInPlace(other) { this._x += other._x; this._y += other._y; this._z += other._z; this._w += other._w; this._isDirty = true; return this; } addToRef(other, result) { result._x = this._x + other._x; result._y = this._y + other._y; result._z = this._z + other._z; result._w = this._w + other._w; result._isDirty = true; return result; } addInPlaceFromFloats(x, y, z, w) { this._x += x; this._y += y; this._z += z; this._w += w; this._isDirty = true; return this; } subtractToRef(other, result) { result._x = this._x - other._x; result._y = this._y - other._y; result._z = this._z - other._z; result._w = this._w - other._w; result._isDirty = true; return result; } subtractFromFloats(x, y, z, w) { return this.subtractFromFloatsToRef(x, y, z, w, new _Quaternion()); } subtractFromFloatsToRef(x, y, z, w, result) { result._x = this._x - x; result._y = this._y - y; result._z = this._z - z; result._w = this._w - w; result._isDirty = true; return result; } /** * Subtract two quaternions * Example Playground https://playground.babylonjs.com/#L49EJ7#57 * @param other defines the second operand * @returns a new quaternion as the subtraction result of the given one from the current one */ subtract(other) { return new _Quaternion(this._x - other._x, this._y - other._y, this._z - other._z, this._w - other._w); } /** * Subtract a quaternion to the current one * Example Playground https://playground.babylonjs.com/#L49EJ7#58 * @param other defines the quaternion to subtract * @returns the current quaternion */ subtractInPlace(other) { this._x -= other._x; this._y -= other._y; this._z -= other._z; this._w -= other._w; this._isDirty = true; return this; } /** * Multiplies the current quaternion by a scale factor * Example Playground https://playground.babylonjs.com/#L49EJ7#88 * @param value defines the scale factor * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale" */ scale(value) { return new _Quaternion(this._x * value, this._y * value, this._z * value, this._w * value); } /** * Scale the current quaternion values by a factor and stores the result to a given quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#89 * @param scale defines the scale factor * @param result defines the Quaternion object where to store the result * @returns result input */ scaleToRef(scale, result) { result._x = this._x * scale; result._y = this._y * scale; result._z = this._z * scale; result._w = this._w * scale; result._isDirty = true; return result; } /** * Multiplies in place the current quaternion by a scale factor * Example Playground https://playground.babylonjs.com/#L49EJ7#90 * @param value defines the scale factor * @returns the current modified quaternion */ scaleInPlace(value) { this._x *= value; this._y *= value; this._z *= value; this._w *= value; this._isDirty = true; return this; } /** * Scale the current quaternion values by a factor and add the result to a given quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#91 * @param scale defines the scale factor * @param result defines the Quaternion object where to store the result * @returns result input */ scaleAndAddToRef(scale, result) { result._x += this._x * scale; result._y += this._y * scale; result._z += this._z * scale; result._w += this._w * scale; result._isDirty = true; return result; } /** * Multiplies two quaternions * Example Playground https://playground.babylonjs.com/#L49EJ7#43 * @param q1 defines the second operand * @returns a new quaternion set as the multiplication result of the current one with the given one "q1" */ multiply(q1) { const result = new _Quaternion(0, 0, 0, 1); this.multiplyToRef(q1, result); return result; } /** * Sets the given "result" as the multiplication result of the current one with the given one "q1" * Example Playground https://playground.babylonjs.com/#L49EJ7#45 * @param q1 defines the second operand * @param result defines the target quaternion * @returns the current quaternion */ multiplyToRef(q1, result) { const x = this._x * q1._w + this._y * q1._z - this._z * q1._y + this._w * q1._x; const y = -this._x * q1._z + this._y * q1._w + this._z * q1._x + this._w * q1._y; const z = this._x * q1._y - this._y * q1._x + this._z * q1._w + this._w * q1._z; const w = -this._x * q1._x - this._y * q1._y - this._z * q1._z + this._w * q1._w; result.copyFromFloats(x, y, z, w); return result; } /** * Updates the current quaternion with the multiplication of itself with the given one "q1" * Example Playground https://playground.babylonjs.com/#L49EJ7#46 * @param other defines the second operand * @returns the currentupdated quaternion */ multiplyInPlace(other) { return this.multiplyToRef(other, this); } multiplyByFloats(x, y, z, w) { this._x *= x; this._y *= y; this._z *= z; this._w *= w; this._isDirty = true; return this; } /** * @internal * Do not use */ divide(_other) { throw new ReferenceError("Can not divide a quaternion"); } /** * @internal * Do not use */ divideToRef(_other, _result) { throw new ReferenceError("Can not divide a quaternion"); } /** * @internal * Do not use */ divideInPlace(_other) { throw new ReferenceError("Can not divide a quaternion"); } /** * @internal * Do not use */ minimizeInPlace() { throw new ReferenceError("Can not minimize a quaternion"); } /** * @internal * Do not use */ minimizeInPlaceFromFloats() { throw new ReferenceError("Can not minimize a quaternion"); } /** * @internal * Do not use */ maximizeInPlace() { throw new ReferenceError("Can not maximize a quaternion"); } /** * @internal * Do not use */ maximizeInPlaceFromFloats() { throw new ReferenceError("Can not maximize a quaternion"); } negate() { return this.negateToRef(new _Quaternion()); } negateInPlace() { this._x = -this._x; this._y = -this._y; this._z = -this._z; this._w = -this._w; this._isDirty = true; return this; } negateToRef(result) { result._x = -this._x; result._y = -this._y; result._z = -this._z; result._w = -this._w; result._isDirty = true; return result; } equalsToFloats(x, y, z, w) { return this._x === x && this._y === y && this._z === z && this._w === w; } /** * @internal * Do not use */ floorToRef(_result) { throw new ReferenceError("Can not floor a quaternion"); } /** * @internal * Do not use */ floor() { throw new ReferenceError("Can not floor a quaternion"); } /** * @internal * Do not use */ fractToRef(_result) { throw new ReferenceError("Can not fract a quaternion"); } /** * @internal * Do not use */ fract() { throw new ReferenceError("Can not fract a quaternion"); } /** * Conjugates the current quaternion and stores the result in the given quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#81 * @param ref defines the target quaternion * @returns result input */ conjugateToRef(ref) { ref.copyFromFloats(-this._x, -this._y, -this._z, this._w); return ref; } /** * Conjugates in place the current quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#82 * @returns the current updated quaternion */ conjugateInPlace() { this._x *= -1; this._y *= -1; this._z *= -1; this._isDirty = true; return this; } /** * Conjugates (1-q) the current quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#83 * @returns a new quaternion */ conjugate() { return new _Quaternion(-this._x, -this._y, -this._z, this._w); } /** * Returns the inverse of the current quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#84 * @returns a new quaternion */ invert() { const conjugate = this.conjugate(); const lengthSquared = this.lengthSquared(); if (lengthSquared == 0 || lengthSquared == 1) { return conjugate; } conjugate.scaleInPlace(1 / lengthSquared); return conjugate; } /** * Invert in place the current quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#85 * @returns this quaternion */ invertInPlace() { this.conjugateInPlace(); const lengthSquared = this.lengthSquared(); if (lengthSquared == 0 || lengthSquared == 1) { return this; } this.scaleInPlace(1 / lengthSquared); return this; } /** * Gets squared length of current quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#29 * @returns the quaternion length (float) */ lengthSquared() { return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; } /** * Gets length of current quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#28 * @returns the quaternion length (float) */ length() { return Math.sqrt(this.lengthSquared()); } /** * Normalize in place the current quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#54 * @returns the current updated quaternion */ normalize() { return this.normalizeFromLength(this.length()); } /** * Normalize the current quaternion with the given input length. * Please note that this is an in place operation. * @param len the length of the quaternion * @returns the current updated Quaternion */ normalizeFromLength(len) { if (len === 0 || len === 1) { return this; } return this.scaleInPlace(1 / len); } /** * Normalize a copy of the current quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#55 * @returns the normalized quaternion */ normalizeToNew() { const normalized = new _Quaternion(0, 0, 0, 1); this.normalizeToRef(normalized); return normalized; } /** * Normalize the current Quaternion to the reference * @param reference define the Quaternion to update * @returns the updated Quaternion */ normalizeToRef(reference) { const len = this.length(); if (len === 0 || len === 1) { return reference.copyFromFloats(this._x, this._y, this._z, this._w); } return this.scaleToRef(1 / len, reference); } /** * Returns a new Vector3 set with the Euler angles translated from the current quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#32 * @returns a new Vector3 containing the Euler angles * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/rotation_conventions */ toEulerAngles() { const result = Vector3.Zero(); this.toEulerAnglesToRef(result); return result; } /** * Sets the given vector3 "result" with the Euler angles translated from the current quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#31 * @param result defines the vector which will be filled with the Euler angles * @returns result input * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/rotation_conventions */ toEulerAnglesToRef(result) { const qz = this._z; const qx = this._x; const qy = this._y; const qw = this._w; const zAxisY = qy * qz - qx * qw; const limit = 0.4999999; if (zAxisY < -limit) { result._y = 2 * Math.atan2(qy, qw); result._x = Math.PI / 2; result._z = 0; result._isDirty = true; } else if (zAxisY > limit) { result._y = 2 * Math.atan2(qy, qw); result._x = -Math.PI / 2; result._z = 0; result._isDirty = true; } else { const sqw = qw * qw; const sqz = qz * qz; const sqx = qx * qx; const sqy = qy * qy; result._z = Math.atan2(2 * (qx * qy + qz * qw), -sqz - sqx + sqy + sqw); result._x = Math.asin(-2 * zAxisY); result._y = Math.atan2(2 * (qz * qx + qy * qw), sqz - sqx - sqy + sqw); result._isDirty = true; } return result; } /** * Sets the given vector3 "result" with the Alpha, Beta, Gamma Euler angles translated from the current quaternion * @param result defines the vector which will be filled with the Euler angles * @returns result input * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/rotation_conventions */ toAlphaBetaGammaToRef(result) { const qz = this._z; const qx = this._x; const qy = this._y; const qw = this._w; const sinHalfBeta = Math.sqrt(qx * qx + qy * qy); const cosHalfBeta = Math.sqrt(qz * qz + qw * qw); const beta = 2 * Math.atan2(sinHalfBeta, cosHalfBeta); const gammaPlusAlpha = 2 * Math.atan2(qz, qw); const gammaMinusAlpha = 2 * Math.atan2(qy, qx); const gamma = (gammaPlusAlpha + gammaMinusAlpha) / 2; const alpha = (gammaPlusAlpha - gammaMinusAlpha) / 2; result.set(alpha, beta, gamma); return result; } /** * Updates the given rotation matrix with the current quaternion values * Example Playground https://playground.babylonjs.com/#L49EJ7#67 * @param result defines the target matrix * @returns the updated matrix with the rotation */ toRotationMatrix(result) { Matrix.FromQuaternionToRef(this, result); return result; } /** * Updates the current quaternion from the given rotation matrix values * Example Playground https://playground.babylonjs.com/#L49EJ7#41 * @param matrix defines the source matrix * @returns the current updated quaternion */ fromRotationMatrix(matrix) { _Quaternion.FromRotationMatrixToRef(matrix, this); return this; } /** * Returns the dot product (float) between the current quaternions and "other" * @param other defines the right operand * @returns the dot product */ dot(other) { return this._x * other._x + this._y * other._y + this._z * other._z + this._w * other._w; } /** * Converts the current quaternion to an axis angle representation * @returns the axis and angle in radians */ toAxisAngle() { const axis = Vector3.Zero(); const angle = this.toAxisAngleToRef(axis); return { axis, angle }; } /** * Converts the current quaternion to an axis angle representation * @param axis defines the target axis vector * @returns the angle in radians */ toAxisAngleToRef(axis) { let angle = 0; const sinHalfAngle = Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z); const cosHalfAngle = this._w; if (sinHalfAngle > 0) { angle = 2 * Math.atan2(sinHalfAngle, cosHalfAngle); axis.set(this._x / sinHalfAngle, this._y / sinHalfAngle, this._z / sinHalfAngle); } else { angle = 0; axis.set(1, 0, 0); } return angle; } // Statics /** * Creates a new quaternion from a rotation matrix * Example Playground https://playground.babylonjs.com/#L49EJ7#101 * @param matrix defines the source matrix * @returns a new quaternion created from the given rotation matrix values */ static FromRotationMatrix(matrix) { const result = new _Quaternion(); _Quaternion.FromRotationMatrixToRef(matrix, result); return result; } /** * Updates the given quaternion with the given rotation matrix values * Example Playground https://playground.babylonjs.com/#L49EJ7#102 * @param matrix defines the source matrix * @param result defines the target quaternion * @returns result input */ static FromRotationMatrixToRef(matrix, result) { const data = matrix.m; const m11 = data[0], m12 = data[4], m13 = data[8]; const m21 = data[1], m22 = data[5], m23 = data[9]; const m31 = data[2], m32 = data[6], m33 = data[10]; const trace = m11 + m22 + m33; let s; if (trace > 0) { s = 0.5 / Math.sqrt(trace + 1); result._w = 0.25 / s; result._x = (m32 - m23) * s; result._y = (m13 - m31) * s; result._z = (m21 - m12) * s; result._isDirty = true; } else if (m11 > m22 && m11 > m33) { s = 2 * Math.sqrt(1 + m11 - m22 - m33); result._w = (m32 - m23) / s; result._x = 0.25 * s; result._y = (m12 + m21) / s; result._z = (m13 + m31) / s; result._isDirty = true; } else if (m22 > m33) { s = 2 * Math.sqrt(1 + m22 - m11 - m33); result._w = (m13 - m31) / s; result._x = (m12 + m21) / s; result._y = 0.25 * s; result._z = (m23 + m32) / s; result._isDirty = true; } else { s = 2 * Math.sqrt(1 + m33 - m11 - m22); result._w = (m21 - m12) / s; result._x = (m13 + m31) / s; result._y = (m23 + m32) / s; result._z = 0.25 * s; result._isDirty = true; } return result; } /** * Returns the dot product (float) between the quaternions "left" and "right" * Example Playground https://playground.babylonjs.com/#L49EJ7#61 * @param left defines the left operand * @param right defines the right operand * @returns the dot product */ static Dot(left, right) { return left._x * right._x + left._y * right._y + left._z * right._z + left._w * right._w; } /** * Checks if the orientations of two rotation quaternions are close to each other * Example Playground https://playground.babylonjs.com/#L49EJ7#60 * @param quat0 defines the first quaternion to check * @param quat1 defines the second quaternion to check * @param epsilon defines closeness, 0 same orientation, 1 PI apart, default 0.1 * @returns true if the two quaternions are close to each other within epsilon */ static AreClose(quat0, quat1, epsilon = 0.1) { const dot = _Quaternion.Dot(quat0, quat1); return 1 - dot * dot <= epsilon; } /** * Smooth interpolation between two quaternions using Slerp * Example Playground https://playground.babylonjs.com/#L49EJ7#93 * @param source source quaternion * @param goal goal quaternion * @param deltaTime current interpolation frame * @param lerpTime total interpolation time * @param result the smoothed quaternion * @returns the smoothed quaternion */ static SmoothToRef(source, goal, deltaTime, lerpTime, result) { let slerp = lerpTime === 0 ? 1 : deltaTime / lerpTime; slerp = Clamp(slerp, 0, 1); _Quaternion.SlerpToRef(source, goal, slerp, result); return result; } /** * Creates an empty quaternion * @returns a new quaternion set to (0.0, 0.0, 0.0) */ static Zero() { return new _Quaternion(0, 0, 0, 0); } /** * Inverse a given quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#103 * @param q defines the source quaternion * @returns a new quaternion as the inverted current quaternion */ static Inverse(q) { return new _Quaternion(-q._x, -q._y, -q._z, q._w); } /** * Inverse a given quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#104 * @param q defines the source quaternion * @param result the quaternion the result will be stored in * @returns the result quaternion */ static InverseToRef(q, result) { result.set(-q._x, -q._y, -q._z, q._w); return result; } /** * Creates an identity quaternion * @returns the identity quaternion */ static Identity() { return new _Quaternion(0, 0, 0, 1); } /** * Gets a boolean indicating if the given quaternion is identity * @param quaternion defines the quaternion to check * @returns true if the quaternion is identity */ static IsIdentity(quaternion) { return quaternion && quaternion._x === 0 && quaternion._y === 0 && quaternion._z === 0 && quaternion._w === 1; } /** * Creates a quaternion from a rotation around an axis * Example Playground https://playground.babylonjs.com/#L49EJ7#72 * @param axis defines the axis to use * @param angle defines the angle to use * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float) */ static RotationAxis(axis, angle) { return _Quaternion.RotationAxisToRef(axis, angle, new _Quaternion()); } /** * Creates a rotation around an axis and stores it into the given quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#73 * @param axis defines the axis to use * @param angle defines the angle to use * @param result defines the target quaternion * @returns the target quaternion */ static RotationAxisToRef(axis, angle, result) { result._w = Math.cos(angle / 2); const sinByLength = Math.sin(angle / 2) / axis.length(); result._x = axis._x * sinByLength; result._y = axis._y * sinByLength; result._z = axis._z * sinByLength; result._isDirty = true; return result; } /** * Creates a new quaternion from data stored into an array * Example Playground https://playground.babylonjs.com/#L49EJ7#63 * @param array defines the data source * @param offset defines the offset in the source array where the data starts * @returns a new quaternion */ static FromArray(array, offset) { if (!offset) { offset = 0; } return new _Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]); } /** * Updates the given quaternion "result" from the starting index of the given array. * Example Playground https://playground.babylonjs.com/#L49EJ7#64 * @param array the array to pull values from * @param offset the offset into the array to start at * @param result the quaternion to store the result in * @returns result input */ static FromArrayToRef(array, offset, result) { result._x = array[offset]; result._y = array[offset + 1]; result._z = array[offset + 2]; result._w = array[offset + 3]; result._isDirty = true; return result; } /** * Sets the given quaternion "result" with the given floats. * @param x defines the x coordinate of the source * @param y defines the y coordinate of the source * @param z defines the z coordinate of the source * @param w defines the w coordinate of the source * @param result defines the quaternion where to store the result * @returns the result quaternion */ static FromFloatsToRef(x, y, z, w, result) { result.copyFromFloats(x, y, z, w); return result; } /** * Create a quaternion from Euler rotation angles * Example Playground https://playground.babylonjs.com/#L49EJ7#33 * @param x Pitch * @param y Yaw * @param z Roll * @returns the new Quaternion */ static FromEulerAngles(x, y, z) { const q = new _Quaternion(); _Quaternion.RotationYawPitchRollToRef(y, x, z, q); return q; } /** * Updates a quaternion from Euler rotation angles * Example Playground https://playground.babylonjs.com/#L49EJ7#34 * @param x Pitch * @param y Yaw * @param z Roll * @param result the quaternion to store the result * @returns the updated quaternion */ static FromEulerAnglesToRef(x, y, z, result) { _Quaternion.RotationYawPitchRollToRef(y, x, z, result); return result; } /** * Create a quaternion from Euler rotation vector * Example Playground https://playground.babylonjs.com/#L49EJ7#35 * @param vec the Euler vector (x Pitch, y Yaw, z Roll) * @returns the new Quaternion */ static FromEulerVector(vec) { const q = new _Quaternion(); _Quaternion.RotationYawPitchRollToRef(vec._y, vec._x, vec._z, q); return q; } /** * Updates a quaternion from Euler rotation vector * Example Playground https://playground.babylonjs.com/#L49EJ7#36 * @param vec the Euler vector (x Pitch, y Yaw, z Roll) * @param result the quaternion to store the result * @returns the updated quaternion */ static FromEulerVectorToRef(vec, result) { _Quaternion.RotationYawPitchRollToRef(vec._y, vec._x, vec._z, result); return result; } /** * Updates a quaternion so that it rotates vector vecFrom to vector vecTo * Example Playground - https://playground.babylonjs.com/#L49EJ7#70 * @param vecFrom defines the direction vector from which to rotate * @param vecTo defines the direction vector to which to rotate * @param result the quaternion to store the result * @param epsilon defines the minimal dot value to define vecs as opposite. Default: `BABYLON.Epsilon` * @returns the updated quaternion */ static FromUnitVectorsToRef(vecFrom, vecTo, result, epsilon = Epsilon) { const r = Vector3.Dot(vecFrom, vecTo) + 1; if (r < epsilon) { if (Math.abs(vecFrom.x) > Math.abs(vecFrom.z)) { result.set(-vecFrom.y, vecFrom.x, 0, 0); } else { result.set(0, -vecFrom.z, vecFrom.y, 0); } } else { Vector3.CrossToRef(vecFrom, vecTo, TmpVectors.Vector3[0]); result.set(TmpVectors.Vector3[0].x, TmpVectors.Vector3[0].y, TmpVectors.Vector3[0].z, r); } return result.normalize(); } /** * Creates a new quaternion from the given Euler float angles (y, x, z) * Example Playground https://playground.babylonjs.com/#L49EJ7#77 * @param yaw defines the rotation around Y axis * @param pitch defines the rotation around X axis * @param roll defines the rotation around Z axis * @returns the new quaternion */ static RotationYawPitchRoll(yaw, pitch, roll) { const q = new _Quaternion(); _Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q); return q; } /** * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#561 * @param yaw defines the rotation around Y axis * @param pitch defines the rotation around X axis * @param roll defines the rotation around Z axis * @param result defines the target quaternion * @returns result input */ static RotationYawPitchRollToRef(yaw, pitch, roll, result) { const halfRoll = roll * 0.5; const halfPitch = pitch * 0.5; const halfYaw = yaw * 0.5; const sinRoll = Math.sin(halfRoll); const cosRoll = Math.cos(halfRoll); const sinPitch = Math.sin(halfPitch); const cosPitch = Math.cos(halfPitch); const sinYaw = Math.sin(halfYaw); const cosYaw = Math.cos(halfYaw); result._x = cosYaw * sinPitch * cosRoll + sinYaw * cosPitch * sinRoll; result._y = sinYaw * cosPitch * cosRoll - cosYaw * sinPitch * sinRoll; result._z = cosYaw * cosPitch * sinRoll - sinYaw * sinPitch * cosRoll; result._w = cosYaw * cosPitch * cosRoll + sinYaw * sinPitch * sinRoll; result._isDirty = true; return result; } /** * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation * Example Playground https://playground.babylonjs.com/#L49EJ7#68 * @param alpha defines the rotation around first axis * @param beta defines the rotation around second axis * @param gamma defines the rotation around third axis * @returns the new quaternion */ static RotationAlphaBetaGamma(alpha, beta, gamma) { const result = new _Quaternion(); _Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result); return result; } /** * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#69 * @param alpha defines the rotation around first axis * @param beta defines the rotation around second axis * @param gamma defines the rotation around third axis * @param result defines the target quaternion * @returns result input */ static RotationAlphaBetaGammaToRef(alpha, beta, gamma, result) { const halfGammaPlusAlpha = (gamma + alpha) * 0.5; const halfGammaMinusAlpha = (gamma - alpha) * 0.5; const halfBeta = beta * 0.5; result._x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta); result._y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta); result._z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta); result._w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta); result._isDirty = true; return result; } /** * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) * Example Playground https://playground.babylonjs.com/#L49EJ7#75 * @param axis1 defines the first axis * @param axis2 defines the second axis * @param axis3 defines the third axis * @returns the new quaternion */ static RotationQuaternionFromAxis(axis1, axis2, axis3) { const quat = new _Quaternion(0, 0, 0, 0); _Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat); return quat; } /** * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#76 * @param axis1 defines the first axis * @param axis2 defines the second axis * @param axis3 defines the third axis * @param ref defines the target quaternion * @returns result input */ static RotationQuaternionFromAxisToRef(axis1, axis2, axis3, ref) { const rotMat = MathTmp.Matrix[0]; axis1 = axis1.normalizeToRef(MathTmp.Vector3[0]); axis2 = axis2.normalizeToRef(MathTmp.Vector3[1]); axis3 = axis3.normalizeToRef(MathTmp.Vector3[2]); Matrix.FromXYZAxesToRef(axis1, axis2, axis3, rotMat); _Quaternion.FromRotationMatrixToRef(rotMat, ref); return ref; } /** * Creates a new rotation value to orient an object to look towards the given forward direction, the up direction being oriented like "up". * This function works in left handed mode * Example Playground https://playground.babylonjs.com/#L49EJ7#96 * @param forward defines the forward direction - Must be normalized and orthogonal to up. * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. * @returns A new quaternion oriented toward the specified forward and up. */ static FromLookDirectionLH(forward, up) { const quat = new _Quaternion(); _Quaternion.FromLookDirectionLHToRef(forward, up, quat); return quat; } /** * Creates a new rotation value to orient an object to look towards the given forward direction with the up direction being oriented like "up", and stores it in the target quaternion. * This function works in left handed mode * Example Playground https://playground.babylonjs.com/#L49EJ7#97 * @param forward defines the forward direction - Must be normalized and orthogonal to up. * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. * @param ref defines the target quaternion. * @returns result input */ static FromLookDirectionLHToRef(forward, up, ref) { const rotMat = MathTmp.Matrix[0]; Matrix.LookDirectionLHToRef(forward, up, rotMat); _Quaternion.FromRotationMatrixToRef(rotMat, ref); return ref; } /** * Creates a new rotation value to orient an object to look towards the given forward direction, the up direction being oriented like "up". * This function works in right handed mode * Example Playground https://playground.babylonjs.com/#L49EJ7#98 * @param forward defines the forward direction - Must be normalized and orthogonal to up. * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. * @returns A new quaternion oriented toward the specified forward and up. */ static FromLookDirectionRH(forward, up) { const quat = new _Quaternion(); _Quaternion.FromLookDirectionRHToRef(forward, up, quat); return quat; } /** * Creates a new rotation value to orient an object to look towards the given forward direction with the up direction being oriented like "up", and stores it in the target quaternion. * This function works in right handed mode * Example Playground https://playground.babylonjs.com/#L49EJ7#105 * @param forward defines the forward direction - Must be normalized and orthogonal to up. * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. * @param ref defines the target quaternion. * @returns result input */ static FromLookDirectionRHToRef(forward, up, ref) { const rotMat = MathTmp.Matrix[0]; Matrix.LookDirectionRHToRef(forward, up, rotMat); return _Quaternion.FromRotationMatrixToRef(rotMat, ref); } /** * Interpolates between two quaternions * Example Playground https://playground.babylonjs.com/#L49EJ7#79 * @param left defines first quaternion * @param right defines second quaternion * @param amount defines the gradient to use * @returns the new interpolated quaternion */ static Slerp(left, right, amount) { const result = _Quaternion.Identity(); _Quaternion.SlerpToRef(left, right, amount, result); return result; } /** * Interpolates between two quaternions and stores it into a target quaternion * Example Playground https://playground.babylonjs.com/#L49EJ7#92 * @param left defines first quaternion * @param right defines second quaternion * @param amount defines the gradient to use * @param result defines the target quaternion * @returns result input */ static SlerpToRef(left, right, amount, result) { let num2; let num3; let num4 = left._x * right._x + left._y * right._y + left._z * right._z + left._w * right._w; let flag = false; if (num4 < 0) { flag = true; num4 = -num4; } if (num4 > 0.999999) { num3 = 1 - amount; num2 = flag ? -amount : amount; } else { const num5 = Math.acos(num4); const num6 = 1 / Math.sin(num5); num3 = Math.sin((1 - amount) * num5) * num6; num2 = flag ? -Math.sin(amount * num5) * num6 : Math.sin(amount * num5) * num6; } result._x = num3 * left._x + num2 * right._x; result._y = num3 * left._y + num2 * right._y; result._z = num3 * left._z + num2 * right._z; result._w = num3 * left._w + num2 * right._w; result._isDirty = true; return result; } /** * Interpolate between two quaternions using Hermite interpolation * Example Playground https://playground.babylonjs.com/#L49EJ7#47 * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#hermite-quaternion-spline * @param value1 defines first quaternion * @param tangent1 defines the incoming tangent * @param value2 defines second quaternion * @param tangent2 defines the outgoing tangent * @param amount defines the target quaternion * @returns the new interpolated quaternion */ static Hermite(value1, tangent1, value2, tangent2, amount) { const squared = amount * amount; const cubed = amount * squared; const part1 = 2 * cubed - 3 * squared + 1; const part2 = -2 * cubed + 3 * squared; const part3 = cubed - 2 * squared + amount; const part4 = cubed - squared; const x = value1._x * part1 + value2._x * part2 + tangent1._x * part3 + tangent2._x * part4; const y = value1._y * part1 + value2._y * part2 + tangent1._y * part3 + tangent2._y * part4; const z = value1._z * part1 + value2._z * part2 + tangent1._z * part3 + tangent2._z * part4; const w = value1._w * part1 + value2._w * part2 + tangent1._w * part3 + tangent2._w * part4; return new _Quaternion(x, y, z, w); } /** * Returns a new Quaternion which is the 1st derivative of the Hermite spline defined by the quaternions "value1", "value2", "tangent1", "tangent2". * Example Playground https://playground.babylonjs.com/#L49EJ7#48 * @param value1 defines the first control point * @param tangent1 defines the first tangent * @param value2 defines the second control point * @param tangent2 defines the second tangent * @param time define where the derivative must be done * @returns 1st derivative */ static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { const result = new _Quaternion(); this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result); return result; } /** * Update a Quaternion with the 1st derivative of the Hermite spline defined by the quaternions "value1", "value2", "tangent1", "tangent2". * Example Playground https://playground.babylonjs.com/#L49EJ7#49 * @param value1 defines the first control point * @param tangent1 defines the first tangent * @param value2 defines the second control point * @param tangent2 defines the second tangent * @param time define where the derivative must be done * @param result define where to store the derivative * @returns result input */ static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { const t2 = time * time; result._x = (t2 - time) * 6 * value1._x + (3 * t2 - 4 * time + 1) * tangent1._x + (-t2 + time) * 6 * value2._x + (3 * t2 - 2 * time) * tangent2._x; result._y = (t2 - time) * 6 * value1._y + (3 * t2 - 4 * time + 1) * tangent1._y + (-t2 + time) * 6 * value2._y + (3 * t2 - 2 * time) * tangent2._y; result._z = (t2 - time) * 6 * value1._z + (3 * t2 - 4 * time + 1) * tangent1._z + (-t2 + time) * 6 * value2._z + (3 * t2 - 2 * time) * tangent2._z; result._w = (t2 - time) * 6 * value1._w + (3 * t2 - 4 * time + 1) * tangent1._w + (-t2 + time) * 6 * value2._w + (3 * t2 - 2 * time) * tangent2._w; result._isDirty = true; return result; } /** * Returns a new Quaternion as the normalization of the given Quaternion * @param quat defines the Quaternion to normalize * @returns the new Quaternion */ static Normalize(quat) { const result = _Quaternion.Zero(); _Quaternion.NormalizeToRef(quat, result); return result; } /** * Sets the given Quaternion "result" with the normalization of the given first Quaternion * @param quat defines the Quaternion to normalize * @param result defines the Quaternion where to store the result * @returns result input */ static NormalizeToRef(quat, result) { quat.normalizeToRef(result); return result; } /** * Returns a new Quaternion set with the coordinates of "value", if the quaternion "value" is in the cube defined by the quaternions "min" and "max" * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one * @param value defines the current value * @param min defines the lower range value * @param max defines the upper range value * @returns the new Quaternion */ static Clamp(value, min, max) { const result = new _Quaternion(); _Quaternion.ClampToRef(value, min, max, result); return result; } /** * Sets the given quaternion "result" with the coordinates of "value", if the quaternion "value" is in the cube defined by the quaternions "min" and "max" * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one * @param value defines the current value * @param min defines the lower range value * @param max defines the upper range value * @param result defines the Quaternion where to store the result * @returns result input */ static ClampToRef(value, min, max, result) { return result.copyFromFloats(Clamp(value.x, min.x, max.x), Clamp(value.y, min.y, max.y), Clamp(value.z, min.z, max.z), Clamp(value.w, min.w, max.w)); } /** * Returns a new Quaternion with random values between min and max * @param min the minimum random value * @param max the maximum random value * @returns a Quaternion with random values between min and max */ static Random(min = 0, max = 1) { return new _Quaternion(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max), RandomRange(min, max)); } /** * Sets a Quaternion with random values between min and max * @param min the minimum random value * @param max the maximum random value * @param ref the ref to store the values in * @returns the ref with random values between min and max */ static RandomToRef(min = 0, max = 1, ref) { return ref.copyFromFloats(RandomRange(min, max), RandomRange(min, max), RandomRange(min, max), RandomRange(min, max)); } /** * Do not use * @internal */ static Minimize() { throw new ReferenceError("Quaternion.Minimize does not make sense"); } /** * Do not use * @internal */ static Maximize() { throw new ReferenceError("Quaternion.Maximize does not make sense"); } /** * Returns the distance (float) between the quaternions "value1" and "value2". * @param value1 value to calulate the distance between * @param value2 value to calulate the distance between * @returns the distance between the two quaternions */ static Distance(value1, value2) { return Math.sqrt(_Quaternion.DistanceSquared(value1, value2)); } /** * Returns the squared distance (float) between the quaternions "value1" and "value2". * @param value1 value to calulate the distance between * @param value2 value to calulate the distance between * @returns the distance between the two quaternions squared */ static DistanceSquared(value1, value2) { const x = value1.x - value2.x; const y = value1.y - value2.y; const z = value1.z - value2.z; const w = value1.w - value2.w; return x * x + y * y + z * z + w * w; } /** * Returns a new Quaternion located at the center between the quaternions "value1" and "value2". * @param value1 value to calulate the center between * @param value2 value to calulate the center between * @returns the center between the two quaternions */ static Center(value1, value2) { return _Quaternion.CenterToRef(value1, value2, _Quaternion.Zero()); } /** * Gets the center of the quaternions "value1" and "value2" and stores the result in the quaternion "ref" * @param value1 defines first quaternion * @param value2 defines second quaternion * @param ref defines third quaternion * @returns ref */ static CenterToRef(value1, value2, ref) { return ref.copyFromFloats((value1.x + value2.x) / 2, (value1.y + value2.y) / 2, (value1.z + value2.z) / 2, (value1.w + value2.w) / 2); } }; Quaternion._V8PerformanceHack = new Quaternion(0.5, 0.5, 0.5, 0.5); Quaternion; Object.defineProperties(Quaternion.prototype, { dimension: { value: [4] }, rank: { value: 1 } }); Matrix = class _Matrix { static { __name(this, "Matrix"); } /** * Gets the precision of matrix computations */ static get Use64Bits() { return PerformanceConfigurator.MatrixUse64Bits; } /** * Gets the internal data of the matrix */ get m() { return this._m; } /** * Update the updateFlag to indicate that the matrix has been updated */ markAsUpdated() { this.updateFlag = MatrixManagement._UpdateFlagSeed++; this._isIdentity = false; this._isIdentity3x2 = false; this._isIdentityDirty = true; this._isIdentity3x2Dirty = true; } _updateIdentityStatus(isIdentity, isIdentityDirty = false, isIdentity3x2 = false, isIdentity3x2Dirty = true) { this._isIdentity = isIdentity; this._isIdentity3x2 = isIdentity || isIdentity3x2; this._isIdentityDirty = this._isIdentity ? false : isIdentityDirty; this._isIdentity3x2Dirty = this._isIdentity3x2 ? false : isIdentity3x2Dirty; } /** * Creates an empty matrix (filled with zeros) */ constructor() { this._isIdentity = false; this._isIdentityDirty = true; this._isIdentity3x2 = true; this._isIdentity3x2Dirty = true; this.updateFlag = -1; if (PerformanceConfigurator.MatrixTrackPrecisionChange) { PerformanceConfigurator.MatrixTrackedMatrices.push(this); } this._m = new PerformanceConfigurator.MatrixCurrentType(16); this.markAsUpdated(); } // Properties /** * Check if the current matrix is identity * @returns true is the matrix is the identity matrix */ isIdentity() { if (this._isIdentityDirty) { this._isIdentityDirty = false; const m = this._m; this._isIdentity = m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 0 && m[4] === 0 && m[5] === 1 && m[6] === 0 && m[7] === 0 && m[8] === 0 && m[9] === 0 && m[10] === 1 && m[11] === 0 && m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1; } return this._isIdentity; } /** * Check if the current matrix is identity as a texture matrix (3x2 store in 4x4) * @returns true is the matrix is the identity matrix */ isIdentityAs3x2() { if (this._isIdentity3x2Dirty) { this._isIdentity3x2Dirty = false; if (this._m[0] !== 1 || this._m[5] !== 1 || this._m[15] !== 1) { this._isIdentity3x2 = false; } else if (this._m[1] !== 0 || this._m[2] !== 0 || this._m[3] !== 0 || this._m[4] !== 0 || this._m[6] !== 0 || this._m[7] !== 0 || this._m[8] !== 0 || this._m[9] !== 0 || this._m[10] !== 0 || this._m[11] !== 0 || this._m[12] !== 0 || this._m[13] !== 0 || this._m[14] !== 0) { this._isIdentity3x2 = false; } else { this._isIdentity3x2 = true; } } return this._isIdentity3x2; } /** * Gets the determinant of the matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#34 * @returns the matrix determinant */ determinant() { if (this._isIdentity === true) { return 1; } const m = this._m; const m00 = m[0], m01 = m[1], m02 = m[2], m03 = m[3]; const m10 = m[4], m11 = m[5], m12 = m[6], m13 = m[7]; const m20 = m[8], m21 = m[9], m22 = m[10], m23 = m[11]; const m30 = m[12], m31 = m[13], m32 = m[14], m33 = m[15]; const det_22_33 = m22 * m33 - m32 * m23; const det_21_33 = m21 * m33 - m31 * m23; const det_21_32 = m21 * m32 - m31 * m22; const det_20_33 = m20 * m33 - m30 * m23; const det_20_32 = m20 * m32 - m22 * m30; const det_20_31 = m20 * m31 - m30 * m21; const cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32); const cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32); const cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31); const cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31); return m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03; } // Methods /** * Gets a string with the Matrix values * @returns a string with the Matrix values */ toString() { return `{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]} ${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]} ${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]} ${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`; } toArray(array = null, index = 0) { if (!array) { return this._m; } const m = this._m; for (let i = 0; i < 16; i++) { array[index + i] = m[i]; } return this; } /** * Returns the matrix as a Float32Array or Array * Example Playground - https://playground.babylonjs.com/#AV9X17#114 * @returns the matrix underlying array. */ asArray() { return this._m; } fromArray(array, index = 0) { return _Matrix.FromArrayToRef(array, index, this); } copyFromFloats(...floats) { return _Matrix.FromArrayToRef(floats, 0, this); } set(...values) { const m = this._m; for (let i = 0; i < 16; i++) { m[i] = values[i]; } this.markAsUpdated(); return this; } setAll(value) { const m = this._m; for (let i = 0; i < 16; i++) { m[i] = value; } this.markAsUpdated(); return this; } /** * Inverts the current matrix in place * Example Playground - https://playground.babylonjs.com/#AV9X17#118 * @returns the current inverted matrix */ invert() { this.invertToRef(this); return this; } /** * Sets all the matrix elements to zero * @returns the current matrix */ reset() { _Matrix.FromValuesToRef(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, this); this._updateIdentityStatus(false); return this; } /** * Adds the current matrix with a second one * Example Playground - https://playground.babylonjs.com/#AV9X17#44 * @param other defines the matrix to add * @returns a new matrix as the addition of the current matrix and the given one */ add(other) { const result = new _Matrix(); this.addToRef(other, result); return result; } /** * Sets the given matrix "result" to the addition of the current matrix and the given one * Example Playground - https://playground.babylonjs.com/#AV9X17#45 * @param other defines the matrix to add * @param result defines the target matrix * @returns result input */ addToRef(other, result) { const m = this._m; const resultM = result._m; const otherM = other.m; for (let index = 0; index < 16; index++) { resultM[index] = m[index] + otherM[index]; } result.markAsUpdated(); return result; } /** * Adds in place the given matrix to the current matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#46 * @param other defines the second operand * @returns the current updated matrix */ addToSelf(other) { const m = this._m; const otherM = other.m; m[0] += otherM[0]; m[1] += otherM[1]; m[2] += otherM[2]; m[3] += otherM[3]; m[4] += otherM[4]; m[5] += otherM[5]; m[6] += otherM[6]; m[7] += otherM[7]; m[8] += otherM[8]; m[9] += otherM[9]; m[10] += otherM[10]; m[11] += otherM[11]; m[12] += otherM[12]; m[13] += otherM[13]; m[14] += otherM[14]; m[15] += otherM[15]; this.markAsUpdated(); return this; } addInPlace(other) { const m = this._m, otherM = other.m; for (let i = 0; i < 16; i++) { m[i] += otherM[i]; } this.markAsUpdated(); return this; } addInPlaceFromFloats(...floats) { const m = this._m; for (let i = 0; i < 16; i++) { m[i] += floats[i]; } this.markAsUpdated(); return this; } subtract(other) { const m = this._m, otherM = other.m; for (let i = 0; i < 16; i++) { m[i] -= otherM[i]; } this.markAsUpdated(); return this; } subtractToRef(other, result) { const m = this._m, otherM = other.m, resultM = result._m; for (let i = 0; i < 16; i++) { resultM[i] = m[i] - otherM[i]; } result.markAsUpdated(); return result; } subtractInPlace(other) { const m = this._m, otherM = other.m; for (let i = 0; i < 16; i++) { m[i] -= otherM[i]; } this.markAsUpdated(); return this; } subtractFromFloats(...floats) { return this.subtractFromFloatsToRef(...floats, new _Matrix()); } subtractFromFloatsToRef(...args) { const result = args.pop(), m = this._m, resultM = result._m, values = args; for (let i = 0; i < 16; i++) { resultM[i] = m[i] - values[i]; } result.markAsUpdated(); return result; } /** * Sets the given matrix to the current inverted Matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#119 * @param other defines the target matrix * @returns result input */ invertToRef(other) { if (this._isIdentity === true) { _Matrix.IdentityToRef(other); return other; } if (InvertMatrixToArray(this, other.asArray())) { other.markAsUpdated(); } else { other.copyFrom(this); } return other; } /** * add a value at the specified position in the current Matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#47 * @param index the index of the value within the matrix. between 0 and 15. * @param value the value to be added * @returns the current updated matrix */ addAtIndex(index, value) { this._m[index] += value; this.markAsUpdated(); return this; } /** * mutiply the specified position in the current Matrix by a value * @param index the index of the value within the matrix. between 0 and 15. * @param value the value to be added * @returns the current updated matrix */ multiplyAtIndex(index, value) { this._m[index] *= value; this.markAsUpdated(); return this; } /** * Inserts the translation vector (using 3 floats) in the current matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#120 * @param x defines the 1st component of the translation * @param y defines the 2nd component of the translation * @param z defines the 3rd component of the translation * @returns the current updated matrix */ setTranslationFromFloats(x, y, z) { this._m[12] = x; this._m[13] = y; this._m[14] = z; this.markAsUpdated(); return this; } /** * Adds the translation vector (using 3 floats) in the current matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#20 * Example Playground - https://playground.babylonjs.com/#AV9X17#48 * @param x defines the 1st component of the translation * @param y defines the 2nd component of the translation * @param z defines the 3rd component of the translation * @returns the current updated matrix */ addTranslationFromFloats(x, y, z) { this._m[12] += x; this._m[13] += y; this._m[14] += z; this.markAsUpdated(); return this; } /** * Inserts the translation vector in the current matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#121 * @param vector3 defines the translation to insert * @returns the current updated matrix */ setTranslation(vector3) { return this.setTranslationFromFloats(vector3._x, vector3._y, vector3._z); } /** * Gets the translation value of the current matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#122 * @returns a new Vector3 as the extracted translation from the matrix */ getTranslation() { return new Vector3(this._m[12], this._m[13], this._m[14]); } /** * Fill a Vector3 with the extracted translation from the matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#123 * @param result defines the Vector3 where to store the translation * @returns the current matrix */ getTranslationToRef(result) { result.x = this._m[12]; result.y = this._m[13]; result.z = this._m[14]; return result; } /** * Remove rotation and scaling part from the matrix * @returns the updated matrix */ removeRotationAndScaling() { const m = this.m; _Matrix.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, m[12], m[13], m[14], m[15], this); this._updateIdentityStatus(m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1); return this; } /** * Copy the current matrix from the given one * Example Playground - https://playground.babylonjs.com/#AV9X17#21 * @param other defines the source matrix * @returns the current updated matrix */ copyFrom(other) { other.copyToArray(this._m); const o = other; this.updateFlag = o.updateFlag; this._updateIdentityStatus(o._isIdentity, o._isIdentityDirty, o._isIdentity3x2, o._isIdentity3x2Dirty); return this; } /** * Populates the given array from the starting index with the current matrix values * @param array defines the target array * @param offset defines the offset in the target array where to start storing values * @returns the current matrix */ copyToArray(array, offset = 0) { CopyMatrixToArray(this, array, offset); return this; } /** * Multiply two matrices * Example Playground - https://playground.babylonjs.com/#AV9X17#15 * A.multiply(B) means apply B to A so result is B x A * @param other defines the second operand * @returns a new matrix set with the multiplication result of the current Matrix and the given one */ multiply(other) { const result = new _Matrix(); this.multiplyToRef(other, result); return result; } /** * This method performs component-by-component in-place multiplication, rather than true matrix multiplication. * Use multiply or multiplyToRef for matrix multiplication. * @param other defines the second operand * @returns the current updated matrix */ multiplyInPlace(other) { const m = this._m, otherM = other.m; for (let i = 0; i < 16; i++) { m[i] *= otherM[i]; } this.markAsUpdated(); return this; } /** * This method performs a component-by-component multiplication of the current matrix with the array of transmitted numbers. * Use multiply or multiplyToRef for matrix multiplication. * @param floats defines the array of numbers to multiply the matrix by * @returns the current updated matrix */ multiplyByFloats(...floats) { const m = this._m; for (let i = 0; i < 16; i++) { m[i] *= floats[i]; } this.markAsUpdated(); return this; } /** * Multiples the current matrix by the given floats and stores them in the given ref * @param args The floats and ref * @returns The updated ref */ multiplyByFloatsToRef(...args) { const result = args.pop(), m = this._m, resultM = result._m, values = args; for (let i = 0; i < 16; i++) { resultM[i] = m[i] * values[i]; } result.markAsUpdated(); return result; } /** * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one * A.multiplyToRef(B, R) means apply B to A and store in R and R = B x A * Example Playground - https://playground.babylonjs.com/#AV9X17#16 * @param other defines the second operand * @param result defines the matrix where to store the multiplication * @returns result input */ multiplyToRef(other, result) { if (this._isIdentity) { result.copyFrom(other); return result; } if (other._isIdentity) { result.copyFrom(this); return result; } this.multiplyToArray(other, result._m, 0); result.markAsUpdated(); return result; } /** * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one * @param other defines the second operand * @param result defines the array where to store the multiplication * @param offset defines the offset in the target array where to start storing values * @returns the current matrix */ multiplyToArray(other, result, offset) { MultiplyMatricesToArray(this, other, result, offset); return this; } divide(other) { return this.divideToRef(other, new _Matrix()); } divideToRef(other, result) { const m = this._m, otherM = other.m, resultM = result._m; for (let i = 0; i < 16; i++) { resultM[i] = m[i] / otherM[i]; } result.markAsUpdated(); return result; } divideInPlace(other) { const m = this._m, otherM = other.m; for (let i = 0; i < 16; i++) { m[i] /= otherM[i]; } this.markAsUpdated(); return this; } minimizeInPlace(other) { const m = this._m, otherM = other.m; for (let i = 0; i < 16; i++) { m[i] = Math.min(m[i], otherM[i]); } this.markAsUpdated(); return this; } minimizeInPlaceFromFloats(...floats) { const m = this._m; for (let i = 0; i < 16; i++) { m[i] = Math.min(m[i], floats[i]); } this.markAsUpdated(); return this; } maximizeInPlace(other) { const m = this._m, otherM = other.m; for (let i = 0; i < 16; i++) { m[i] = Math.min(m[i], otherM[i]); } this.markAsUpdated(); return this; } maximizeInPlaceFromFloats(...floats) { const m = this._m; for (let i = 0; i < 16; i++) { m[i] = Math.min(m[i], floats[i]); } this.markAsUpdated(); return this; } negate() { return this.negateToRef(new _Matrix()); } negateInPlace() { const m = this._m; for (let i = 0; i < 16; i++) { m[i] = -m[i]; } this.markAsUpdated(); return this; } negateToRef(result) { const m = this._m, resultM = result._m; for (let i = 0; i < 16; i++) { resultM[i] = -m[i]; } result.markAsUpdated(); return result; } /** * Check equality between this matrix and a second one * @param value defines the second matrix to compare * @returns true is the current matrix and the given one values are strictly equal */ equals(value) { const other = value; if (!other) { return false; } if (this._isIdentity || other._isIdentity) { if (!this._isIdentityDirty && !other._isIdentityDirty) { return this._isIdentity && other._isIdentity; } } const m = this.m; const om = other.m; return m[0] === om[0] && m[1] === om[1] && m[2] === om[2] && m[3] === om[3] && m[4] === om[4] && m[5] === om[5] && m[6] === om[6] && m[7] === om[7] && m[8] === om[8] && m[9] === om[9] && m[10] === om[10] && m[11] === om[11] && m[12] === om[12] && m[13] === om[13] && m[14] === om[14] && m[15] === om[15]; } equalsWithEpsilon(other, epsilon = 0) { const m = this._m, otherM = other.m; for (let i = 0; i < 16; i++) { if (!WithinEpsilon(m[i], otherM[i], epsilon)) { return false; } } return true; } equalsToFloats(...floats) { const m = this._m; for (let i = 0; i < 16; i++) { if (m[i] != floats[i]) { return false; } } return true; } floor() { return this.floorToRef(new _Matrix()); } floorToRef(result) { const m = this._m, resultM = result._m; for (let i = 0; i < 16; i++) { resultM[i] = Math.floor(m[i]); } result.markAsUpdated(); return result; } fract() { return this.fractToRef(new _Matrix()); } fractToRef(result) { const m = this._m, resultM = result._m; for (let i = 0; i < 16; i++) { resultM[i] = m[i] - Math.floor(m[i]); } result.markAsUpdated(); return result; } /** * Clone the current matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#18 * @returns a new matrix from the current matrix */ clone() { const matrix = new _Matrix(); matrix.copyFrom(this); return matrix; } /** * Returns the name of the current matrix class * @returns the string "Matrix" */ getClassName() { return "Matrix"; } /** * Gets the hash code of the current matrix * @returns the hash code */ getHashCode() { let hash = ExtractAsInt2(this._m[0]); for (let i = 1; i < 16; i++) { hash = hash * 397 ^ ExtractAsInt2(this._m[i]); } return hash; } /** * Decomposes the current Matrix into a translation, rotation and scaling components of the provided node * Example Playground - https://playground.babylonjs.com/#AV9X17#13 * @param node the node to decompose the matrix to * @returns true if operation was successful */ decomposeToTransformNode(node) { node.rotationQuaternion = node.rotationQuaternion || new Quaternion(); return this.decompose(node.scaling, node.rotationQuaternion, node.position); } /** * Decomposes the current Matrix into a translation, rotation and scaling components * Example Playground - https://playground.babylonjs.com/#AV9X17#12 * @param scale defines the scale vector3 given as a reference to update * @param rotation defines the rotation quaternion given as a reference to update * @param translation defines the translation vector3 given as a reference to update * @param preserveScalingNode Use scaling sign coming from this node. Otherwise scaling sign might change. * @param useAbsoluteScaling Use scaling sign coming from this absoluteScaling when true or scaling otherwise. * @returns true if operation was successful */ decompose(scale, rotation, translation, preserveScalingNode, useAbsoluteScaling = true) { if (this._isIdentity) { if (translation) { translation.setAll(0); } if (scale) { scale.setAll(1); } if (rotation) { rotation.copyFromFloats(0, 0, 0, 1); } return true; } const m = this._m; if (translation) { translation.copyFromFloats(m[12], m[13], m[14]); } scale = scale || MathTmp.Vector3[0]; scale.x = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]); scale.y = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]); scale.z = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]); if (preserveScalingNode) { const signX = (useAbsoluteScaling ? preserveScalingNode.absoluteScaling.x : preserveScalingNode.scaling.x) < 0 ? -1 : 1; const signY = (useAbsoluteScaling ? preserveScalingNode.absoluteScaling.y : preserveScalingNode.scaling.y) < 0 ? -1 : 1; const signZ = (useAbsoluteScaling ? preserveScalingNode.absoluteScaling.z : preserveScalingNode.scaling.z) < 0 ? -1 : 1; scale.x *= signX; scale.y *= signY; scale.z *= signZ; } else { if (this.determinant() <= 0) { scale.y *= -1; } } if (scale._x === 0 || scale._y === 0 || scale._z === 0) { if (rotation) { rotation.copyFromFloats(0, 0, 0, 1); } return false; } if (rotation) { const sx = 1 / scale._x, sy = 1 / scale._y, sz = 1 / scale._z; _Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0, m[4] * sy, m[5] * sy, m[6] * sy, 0, m[8] * sz, m[9] * sz, m[10] * sz, 0, 0, 0, 0, 1, MathTmp.Matrix[0]); Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation); } return true; } /** * Gets specific row of the matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#36 * @param index defines the number of the row to get * @returns the index-th row of the current matrix as a new Vector4 */ getRow(index) { if (index < 0 || index > 3) { return null; } const i = index * 4; return new Vector4(this._m[i + 0], this._m[i + 1], this._m[i + 2], this._m[i + 3]); } /** * Gets specific row of the matrix to ref * Example Playground - https://playground.babylonjs.com/#AV9X17#36 * @param index defines the number of the row to get * @param rowVector vector to store the index-th row of the current matrix * @returns result input */ getRowToRef(index, rowVector) { if (index >= 0 && index <= 3) { const i = index * 4; rowVector.x = this._m[i + 0]; rowVector.y = this._m[i + 1]; rowVector.z = this._m[i + 2]; rowVector.w = this._m[i + 3]; } return rowVector; } /** * Sets the index-th row of the current matrix to the vector4 values * Example Playground - https://playground.babylonjs.com/#AV9X17#36 * @param index defines the number of the row to set * @param row defines the target vector4 * @returns the updated current matrix */ setRow(index, row) { return this.setRowFromFloats(index, row.x, row.y, row.z, row.w); } /** * Compute the transpose of the matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#40 * @returns the new transposed matrix */ transpose() { const result = new _Matrix(); _Matrix.TransposeToRef(this, result); return result; } /** * Compute the transpose of the matrix and store it in a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#41 * @param result defines the target matrix * @returns result input */ transposeToRef(result) { _Matrix.TransposeToRef(this, result); return result; } /** * Sets the index-th row of the current matrix with the given 4 x float values * Example Playground - https://playground.babylonjs.com/#AV9X17#36 * @param index defines the row index * @param x defines the x component to set * @param y defines the y component to set * @param z defines the z component to set * @param w defines the w component to set * @returns the updated current matrix */ setRowFromFloats(index, x, y, z, w) { if (index < 0 || index > 3) { return this; } const i = index * 4; this._m[i + 0] = x; this._m[i + 1] = y; this._m[i + 2] = z; this._m[i + 3] = w; this.markAsUpdated(); return this; } /** * Compute a new matrix set with the current matrix values multiplied by scale (float) * @param scale defines the scale factor * @returns a new matrix */ scale(scale) { const result = new _Matrix(); this.scaleToRef(scale, result); return result; } /** * Scale the current matrix values by a factor to a given result matrix * @param scale defines the scale factor * @param result defines the matrix to store the result * @returns result input */ scaleToRef(scale, result) { for (let index = 0; index < 16; index++) { result._m[index] = this._m[index] * scale; } result.markAsUpdated(); return result; } /** * Scale the current matrix values by a factor and add the result to a given matrix * @param scale defines the scale factor * @param result defines the Matrix to store the result * @returns result input */ scaleAndAddToRef(scale, result) { for (let index = 0; index < 16; index++) { result._m[index] += this._m[index] * scale; } result.markAsUpdated(); return result; } scaleInPlace(scale) { const m = this._m; for (let i = 0; i < 16; i++) { m[i] *= scale; } this.markAsUpdated(); return this; } /** * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column). * Example Playground - https://playground.babylonjs.com/#AV9X17#17 * @param ref matrix to store the result * @returns the reference matrix */ toNormalMatrix(ref) { const tmp = MathTmp.Matrix[0]; this.invertToRef(tmp); tmp.transposeToRef(ref); const m = ref._m; _Matrix.FromValuesToRef(m[0], m[1], m[2], 0, m[4], m[5], m[6], 0, m[8], m[9], m[10], 0, 0, 0, 0, 1, ref); return ref; } /** * Gets only rotation part of the current matrix * @returns a new matrix sets to the extracted rotation matrix from the current one */ getRotationMatrix() { const result = new _Matrix(); this.getRotationMatrixToRef(result); return result; } /** * Extracts the rotation matrix from the current one and sets it as the given "result" * @param result defines the target matrix to store data to * @returns result input */ getRotationMatrixToRef(result) { const scale = MathTmp.Vector3[0]; if (!this.decompose(scale)) { _Matrix.IdentityToRef(result); return result; } const m = this._m; const sx = 1 / scale._x, sy = 1 / scale._y, sz = 1 / scale._z; _Matrix.FromValuesToRef(m[0] * sx, m[1] * sx, m[2] * sx, 0, m[4] * sy, m[5] * sy, m[6] * sy, 0, m[8] * sz, m[9] * sz, m[10] * sz, 0, 0, 0, 0, 1, result); return result; } /** * Toggles model matrix from being right handed to left handed in place and vice versa * @returns the current updated matrix */ toggleModelMatrixHandInPlace() { const m = this._m; m[2] *= -1; m[6] *= -1; m[8] *= -1; m[9] *= -1; m[14] *= -1; this.markAsUpdated(); return this; } /** * Toggles projection matrix from being right handed to left handed in place and vice versa * @returns the current updated matrix */ toggleProjectionMatrixHandInPlace() { const m = this._m; m[8] *= -1; m[9] *= -1; m[10] *= -1; m[11] *= -1; this.markAsUpdated(); return this; } // Statics /** * Creates a matrix from an array * Example Playground - https://playground.babylonjs.com/#AV9X17#42 * @param array defines the source array * @param offset defines an offset in the source array * @returns a new Matrix set from the starting index of the given array */ static FromArray(array, offset = 0) { const result = new _Matrix(); _Matrix.FromArrayToRef(array, offset, result); return result; } /** * Copy the content of an array into a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#43 * @param array defines the source array * @param offset defines an offset in the source array * @param result defines the target matrix * @returns result input */ static FromArrayToRef(array, offset, result) { for (let index = 0; index < 16; index++) { result._m[index] = array[index + offset]; } result.markAsUpdated(); return result; } /** * Stores an array into a matrix after having multiplied each component by a given factor * Example Playground - https://playground.babylonjs.com/#AV9X17#50 * @param array defines the source array * @param offset defines the offset in the source array * @param scale defines the scaling factor * @param result defines the target matrix * @returns result input */ static FromFloat32ArrayToRefScaled(array, offset, scale, result) { result._m[0] = array[0 + offset] * scale; result._m[1] = array[1 + offset] * scale; result._m[2] = array[2 + offset] * scale; result._m[3] = array[3 + offset] * scale; result._m[4] = array[4 + offset] * scale; result._m[5] = array[5 + offset] * scale; result._m[6] = array[6 + offset] * scale; result._m[7] = array[7 + offset] * scale; result._m[8] = array[8 + offset] * scale; result._m[9] = array[9 + offset] * scale; result._m[10] = array[10 + offset] * scale; result._m[11] = array[11 + offset] * scale; result._m[12] = array[12 + offset] * scale; result._m[13] = array[13 + offset] * scale; result._m[14] = array[14 + offset] * scale; result._m[15] = array[15 + offset] * scale; result.markAsUpdated(); return result; } /** * Gets an identity matrix that must not be updated */ static get IdentityReadOnly() { return _Matrix._IdentityReadOnly; } /** * Stores a list of values (16) inside a given matrix * @param initialM11 defines 1st value of 1st row * @param initialM12 defines 2nd value of 1st row * @param initialM13 defines 3rd value of 1st row * @param initialM14 defines 4th value of 1st row * @param initialM21 defines 1st value of 2nd row * @param initialM22 defines 2nd value of 2nd row * @param initialM23 defines 3rd value of 2nd row * @param initialM24 defines 4th value of 2nd row * @param initialM31 defines 1st value of 3rd row * @param initialM32 defines 2nd value of 3rd row * @param initialM33 defines 3rd value of 3rd row * @param initialM34 defines 4th value of 3rd row * @param initialM41 defines 1st value of 4th row * @param initialM42 defines 2nd value of 4th row * @param initialM43 defines 3rd value of 4th row * @param initialM44 defines 4th value of 4th row * @param result defines the target matrix */ static FromValuesToRef(initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) { const m = result._m; m[0] = initialM11; m[1] = initialM12; m[2] = initialM13; m[3] = initialM14; m[4] = initialM21; m[5] = initialM22; m[6] = initialM23; m[7] = initialM24; m[8] = initialM31; m[9] = initialM32; m[10] = initialM33; m[11] = initialM34; m[12] = initialM41; m[13] = initialM42; m[14] = initialM43; m[15] = initialM44; result.markAsUpdated(); } /** * Creates new matrix from a list of values (16) * @param initialM11 defines 1st value of 1st row * @param initialM12 defines 2nd value of 1st row * @param initialM13 defines 3rd value of 1st row * @param initialM14 defines 4th value of 1st row * @param initialM21 defines 1st value of 2nd row * @param initialM22 defines 2nd value of 2nd row * @param initialM23 defines 3rd value of 2nd row * @param initialM24 defines 4th value of 2nd row * @param initialM31 defines 1st value of 3rd row * @param initialM32 defines 2nd value of 3rd row * @param initialM33 defines 3rd value of 3rd row * @param initialM34 defines 4th value of 3rd row * @param initialM41 defines 1st value of 4th row * @param initialM42 defines 2nd value of 4th row * @param initialM43 defines 3rd value of 4th row * @param initialM44 defines 4th value of 4th row * @returns the new matrix */ static FromValues(initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) { const result = new _Matrix(); const m = result._m; m[0] = initialM11; m[1] = initialM12; m[2] = initialM13; m[3] = initialM14; m[4] = initialM21; m[5] = initialM22; m[6] = initialM23; m[7] = initialM24; m[8] = initialM31; m[9] = initialM32; m[10] = initialM33; m[11] = initialM34; m[12] = initialM41; m[13] = initialM42; m[14] = initialM43; m[15] = initialM44; result.markAsUpdated(); return result; } /** * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3) * Example Playground - https://playground.babylonjs.com/#AV9X17#24 * @param scale defines the scale vector3 * @param rotation defines the rotation quaternion * @param translation defines the translation vector3 * @returns a new matrix */ static Compose(scale, rotation, translation) { const result = new _Matrix(); _Matrix.ComposeToRef(scale, rotation, translation, result); return result; } /** * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3) * Example Playground - https://playground.babylonjs.com/#AV9X17#25 * @param scale defines the scale vector3 * @param rotation defines the rotation quaternion * @param translation defines the translation vector3 * @param result defines the target matrix * @returns result input */ static ComposeToRef(scale, rotation, translation, result) { const m = result._m; const x = rotation._x, y = rotation._y, z = rotation._z, w = rotation._w; const x2 = x + x, y2 = y + y, z2 = z + z; const xx = x * x2, xy = x * y2, xz = x * z2; const yy = y * y2, yz = y * z2, zz = z * z2; const wx = w * x2, wy = w * y2, wz = w * z2; const sx = scale._x, sy = scale._y, sz = scale._z; m[0] = (1 - (yy + zz)) * sx; m[1] = (xy + wz) * sx; m[2] = (xz - wy) * sx; m[3] = 0; m[4] = (xy - wz) * sy; m[5] = (1 - (xx + zz)) * sy; m[6] = (yz + wx) * sy; m[7] = 0; m[8] = (xz + wy) * sz; m[9] = (yz - wx) * sz; m[10] = (1 - (xx + yy)) * sz; m[11] = 0; m[12] = translation._x; m[13] = translation._y; m[14] = translation._z; m[15] = 1; result.markAsUpdated(); return result; } /** * Creates a new identity matrix * @returns a new identity matrix */ static Identity() { const identity = _Matrix.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); identity._updateIdentityStatus(true); return identity; } /** * Creates a new identity matrix and stores the result in a given matrix * @param result defines the target matrix * @returns result input */ static IdentityToRef(result) { _Matrix.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, result); result._updateIdentityStatus(true); return result; } /** * Creates a new zero matrix * @returns a new zero matrix */ static Zero() { const zero = _Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); zero._updateIdentityStatus(false); return zero; } /** * Creates a new rotation matrix for "angle" radians around the X axis * Example Playground - https://playground.babylonjs.com/#AV9X17#97 * @param angle defines the angle (in radians) to use * @returns the new matrix */ static RotationX(angle) { const result = new _Matrix(); _Matrix.RotationXToRef(angle, result); return result; } /** * Creates a new matrix as the invert of a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#124 * @param source defines the source matrix * @returns the new matrix */ static Invert(source) { const result = new _Matrix(); source.invertToRef(result); return result; } /** * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#98 * @param angle defines the angle (in radians) to use * @param result defines the target matrix * @returns result input */ static RotationXToRef(angle, result) { const s = Math.sin(angle); const c = Math.cos(angle); _Matrix.FromValuesToRef(1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, result); result._updateIdentityStatus(c === 1 && s === 0); return result; } /** * Creates a new rotation matrix for "angle" radians around the Y axis * Example Playground - https://playground.babylonjs.com/#AV9X17#99 * @param angle defines the angle (in radians) to use * @returns the new matrix */ static RotationY(angle) { const result = new _Matrix(); _Matrix.RotationYToRef(angle, result); return result; } /** * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#100 * @param angle defines the angle (in radians) to use * @param result defines the target matrix * @returns result input */ static RotationYToRef(angle, result) { const s = Math.sin(angle); const c = Math.cos(angle); _Matrix.FromValuesToRef(c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1, result); result._updateIdentityStatus(c === 1 && s === 0); return result; } /** * Creates a new rotation matrix for "angle" radians around the Z axis * Example Playground - https://playground.babylonjs.com/#AV9X17#101 * @param angle defines the angle (in radians) to use * @returns the new matrix */ static RotationZ(angle) { const result = new _Matrix(); _Matrix.RotationZToRef(angle, result); return result; } /** * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#102 * @param angle defines the angle (in radians) to use * @param result defines the target matrix * @returns result input */ static RotationZToRef(angle, result) { const s = Math.sin(angle); const c = Math.cos(angle); _Matrix.FromValuesToRef(c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, result); result._updateIdentityStatus(c === 1 && s === 0); return result; } /** * Creates a new rotation matrix for "angle" radians around the given axis * Example Playground - https://playground.babylonjs.com/#AV9X17#96 * @param axis defines the axis to use * @param angle defines the angle (in radians) to use * @returns the new matrix */ static RotationAxis(axis, angle) { const result = new _Matrix(); _Matrix.RotationAxisToRef(axis, angle, result); return result; } /** * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#94 * @param axis defines the axis to use * @param angle defines the angle (in radians) to use * @param result defines the target matrix * @returns result input */ static RotationAxisToRef(axis, angle, result) { const s = Math.sin(-angle); const c = Math.cos(-angle); const c1 = 1 - c; axis = axis.normalizeToRef(MathTmp.Vector3[0]); const m = result._m; m[0] = axis._x * axis._x * c1 + c; m[1] = axis._x * axis._y * c1 - axis._z * s; m[2] = axis._x * axis._z * c1 + axis._y * s; m[3] = 0; m[4] = axis._y * axis._x * c1 + axis._z * s; m[5] = axis._y * axis._y * c1 + c; m[6] = axis._y * axis._z * c1 - axis._x * s; m[7] = 0; m[8] = axis._z * axis._x * c1 - axis._y * s; m[9] = axis._z * axis._y * c1 + axis._x * s; m[10] = axis._z * axis._z * c1 + c; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; result.markAsUpdated(); return result; } /** * Takes normalised vectors and returns a rotation matrix to align "from" with "to". * Taken from http://www.iquilezles.org/www/articles/noacos/noacos.htm * Example Playground - https://playground.babylonjs.com/#AV9X17#93 * @param from defines the vector to align * @param to defines the vector to align to * @param result defines the target matrix * @param useYAxisForCoplanar defines a boolean indicating that we should favor Y axis for coplanar vectors (default is false) * @returns result input */ static RotationAlignToRef(from, to, result, useYAxisForCoplanar = false) { const c = Vector3.Dot(to, from); const m = result._m; if (c < -1 + Epsilon) { m[0] = -1; m[1] = 0; m[2] = 0; m[3] = 0; m[4] = 0; m[5] = useYAxisForCoplanar ? 1 : -1; m[6] = 0; m[7] = 0; m[8] = 0; m[9] = 0; m[10] = useYAxisForCoplanar ? -1 : 1; m[11] = 0; } else { const v = Vector3.Cross(to, from); const k = 1 / (1 + c); m[0] = v._x * v._x * k + c; m[1] = v._y * v._x * k - v._z; m[2] = v._z * v._x * k + v._y; m[3] = 0; m[4] = v._x * v._y * k + v._z; m[5] = v._y * v._y * k + c; m[6] = v._z * v._y * k - v._x; m[7] = 0; m[8] = v._x * v._z * k - v._y; m[9] = v._y * v._z * k + v._x; m[10] = v._z * v._z * k + c; m[11] = 0; } m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; result.markAsUpdated(); return result; } /** * Creates a rotation matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#103 * Example Playground - https://playground.babylonjs.com/#AV9X17#105 * @param yaw defines the yaw angle in radians (Y axis) * @param pitch defines the pitch angle in radians (X axis) * @param roll defines the roll angle in radians (Z axis) * @returns the new rotation matrix */ static RotationYawPitchRoll(yaw, pitch, roll) { const result = new _Matrix(); _Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result); return result; } /** * Creates a rotation matrix and stores it in a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#104 * @param yaw defines the yaw angle in radians (Y axis) * @param pitch defines the pitch angle in radians (X axis) * @param roll defines the roll angle in radians (Z axis) * @param result defines the target matrix * @returns result input */ static RotationYawPitchRollToRef(yaw, pitch, roll, result) { Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, MathTmp.Quaternion[0]); MathTmp.Quaternion[0].toRotationMatrix(result); return result; } /** * Creates a scaling matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#107 * @param x defines the scale factor on X axis * @param y defines the scale factor on Y axis * @param z defines the scale factor on Z axis * @returns the new matrix */ static Scaling(x, y, z) { const result = new _Matrix(); _Matrix.ScalingToRef(x, y, z, result); return result; } /** * Creates a scaling matrix and stores it in a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#108 * @param x defines the scale factor on X axis * @param y defines the scale factor on Y axis * @param z defines the scale factor on Z axis * @param result defines the target matrix * @returns result input */ static ScalingToRef(x, y, z, result) { _Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, result); result._updateIdentityStatus(x === 1 && y === 1 && z === 1); return result; } /** * Creates a translation matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#109 * @param x defines the translation on X axis * @param y defines the translation on Y axis * @param z defines the translationon Z axis * @returns the new matrix */ static Translation(x, y, z) { const result = new _Matrix(); _Matrix.TranslationToRef(x, y, z, result); return result; } /** * Creates a translation matrix and stores it in a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#110 * @param x defines the translation on X axis * @param y defines the translation on Y axis * @param z defines the translationon Z axis * @param result defines the target matrix * @returns result input */ static TranslationToRef(x, y, z, result) { _Matrix.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1, result); result._updateIdentityStatus(x === 0 && y === 0 && z === 0); return result; } /** * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue". * Example Playground - https://playground.babylonjs.com/#AV9X17#55 * @param startValue defines the start value * @param endValue defines the end value * @param gradient defines the gradient factor * @returns the new matrix */ static Lerp(startValue, endValue, gradient) { const result = new _Matrix(); _Matrix.LerpToRef(startValue, endValue, gradient, result); return result; } /** * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue". * Example Playground - https://playground.babylonjs.com/#AV9X17#54 * @param startValue defines the start value * @param endValue defines the end value * @param gradient defines the gradient factor * @param result defines the Matrix object where to store data * @returns result input */ static LerpToRef(startValue, endValue, gradient, result) { const resultM = result._m; const startM = startValue.m; const endM = endValue.m; for (let index = 0; index < 16; index++) { resultM[index] = startM[index] * (1 - gradient) + endM[index] * gradient; } result.markAsUpdated(); return result; } /** * Builds a new matrix whose values are computed by: * * decomposing the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices * Example Playground - https://playground.babylonjs.com/#AV9X17#22 * Example Playground - https://playground.babylonjs.com/#AV9X17#51 * @param startValue defines the first matrix * @param endValue defines the second matrix * @param gradient defines the gradient between the two matrices * @returns the new matrix */ static DecomposeLerp(startValue, endValue, gradient) { const result = new _Matrix(); _Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result); return result; } /** * Update a matrix to values which are computed by: * * decomposing the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices * Example Playground - https://playground.babylonjs.com/#AV9X17#23 * Example Playground - https://playground.babylonjs.com/#AV9X17#53 * @param startValue defines the first matrix * @param endValue defines the second matrix * @param gradient defines the gradient between the two matrices * @param result defines the target matrix * @returns result input */ static DecomposeLerpToRef(startValue, endValue, gradient, result) { const startScale = MathTmp.Vector3[0]; const startRotation = MathTmp.Quaternion[0]; const startTranslation = MathTmp.Vector3[1]; startValue.decompose(startScale, startRotation, startTranslation); const endScale = MathTmp.Vector3[2]; const endRotation = MathTmp.Quaternion[1]; const endTranslation = MathTmp.Vector3[3]; endValue.decompose(endScale, endRotation, endTranslation); const resultScale = MathTmp.Vector3[4]; Vector3.LerpToRef(startScale, endScale, gradient, resultScale); const resultRotation = MathTmp.Quaternion[2]; Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation); const resultTranslation = MathTmp.Vector3[5]; Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation); _Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result); return result; } /** * Creates a new matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera. * This function generates a matrix suitable for a left handed coordinate system * Example Playground - https://playground.babylonjs.com/#AV9X17#58 * Example Playground - https://playground.babylonjs.com/#AV9X17#59 * @param eye defines the final position of the entity * @param target defines where the entity should look at * @param up defines the up vector for the entity * @returns the new matrix */ static LookAtLH(eye, target, up) { const result = new _Matrix(); _Matrix.LookAtLHToRef(eye, target, up, result); return result; } /** * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera. * This function generates a matrix suitable for a left handed coordinate system * Example Playground - https://playground.babylonjs.com/#AV9X17#60 * Example Playground - https://playground.babylonjs.com/#AV9X17#61 * @param eye defines the final position of the entity * @param target defines where the entity should look at * @param up defines the up vector for the entity * @param result defines the target matrix * @returns result input */ static LookAtLHToRef(eye, target, up, result) { const xAxis = MathTmp.Vector3[0]; const yAxis = MathTmp.Vector3[1]; const zAxis = MathTmp.Vector3[2]; target.subtractToRef(eye, zAxis); zAxis.normalize(); Vector3.CrossToRef(up, zAxis, xAxis); const xSquareLength = xAxis.lengthSquared(); if (xSquareLength === 0) { xAxis.x = 1; } else { xAxis.normalizeFromLength(Math.sqrt(xSquareLength)); } Vector3.CrossToRef(zAxis, xAxis, yAxis); yAxis.normalize(); const ex = -Vector3.Dot(xAxis, eye); const ey = -Vector3.Dot(yAxis, eye); const ez = -Vector3.Dot(zAxis, eye); _Matrix.FromValuesToRef(xAxis._x, yAxis._x, zAxis._x, 0, xAxis._y, yAxis._y, zAxis._y, 0, xAxis._z, yAxis._z, zAxis._z, 0, ex, ey, ez, 1, result); return result; } /** * Creates a new matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera. * This function generates a matrix suitable for a right handed coordinate system * Example Playground - https://playground.babylonjs.com/#AV9X17#62 * Example Playground - https://playground.babylonjs.com/#AV9X17#63 * @param eye defines the final position of the entity * @param target defines where the entity should look at * @param up defines the up vector for the entity * @returns the new matrix */ static LookAtRH(eye, target, up) { const result = new _Matrix(); _Matrix.LookAtRHToRef(eye, target, up, result); return result; } /** * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes three vectors as arguments that together describe the position and orientation of the camera. * This function generates a matrix suitable for a right handed coordinate system * Example Playground - https://playground.babylonjs.com/#AV9X17#64 * Example Playground - https://playground.babylonjs.com/#AV9X17#65 * @param eye defines the final position of the entity * @param target defines where the entity should look at * @param up defines the up vector for the entity * @param result defines the target matrix * @returns result input */ static LookAtRHToRef(eye, target, up, result) { const xAxis = MathTmp.Vector3[0]; const yAxis = MathTmp.Vector3[1]; const zAxis = MathTmp.Vector3[2]; eye.subtractToRef(target, zAxis); zAxis.normalize(); Vector3.CrossToRef(up, zAxis, xAxis); const xSquareLength = xAxis.lengthSquared(); if (xSquareLength === 0) { xAxis.x = 1; } else { xAxis.normalizeFromLength(Math.sqrt(xSquareLength)); } Vector3.CrossToRef(zAxis, xAxis, yAxis); yAxis.normalize(); const ex = -Vector3.Dot(xAxis, eye); const ey = -Vector3.Dot(yAxis, eye); const ez = -Vector3.Dot(zAxis, eye); _Matrix.FromValuesToRef(xAxis._x, yAxis._x, zAxis._x, 0, xAxis._y, yAxis._y, zAxis._y, 0, xAxis._z, yAxis._z, zAxis._z, 0, ex, ey, ez, 1, result); return result; } /** * Creates a new matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0) * This function generates a matrix suitable for a left handed coordinate system * Example Playground - https://playground.babylonjs.com/#AV9X17#66 * @param forward defines the forward direction - Must be normalized and orthogonal to up. * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. * @returns the new matrix */ static LookDirectionLH(forward, up) { const result = new _Matrix(); _Matrix.LookDirectionLHToRef(forward, up, result); return result; } /** * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0) * This function generates a matrix suitable for a left handed coordinate system * Example Playground - https://playground.babylonjs.com/#AV9X17#67 * @param forward defines the forward direction - Must be normalized and orthogonal to up. * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. * @param result defines the target matrix * @returns result input */ static LookDirectionLHToRef(forward, up, result) { const back = MathTmp.Vector3[0]; back.copyFrom(forward); back.scaleInPlace(-1); const left = MathTmp.Vector3[1]; Vector3.CrossToRef(up, back, left); _Matrix.FromValuesToRef(left._x, left._y, left._z, 0, up._x, up._y, up._z, 0, back._x, back._y, back._z, 0, 0, 0, 0, 1, result); return result; } /** * Creates a new matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0) * This function generates a matrix suitable for a right handed coordinate system * Example Playground - https://playground.babylonjs.com/#AV9X17#68 * @param forward defines the forward direction - Must be normalized and orthogonal to up. * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. * @returns the new matrix */ static LookDirectionRH(forward, up) { const result = new _Matrix(); _Matrix.LookDirectionRHToRef(forward, up, result); return result; } /** * Sets the given "result" Matrix to a matrix that transforms vertices from world space to camera space. It takes two vectors as arguments that together describe the orientation of the camera. The position is assumed to be at the origin (0,0,0) * This function generates a matrix suitable for a right handed coordinate system * Example Playground - https://playground.babylonjs.com/#AV9X17#69 * @param forward defines the forward direction - Must be normalized and orthogonal to up. * @param up defines the up vector for the entity - Must be normalized and orthogonal to forward. * @param result defines the target matrix * @returns result input */ static LookDirectionRHToRef(forward, up, result) { const right = MathTmp.Vector3[2]; Vector3.CrossToRef(up, forward, right); _Matrix.FromValuesToRef(right._x, right._y, right._z, 0, up._x, up._y, up._z, 0, forward._x, forward._y, forward._z, 0, 0, 0, 0, 1, result); return result; } /** * Create a left-handed orthographic projection matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#70 * @param width defines the viewport width * @param height defines the viewport height * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @returns a new matrix as a left-handed orthographic projection matrix */ static OrthoLH(width, height, znear, zfar, halfZRange) { const matrix = new _Matrix(); _Matrix.OrthoLHToRef(width, height, znear, zfar, matrix, halfZRange); return matrix; } /** * Store a left-handed orthographic projection to a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#71 * @param width defines the viewport width * @param height defines the viewport height * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param result defines the target matrix * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @returns result input */ static OrthoLHToRef(width, height, znear, zfar, result, halfZRange) { const n = znear; const f = zfar; const a = 2 / width; const b = 2 / height; const c = 2 / (f - n); const d = -(f + n) / (f - n); _Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, 0, 0, d, 1, result); if (halfZRange) { result.multiplyToRef(mtxConvertNDCToHalfZRange, result); } result._updateIdentityStatus(a === 1 && b === 1 && c === 1 && d === 0); return result; } /** * Create a left-handed orthographic projection matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#72 * @param left defines the viewport left coordinate * @param right defines the viewport right coordinate * @param bottom defines the viewport bottom coordinate * @param top defines the viewport top coordinate * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @returns a new matrix as a left-handed orthographic projection matrix */ static OrthoOffCenterLH(left, right, bottom, top, znear, zfar, halfZRange) { const matrix = new _Matrix(); _Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix, halfZRange); return matrix; } /** * Stores a left-handed orthographic projection into a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#73 * @param left defines the viewport left coordinate * @param right defines the viewport right coordinate * @param bottom defines the viewport bottom coordinate * @param top defines the viewport top coordinate * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param result defines the target matrix * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @returns result input */ static OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result, halfZRange) { const n = znear; const f = zfar; const a = 2 / (right - left); const b = 2 / (top - bottom); const c = 2 / (f - n); const d = -(f + n) / (f - n); const i0 = (left + right) / (left - right); const i1 = (top + bottom) / (bottom - top); _Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, i0, i1, d, 1, result); if (halfZRange) { result.multiplyToRef(mtxConvertNDCToHalfZRange, result); } result.markAsUpdated(); return result; } /** * Stores a left-handed oblique projection into a given matrix * @param left defines the viewport left coordinate * @param right defines the viewport right coordinate * @param bottom defines the viewport bottom coordinate * @param top defines the viewport top coordinate * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param length Length of the shear * @param angle Angle (along X/Y Plane) to apply shear * @param distance Distance from shear point * @param result defines the target matrix * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @returns result input */ static ObliqueOffCenterLHToRef(left, right, bottom, top, znear, zfar, length, angle, distance, result, halfZRange) { const a = -length * Math.cos(angle); const b = -length * Math.sin(angle); _Matrix.TranslationToRef(0, 0, -distance, MathTmp.Matrix[1]); _Matrix.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, a, b, 1, 0, 0, 0, 0, 1, MathTmp.Matrix[0]); MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], MathTmp.Matrix[0]); _Matrix.TranslationToRef(0, 0, distance, MathTmp.Matrix[1]); MathTmp.Matrix[0].multiplyToRef(MathTmp.Matrix[1], MathTmp.Matrix[0]); _Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result, halfZRange); MathTmp.Matrix[0].multiplyToRef(result, result); return result; } /** * Creates a right-handed orthographic projection matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#76 * @param left defines the viewport left coordinate * @param right defines the viewport right coordinate * @param bottom defines the viewport bottom coordinate * @param top defines the viewport top coordinate * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @returns a new matrix as a right-handed orthographic projection matrix */ static OrthoOffCenterRH(left, right, bottom, top, znear, zfar, halfZRange) { const matrix = new _Matrix(); _Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix, halfZRange); return matrix; } /** * Stores a right-handed orthographic projection into a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#77 * @param left defines the viewport left coordinate * @param right defines the viewport right coordinate * @param bottom defines the viewport bottom coordinate * @param top defines the viewport top coordinate * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param result defines the target matrix * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @returns result input */ static OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, result, halfZRange) { _Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result, halfZRange); result._m[10] *= -1; return result; } /** * Stores a right-handed oblique projection into a given matrix * @param left defines the viewport left coordinate * @param right defines the viewport right coordinate * @param bottom defines the viewport bottom coordinate * @param top defines the viewport top coordinate * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param length Length of the shear * @param angle Angle (along X/Y Plane) to apply shear * @param distance Distance from shear point * @param result defines the target matrix * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @returns result input */ static ObliqueOffCenterRHToRef(left, right, bottom, top, znear, zfar, length, angle, distance, result, halfZRange) { const a = length * Math.cos(angle); const b = length * Math.sin(angle); _Matrix.TranslationToRef(0, 0, distance, MathTmp.Matrix[1]); _Matrix.FromValuesToRef(1, 0, 0, 0, 0, 1, 0, 0, a, b, 1, 0, 0, 0, 0, 1, MathTmp.Matrix[0]); MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], MathTmp.Matrix[0]); _Matrix.TranslationToRef(0, 0, -distance, MathTmp.Matrix[1]); MathTmp.Matrix[0].multiplyToRef(MathTmp.Matrix[1], MathTmp.Matrix[0]); _Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, result, halfZRange); MathTmp.Matrix[0].multiplyToRef(result, result); return result; } /** * Creates a left-handed perspective projection matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#85 * @param width defines the viewport width * @param height defines the viewport height * @param znear defines the near clip plane * @param zfar defines the far clip plane * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) * @returns a new matrix as a left-handed perspective projection matrix */ static PerspectiveLH(width, height, znear, zfar, halfZRange, projectionPlaneTilt = 0) { const matrix = new _Matrix(); const n = znear; const f = zfar; const a = 2 * n / width; const b = 2 * n / height; const c = (f + n) / (f - n); const d = -2 * f * n / (f - n); const rot = Math.tan(projectionPlaneTilt); _Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, rot, 0, 0, c, 1, 0, 0, d, 0, matrix); if (halfZRange) { matrix.multiplyToRef(mtxConvertNDCToHalfZRange, matrix); } matrix._updateIdentityStatus(false); return matrix; } /** * Creates a left-handed perspective projection matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#78 * @param fov defines the horizontal field of view * @param aspect defines the aspect ratio * @param znear defines the near clip plane * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function) * @returns a new matrix as a left-handed perspective projection matrix */ static PerspectiveFovLH(fov, aspect, znear, zfar, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) { const matrix = new _Matrix(); _Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix, true, halfZRange, projectionPlaneTilt, reverseDepthBufferMode); return matrix; } /** * Stores a left-handed perspective projection into a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#81 * @param fov defines the horizontal field of view * @param aspect defines the aspect ratio * @param znear defines the near clip plane * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode * @param result defines the target matrix * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function) * @returns result input */ static PerspectiveFovLHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) { const n = znear; const f = zfar; const t = 1 / Math.tan(fov * 0.5); const a = isVerticalFovFixed ? t / aspect : t; const b = isVerticalFovFixed ? t : t * aspect; const c = reverseDepthBufferMode && n === 0 ? -1 : f !== 0 ? (f + n) / (f - n) : 1; const d = reverseDepthBufferMode && n === 0 ? 2 * f : f !== 0 ? -2 * f * n / (f - n) : -2 * n; const rot = Math.tan(projectionPlaneTilt); _Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, rot, 0, 0, c, 1, 0, 0, d, 0, result); if (halfZRange) { result.multiplyToRef(mtxConvertNDCToHalfZRange, result); } result._updateIdentityStatus(false); return result; } /** * Stores a left-handed perspective projection into a given matrix with depth reversed * Example Playground - https://playground.babylonjs.com/#AV9X17#89 * @param fov defines the horizontal field of view * @param aspect defines the aspect ratio * @param znear defines the near clip plane * @param zfar not used as infinity is used as far clip * @param result defines the target matrix * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) * @returns result input */ static PerspectiveFovReverseLHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0) { const t = 1 / Math.tan(fov * 0.5); const a = isVerticalFovFixed ? t / aspect : t; const b = isVerticalFovFixed ? t : t * aspect; const rot = Math.tan(projectionPlaneTilt); _Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, rot, 0, 0, -znear, 1, 0, 0, 1, 0, result); if (halfZRange) { result.multiplyToRef(mtxConvertNDCToHalfZRange, result); } result._updateIdentityStatus(false); return result; } /** * Creates a right-handed perspective projection matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#83 * @param fov defines the horizontal field of view * @param aspect defines the aspect ratio * @param znear defines the near clip plane * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function) * @returns a new matrix as a right-handed perspective projection matrix */ static PerspectiveFovRH(fov, aspect, znear, zfar, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) { const matrix = new _Matrix(); _Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix, true, halfZRange, projectionPlaneTilt, reverseDepthBufferMode); return matrix; } /** * Stores a right-handed perspective projection into a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#84 * @param fov defines the horizontal field of view * @param aspect defines the aspect ratio * @param znear defines the near clip plane * @param zfar defines the far clip plane. If 0, assume we are in "infinite zfar" mode * @param result defines the target matrix * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) * @param reverseDepthBufferMode true to indicate that we are in a reverse depth buffer mode (meaning znear and zfar have been inverted when calling the function) * @returns result input */ static PerspectiveFovRHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0, reverseDepthBufferMode = false) { const n = znear; const f = zfar; const t = 1 / Math.tan(fov * 0.5); const a = isVerticalFovFixed ? t / aspect : t; const b = isVerticalFovFixed ? t : t * aspect; const c = reverseDepthBufferMode && n === 0 ? 1 : f !== 0 ? -(f + n) / (f - n) : -1; const d = reverseDepthBufferMode && n === 0 ? 2 * f : f !== 0 ? -2 * f * n / (f - n) : -2 * n; const rot = Math.tan(projectionPlaneTilt); _Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, rot, 0, 0, c, -1, 0, 0, d, 0, result); if (halfZRange) { result.multiplyToRef(mtxConvertNDCToHalfZRange, result); } result._updateIdentityStatus(false); return result; } /** * Stores a right-handed perspective projection into a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#90 * @param fov defines the horizontal field of view * @param aspect defines the aspect ratio * @param znear defines the near clip plane * @param zfar not used as infinity is used as far clip * @param result defines the target matrix * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally * @param halfZRange true to generate NDC coordinates between 0 and 1 instead of -1 and 1 (default: false) * @param projectionPlaneTilt optional tilt angle of the projection plane around the X axis (horizontal) * @returns result input */ static PerspectiveFovReverseRHToRef(fov, aspect, znear, zfar, result, isVerticalFovFixed = true, halfZRange, projectionPlaneTilt = 0) { const t = 1 / Math.tan(fov * 0.5); const a = isVerticalFovFixed ? t / aspect : t; const b = isVerticalFovFixed ? t : t * aspect; const rot = Math.tan(projectionPlaneTilt); _Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, rot, 0, 0, -znear, -1, 0, 0, -1, 0, result); if (halfZRange) { result.multiplyToRef(mtxConvertNDCToHalfZRange, result); } result._updateIdentityStatus(false); return result; } /** * Computes a complete transformation matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#113 * @param viewport defines the viewport to use * @param world defines the world matrix * @param view defines the view matrix * @param projection defines the projection matrix * @param zmin defines the near clip plane * @param zmax defines the far clip plane * @returns the transformation matrix */ static GetFinalMatrix(viewport, world, view, projection, zmin, zmax) { const cw = viewport.width; const ch = viewport.height; const cx = viewport.x; const cy = viewport.y; const viewportMatrix = _Matrix.FromValues(cw / 2, 0, 0, 0, 0, -ch / 2, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2, ch / 2 + cy, zmin, 1); const matrix = new _Matrix(); world.multiplyToRef(view, matrix); matrix.multiplyToRef(projection, matrix); return matrix.multiplyToRef(viewportMatrix, matrix); } /** * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array * @param matrix defines the matrix to use * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix */ static GetAsMatrix2x2(matrix) { const m = matrix.m; const arr = [m[0], m[1], m[4], m[5]]; return PerformanceConfigurator.MatrixUse64Bits ? arr : new Float32Array(arr); } /** * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array * @param matrix defines the matrix to use * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix */ static GetAsMatrix3x3(matrix) { const m = matrix.m; const arr = [m[0], m[1], m[2], m[4], m[5], m[6], m[8], m[9], m[10]]; return PerformanceConfigurator.MatrixUse64Bits ? arr : new Float32Array(arr); } /** * Compute the transpose of a given matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#111 * @param matrix defines the matrix to transpose * @returns the new matrix */ static Transpose(matrix) { const result = new _Matrix(); _Matrix.TransposeToRef(matrix, result); return result; } /** * Compute the transpose of a matrix and store it in a target matrix * Example Playground - https://playground.babylonjs.com/#AV9X17#112 * @param matrix defines the matrix to transpose * @param result defines the target matrix * @returns result input */ static TransposeToRef(matrix, result) { const mm = matrix.m; const rm0 = mm[0]; const rm1 = mm[4]; const rm2 = mm[8]; const rm3 = mm[12]; const rm4 = mm[1]; const rm5 = mm[5]; const rm6 = mm[9]; const rm7 = mm[13]; const rm8 = mm[2]; const rm9 = mm[6]; const rm10 = mm[10]; const rm11 = mm[14]; const rm12 = mm[3]; const rm13 = mm[7]; const rm14 = mm[11]; const rm15 = mm[15]; const rm = result._m; rm[0] = rm0; rm[1] = rm1; rm[2] = rm2; rm[3] = rm3; rm[4] = rm4; rm[5] = rm5; rm[6] = rm6; rm[7] = rm7; rm[8] = rm8; rm[9] = rm9; rm[10] = rm10; rm[11] = rm11; rm[12] = rm12; rm[13] = rm13; rm[14] = rm14; rm[15] = rm15; result.markAsUpdated(); result._updateIdentityStatus(matrix._isIdentity, matrix._isIdentityDirty); return result; } /** * Computes a reflection matrix from a plane * Example Playground - https://playground.babylonjs.com/#AV9X17#87 * @param plane defines the reflection plane * @returns a new matrix */ static Reflection(plane) { const matrix = new _Matrix(); _Matrix.ReflectionToRef(plane, matrix); return matrix; } /** * Computes a reflection matrix from a plane * Example Playground - https://playground.babylonjs.com/#AV9X17#88 * @param plane defines the reflection plane * @param result defines the target matrix * @returns result input */ static ReflectionToRef(plane, result) { plane.normalize(); const x = plane.normal.x; const y = plane.normal.y; const z = plane.normal.z; const temp = -2 * x; const temp2 = -2 * y; const temp3 = -2 * z; _Matrix.FromValuesToRef(temp * x + 1, temp2 * x, temp3 * x, 0, temp * y, temp2 * y + 1, temp3 * y, 0, temp * z, temp2 * z, temp3 * z + 1, 0, temp * plane.d, temp2 * plane.d, temp3 * plane.d, 1, result); return result; } /** * Sets the given matrix as a rotation matrix composed from the 3 left handed axes * @param xaxis defines the value of the 1st axis * @param yaxis defines the value of the 2nd axis * @param zaxis defines the value of the 3rd axis * @param result defines the target matrix * @returns result input */ static FromXYZAxesToRef(xaxis, yaxis, zaxis, result) { _Matrix.FromValuesToRef(xaxis._x, xaxis._y, xaxis._z, 0, yaxis._x, yaxis._y, yaxis._z, 0, zaxis._x, zaxis._y, zaxis._z, 0, 0, 0, 0, 1, result); return result; } /** * Creates a rotation matrix from a quaternion and stores it in a target matrix * @param quat defines the quaternion to use * @param result defines the target matrix * @returns result input */ static FromQuaternionToRef(quat, result) { const xx = quat._x * quat._x; const yy = quat._y * quat._y; const zz = quat._z * quat._z; const xy = quat._x * quat._y; const zw = quat._z * quat._w; const zx = quat._z * quat._x; const yw = quat._y * quat._w; const yz = quat._y * quat._z; const xw = quat._x * quat._w; result._m[0] = 1 - 2 * (yy + zz); result._m[1] = 2 * (xy + zw); result._m[2] = 2 * (zx - yw); result._m[3] = 0; result._m[4] = 2 * (xy - zw); result._m[5] = 1 - 2 * (zz + xx); result._m[6] = 2 * (yz + xw); result._m[7] = 0; result._m[8] = 2 * (zx + yw); result._m[9] = 2 * (yz - xw); result._m[10] = 1 - 2 * (yy + xx); result._m[11] = 0; result._m[12] = 0; result._m[13] = 0; result._m[14] = 0; result._m[15] = 1; result.markAsUpdated(); return result; } }; Matrix._IdentityReadOnly = Matrix.Identity(); Object.defineProperties(Matrix.prototype, { dimension: { value: [4, 4] }, rank: { value: 2 } }); MathTmp = class { static { __name(this, "MathTmp"); } }; MathTmp.Vector3 = BuildTuple(11, Vector3.Zero); MathTmp.Matrix = BuildTuple(2, Matrix.Identity); MathTmp.Quaternion = BuildTuple(3, Quaternion.Zero); TmpVectors = class { static { __name(this, "TmpVectors"); } }; TmpVectors.Vector2 = BuildTuple(3, Vector2.Zero); TmpVectors.Vector3 = BuildTuple(13, Vector3.Zero); TmpVectors.Vector4 = BuildTuple(3, Vector4.Zero); TmpVectors.Quaternion = BuildTuple(3, Quaternion.Zero); TmpVectors.Matrix = BuildTuple(8, Matrix.Identity); RegisterClass("BABYLON.Vector2", Vector2); RegisterClass("BABYLON.Vector3", Vector3); RegisterClass("BABYLON.Vector4", Vector4); RegisterClass("BABYLON.Matrix", Matrix); mtxConvertNDCToHalfZRange = Matrix.FromValues(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 1); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/domManagement.js function IsWindowObjectExist() { return typeof window !== "undefined"; } function IsNavigatorAvailable() { return typeof navigator !== "undefined"; } function IsDocumentAvailable() { return typeof document !== "undefined"; } function GetDOMTextContent(element) { let result = ""; let child = element.firstChild; while (child) { if (child.nodeType === 3) { result += child.textContent; } child = child.nextSibling; } return result; } var DomManagement; var init_domManagement = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/domManagement.js"() { __name(IsWindowObjectExist, "IsWindowObjectExist"); __name(IsNavigatorAvailable, "IsNavigatorAvailable"); __name(IsDocumentAvailable, "IsDocumentAvailable"); __name(GetDOMTextContent, "GetDOMTextContent"); DomManagement = { /** * Checks if the window object exists * @returns true if the window object exists */ IsWindowObjectExist, /** * Checks if the navigator object exists * @returns true if the navigator object exists */ IsNavigatorAvailable, /** * Check if the document object exists * @returns true if the document object exists */ IsDocumentAvailable, /** * Extracts text content from a DOM element hierarchy * @param element defines the root element * @returns a string */ GetDOMTextContent }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/logger.js var Logger; var init_logger = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/logger.js"() { Logger = class _Logger { static { __name(this, "Logger"); } static _CheckLimit(message, limit) { let entry = _Logger._LogLimitOutputs[message]; if (!entry) { entry = { limit, current: 1 }; _Logger._LogLimitOutputs[message] = entry; } else { entry.current++; } return entry.current <= entry.limit; } static _GenerateLimitMessage(message, level = 1) { const entry = _Logger._LogLimitOutputs[message]; if (!entry || !_Logger.MessageLimitReached) { return; } const type = this._Levels[level]; if (entry.current === entry.limit) { _Logger[type.name](_Logger.MessageLimitReached.replace(/%LIMIT%/g, "" + entry.limit).replace(/%TYPE%/g, type.name ?? "")); } } static _AddLogEntry(entry) { _Logger._LogCache = entry + _Logger._LogCache; if (_Logger.OnNewCacheEntry) { _Logger.OnNewCacheEntry(entry); } } static _FormatMessage(message) { const padStr = /* @__PURE__ */ __name((i) => i < 10 ? "0" + i : "" + i, "padStr"); const date = /* @__PURE__ */ new Date(); return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message; } // eslint-disable-next-line @typescript-eslint/no-unused-vars static _LogDisabled(message, limit) { } static _LogEnabled(level = 1, message, limit) { const msg = Array.isArray(message) ? message[0] : message; if (limit !== void 0 && !_Logger._CheckLimit(msg, limit)) { return; } const formattedMessage = _Logger._FormatMessage(msg); const type = this._Levels[level]; const optionals = Array.isArray(message) ? message.slice(1) : []; type.logFunc && type.logFunc("BJS - " + formattedMessage, ...optionals); const entry = `
${formattedMessage}

`; _Logger._AddLogEntry(entry); _Logger._GenerateLimitMessage(msg, level); } /** * Gets current log cache (list of logs) */ static get LogCache() { return _Logger._LogCache; } /** * Clears the log cache */ static ClearLogCache() { _Logger._LogCache = ""; _Logger._LogLimitOutputs = {}; _Logger.errorsCount = 0; } /** * Sets the current log level. This property is a bit field, allowing you to combine different levels (MessageLogLevel / WarningLogLevel / ErrorLogLevel). * Use NoneLogLevel to disable logging and AllLogLevel for a quick way to enable all levels. */ static set LogLevels(level) { _Logger.Log = _Logger._LogDisabled; _Logger.Warn = _Logger._LogDisabled; _Logger.Error = _Logger._LogDisabled; const levels = [_Logger.MessageLogLevel, _Logger.WarningLogLevel, _Logger.ErrorLogLevel]; for (const l of levels) { if ((level & l) === l) { const type = this._Levels[l]; _Logger[type.name] = _Logger._LogEnabled.bind(_Logger, l); } } } }; Logger.NoneLogLevel = 0; Logger.MessageLogLevel = 1; Logger.WarningLogLevel = 2; Logger.ErrorLogLevel = 4; Logger.AllLogLevel = 7; Logger.MessageLimitReached = "Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message."; Logger._LogCache = ""; Logger._LogLimitOutputs = {}; Logger._Levels = [ {}, { color: "white", logFunc: console.log, name: "Log" }, { color: "orange", logFunc: console.warn, name: "Warn" }, {}, { color: "red", logFunc: console.error, name: "Error" } ]; Logger.errorsCount = 0; Logger.Log = Logger._LogEnabled.bind(Logger, Logger.MessageLogLevel); Logger.Warn = Logger._LogEnabled.bind(Logger, Logger.WarningLogLevel); Logger.Error = Logger._LogEnabled.bind(Logger, Logger.ErrorLogLevel); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/deepCopier.js function GetAllPropertyNames(obj) { const props = []; do { const propNames = Object.getOwnPropertyNames(obj); for (const prop of propNames) { if (props.indexOf(prop) === -1) { props.push(prop); } } } while (obj = Object.getPrototypeOf(obj)); return props; } var CloneValue, DeepCopier; var init_deepCopier = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/deepCopier.js"() { init_logger(); CloneValue = /* @__PURE__ */ __name((source, destinationObject, shallowCopyValues) => { if (!source) { return null; } if (source.getClassName && source.getClassName() === "Mesh") { return null; } if (source.getClassName && (source.getClassName() === "SubMesh" || source.getClassName() === "PhysicsBody")) { return source.clone(destinationObject); } else if (source.clone) { return source.clone(); } else if (Array.isArray(source)) { return source.slice(); } else if (shallowCopyValues && typeof source === "object") { return { ...source }; } return null; }, "CloneValue"); __name(GetAllPropertyNames, "GetAllPropertyNames"); DeepCopier = class { static { __name(this, "DeepCopier"); } /** * Tries to copy an object by duplicating every property * @param source defines the source object * @param destination defines the target object * @param doNotCopyList defines a list of properties to avoid * @param mustCopyList defines a list of properties to copy (even if they start with _) * @param shallowCopyValues defines wether properties referencing objects (none cloneable) must be shallow copied (false by default) * @remarks shallowCopyValues will not instantite the copied values which makes it only usable for "JSON objects" */ static DeepCopy(source, destination, doNotCopyList, mustCopyList, shallowCopyValues = false) { const properties = GetAllPropertyNames(source); for (const prop of properties) { if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) { continue; } if (prop.endsWith("Observable")) { continue; } if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) { continue; } const sourceValue = source[prop]; const typeOfSourceValue = typeof sourceValue; if (typeOfSourceValue === "function") { continue; } try { if (typeOfSourceValue === "object") { if (sourceValue instanceof Uint8Array) { destination[prop] = Uint8Array.from(sourceValue); } else if (sourceValue instanceof Array) { destination[prop] = []; if (sourceValue.length > 0) { if (typeof sourceValue[0] == "object") { for (let index = 0; index < sourceValue.length; index++) { const clonedValue = CloneValue(sourceValue[index], destination, shallowCopyValues); if (destination[prop].indexOf(clonedValue) === -1) { destination[prop].push(clonedValue); } } } else { destination[prop] = sourceValue.slice(0); } } } else { destination[prop] = CloneValue(sourceValue, destination, shallowCopyValues); } } else { destination[prop] = sourceValue; } } catch (e) { Logger.Warn(e.message); } } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/precisionDate.js var PrecisionDate; var init_precisionDate = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/precisionDate.js"() { init_domManagement(); PrecisionDate = class { static { __name(this, "PrecisionDate"); } /** * Gets either window.performance.now() if supported or Date.now() else */ static get Now() { if (IsWindowObjectExist() && window.performance && window.performance.now) { return window.performance.now(); } return Date.now(); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/devTools.js function _WarnImport(name260, warnOnce = false) { if (warnOnce && WarnedMap[name260]) { return; } WarnedMap[name260] = true; return `${name260} needs to be imported before as it contains a side-effect required by your code.`; } var WarnedMap; var init_devTools = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/devTools.js"() { WarnedMap = {}; __name(_WarnImport, "_WarnImport"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/webRequest.js function createXMLHttpRequest() { if (typeof _native !== "undefined" && _native.XMLHttpRequest) { return new _native.XMLHttpRequest(); } else { return new XMLHttpRequest(); } } var WebRequest; var init_webRequest = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/webRequest.js"() { __name(createXMLHttpRequest, "createXMLHttpRequest"); WebRequest = class _WebRequest { static { __name(this, "WebRequest"); } constructor() { this._xhr = createXMLHttpRequest(); this._requestURL = ""; } /** * This function can be called to check if there are request modifiers for network requests * @returns true if there are any custom requests available */ static get IsCustomRequestAvailable() { return Object.keys(_WebRequest.CustomRequestHeaders).length > 0 || _WebRequest.CustomRequestModifiers.length > 0; } /** * Returns the requested URL once open has been called */ get requestURL() { return this._requestURL; } _injectCustomRequestHeaders() { if (this._shouldSkipRequestModifications(this._requestURL)) { return; } for (const key in _WebRequest.CustomRequestHeaders) { const val = _WebRequest.CustomRequestHeaders[key]; if (val) { this._xhr.setRequestHeader(key, val); } } } _shouldSkipRequestModifications(url) { return _WebRequest.SkipRequestModificationForBabylonCDN && (url.includes("preview.babylonjs.com") || url.includes("cdn.babylonjs.com")); } /** * Gets or sets a function to be called when loading progress changes */ get onprogress() { return this._xhr.onprogress; } set onprogress(value) { this._xhr.onprogress = value; } /** * Returns client's state */ get readyState() { return this._xhr.readyState; } /** * Returns client's status */ get status() { return this._xhr.status; } /** * Returns client's status as a text */ get statusText() { return this._xhr.statusText; } /** * Returns client's response */ get response() { return this._xhr.response; } /** * Returns client's response url */ get responseURL() { return this._xhr.responseURL; } /** * Returns client's response as text */ get responseText() { return this._xhr.responseText; } /** * Gets or sets the expected response type */ get responseType() { return this._xhr.responseType; } set responseType(value) { this._xhr.responseType = value; } /** * Gets or sets the timeout value in milliseconds */ get timeout() { return this._xhr.timeout; } set timeout(value) { this._xhr.timeout = value; } addEventListener(type, listener, options) { this._xhr.addEventListener(type, listener, options); } removeEventListener(type, listener, options) { this._xhr.removeEventListener(type, listener, options); } /** * Cancels any network activity */ abort() { this._xhr.abort(); } /** * Initiates the request. The optional argument provides the request body. The argument is ignored if request method is GET or HEAD * @param body defines an optional request body */ send(body) { if (_WebRequest.CustomRequestHeaders) { this._injectCustomRequestHeaders(); } this._xhr.send(body); } /** * Sets the request method, request URL * @param method defines the method to use (GET, POST, etc..) * @param url defines the url to connect with */ open(method, url) { for (const update of _WebRequest.CustomRequestModifiers) { if (this._shouldSkipRequestModifications(url)) { return; } url = update(this._xhr, url) || url; } url = url.replace("file:http:", "http:"); url = url.replace("file:https:", "https:"); this._requestURL = url; this._xhr.open(method, url, true); } /** * Sets the value of a request header. * @param name The name of the header whose value is to be set * @param value The value to set as the body of the header */ setRequestHeader(name260, value) { this._xhr.setRequestHeader(name260, value); } /** * Get the string containing the text of a particular header's value. * @param name The name of the header * @returns The string containing the text of the given header name */ getResponseHeader(name260) { return this._xhr.getResponseHeader(name260); } }; WebRequest.CustomRequestHeaders = {}; WebRequest.CustomRequestModifiers = new Array(); WebRequest.SkipRequestModificationForBabylonCDN = true; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/filesInputStore.js var FilesInputStore; var init_filesInputStore = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/filesInputStore.js"() { FilesInputStore = class { static { __name(this, "FilesInputStore"); } }; FilesInputStore.FilesToLoad = {}; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/retryStrategy.js var RetryStrategy; var init_retryStrategy = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/retryStrategy.js"() { RetryStrategy = class { static { __name(this, "RetryStrategy"); } /** * Function used to defines an exponential back off strategy * @param maxRetries defines the maximum number of retries (3 by default) * @param baseInterval defines the interval between retries * @returns the strategy function to use */ static ExponentialBackoff(maxRetries = 3, baseInterval = 500) { return (url, request, retryIndex) => { if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) { return -1; } return Math.pow(2, retryIndex) * baseInterval; }; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/error.js var BaseError, ErrorCodes, RuntimeError, AbortError; var init_error = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/error.js"() { BaseError = class extends Error { static { __name(this, "BaseError"); } }; BaseError._setPrototypeOf = Object.setPrototypeOf || ((o, proto) => { o.__proto__ = proto; return o; }); ErrorCodes = { // Mesh errors 0-999 /** Invalid or empty mesh vertex positions. */ MeshInvalidPositionsError: 0, // Texture errors 1000-1999 /** Unsupported texture found. */ UnsupportedTextureError: 1e3, // GLTFLoader errors 2000-2999 /** Unexpected magic number found in GLTF file header. */ GLTFLoaderUnexpectedMagicError: 2e3, // SceneLoader errors 3000-3999 /** SceneLoader generic error code. Ideally wraps the inner exception. */ SceneLoaderError: 3e3, // File related errors 4000-4999 /** Load file error */ LoadFileError: 4e3, /** Request file error */ RequestFileError: 4001, /** Read file error */ ReadFileError: 4002 }; RuntimeError = class _RuntimeError extends BaseError { static { __name(this, "RuntimeError"); } /** * Creates a new RuntimeError * @param message defines the message of the error * @param errorCode the error code * @param innerError the error that caused the outer error */ constructor(message, errorCode, innerError) { super(message); this.errorCode = errorCode; this.innerError = innerError; this.name = "RuntimeError"; BaseError._setPrototypeOf(this, _RuntimeError.prototype); } }; AbortError = class _AbortError extends BaseError { static { __name(this, "AbortError"); } constructor(message = "Operation aborted") { super(message); this.name = "AbortError"; BaseError._setPrototypeOf(this, _AbortError.prototype); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/stringTools.js var EndsWith, StartsWith, Decode, EncodeArrayBufferToBase64, DecodeBase64ToString, DecodeBase64ToBinary, PadNumber, StringTools; var init_stringTools = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/stringTools.js"() { EndsWith = /* @__PURE__ */ __name((str, suffix) => { return str.endsWith(suffix); }, "EndsWith"); StartsWith = /* @__PURE__ */ __name((str, suffix) => { if (!str) { return false; } return str.startsWith(suffix); }, "StartsWith"); Decode = /* @__PURE__ */ __name((buffer) => { if (typeof TextDecoder !== "undefined") { return new TextDecoder().decode(buffer); } let result = ""; for (let i = 0; i < buffer.byteLength; i++) { result += String.fromCharCode(buffer[i]); } return result; }, "Decode"); EncodeArrayBufferToBase64 = /* @__PURE__ */ __name((buffer) => { const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; let output = ""; let chr1, chr2, chr3, enc1, enc2, enc3, enc4; let i = 0; const bytes = ArrayBuffer.isView(buffer) ? new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength) : new Uint8Array(buffer); while (i < bytes.length) { chr1 = bytes[i++]; chr2 = i < bytes.length ? bytes[i++] : Number.NaN; chr3 = i < bytes.length ? bytes[i++] : Number.NaN; enc1 = chr1 >> 2; enc2 = (chr1 & 3) << 4 | chr2 >> 4; enc3 = (chr2 & 15) << 2 | chr3 >> 6; enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output += keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } return output; }, "EncodeArrayBufferToBase64"); DecodeBase64ToString = /* @__PURE__ */ __name((base64Data) => { return atob(base64Data); }, "DecodeBase64ToString"); DecodeBase64ToBinary = /* @__PURE__ */ __name((base64Data) => { const decodedString = DecodeBase64ToString(base64Data); const bufferLength = decodedString.length; const bufferView = new Uint8Array(new ArrayBuffer(bufferLength)); for (let i = 0; i < bufferLength; i++) { bufferView[i] = decodedString.charCodeAt(i); } return bufferView.buffer; }, "DecodeBase64ToBinary"); PadNumber = /* @__PURE__ */ __name((num, length) => { let str = String(num); while (str.length < length) { str = "0" + str; } return str; }, "PadNumber"); StringTools = { EndsWith, StartsWith, Decode, EncodeArrayBufferToBase64, DecodeBase64ToString, DecodeBase64ToBinary, PadNumber }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeNode.js var DefaultAttributeKeywordName, DefaultVaryingKeywordName, ShaderCodeNode; var init_shaderCodeNode = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeNode.js"() { DefaultAttributeKeywordName = "attribute"; DefaultVaryingKeywordName = "varying"; ShaderCodeNode = class { static { __name(this, "ShaderCodeNode"); } constructor() { this.children = []; } // eslint-disable-next-line @typescript-eslint/no-unused-vars isValid(preprocessors) { return true; } process(preprocessors, options, preProcessorsFromCode) { let result = ""; if (this.line) { let value = this.line; const processor = options.processor; if (processor) { if (processor.lineProcessor) { value = processor.lineProcessor(value, options.isFragment, options.processingContext); } const attributeKeyword = options.processor?.attributeKeywordName ?? DefaultAttributeKeywordName; const varyingKeyword = options.isFragment && options.processor?.varyingFragmentKeywordName ? options.processor?.varyingFragmentKeywordName : !options.isFragment && options.processor?.varyingVertexKeywordName ? options.processor?.varyingVertexKeywordName : DefaultVaryingKeywordName; if (!options.isFragment && processor.attributeProcessor && this.line.startsWith(attributeKeyword)) { value = processor.attributeProcessor(this.line, preprocessors, options.processingContext); } else if (processor.varyingProcessor && (processor.varyingCheck?.(this.line, options.isFragment) || !processor.varyingCheck && this.line.startsWith(varyingKeyword))) { value = processor.varyingProcessor(this.line, options.isFragment, preprocessors, options.processingContext); } else if (processor.uniformProcessor && processor.uniformRegexp && processor.uniformRegexp.test(this.line)) { if (!options.lookForClosingBracketForUniformBuffer) { value = processor.uniformProcessor(this.line, options.isFragment, preprocessors, options.processingContext); } } else if (processor.uniformBufferProcessor && processor.uniformBufferRegexp && processor.uniformBufferRegexp.test(this.line)) { if (!options.lookForClosingBracketForUniformBuffer) { value = processor.uniformBufferProcessor(this.line, options.isFragment, options.processingContext); options.lookForClosingBracketForUniformBuffer = true; } } else if (processor.textureProcessor && processor.textureRegexp && processor.textureRegexp.test(this.line)) { value = processor.textureProcessor(this.line, options.isFragment, preprocessors, options.processingContext); } else if ((processor.uniformProcessor || processor.uniformBufferProcessor) && this.line.startsWith("uniform") && !options.lookForClosingBracketForUniformBuffer) { const regex = /uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/; if (regex.test(this.line)) { if (processor.uniformProcessor) { value = processor.uniformProcessor(this.line, options.isFragment, preprocessors, options.processingContext); } } else { if (processor.uniformBufferProcessor) { value = processor.uniformBufferProcessor(this.line, options.isFragment, options.processingContext); options.lookForClosingBracketForUniformBuffer = true; } } } if (options.lookForClosingBracketForUniformBuffer && this.line.indexOf("}") !== -1) { options.lookForClosingBracketForUniformBuffer = false; if (processor.endOfUniformBufferProcessor) { value = processor.endOfUniformBufferProcessor(this.line, options.isFragment, options.processingContext); } } } result += value + "\n"; } for (const child of this.children) { result += child.process(preprocessors, options, preProcessorsFromCode); } if (this.additionalDefineKey) { preprocessors[this.additionalDefineKey] = this.additionalDefineValue || "true"; preProcessorsFromCode[this.additionalDefineKey] = preprocessors[this.additionalDefineKey]; } return result; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeCursor.js var ShaderCodeCursor; var init_shaderCodeCursor = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeCursor.js"() { ShaderCodeCursor = class { static { __name(this, "ShaderCodeCursor"); } constructor() { this._lines = []; } get currentLine() { return this._lines[this.lineIndex]; } get canRead() { return this.lineIndex < this._lines.length - 1; } set lines(value) { this._lines.length = 0; for (const line of value) { if (!line || line === "\r") { continue; } if (line[0] === "#") { this._lines.push(line); continue; } const trimmedLine = line.trim(); if (!trimmedLine) { continue; } if (trimmedLine.startsWith("//")) { this._lines.push(line); continue; } const semicolonIndex = trimmedLine.indexOf(";"); if (semicolonIndex === -1) { this._lines.push(trimmedLine); } else if (semicolonIndex === trimmedLine.length - 1) { if (trimmedLine.length > 1) { this._lines.push(trimmedLine); } } else { const split = line.split(";"); for (let index = 0; index < split.length; index++) { let subLine = split[index]; if (!subLine) { continue; } subLine = subLine.trim(); if (!subLine) { continue; } this._lines.push(subLine + (index !== split.length - 1 ? ";" : "")); } } } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeConditionNode.js var ShaderCodeConditionNode; var init_shaderCodeConditionNode = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeConditionNode.js"() { init_shaderCodeNode(); ShaderCodeConditionNode = class extends ShaderCodeNode { static { __name(this, "ShaderCodeConditionNode"); } process(preprocessors, options, preProcessorsFromCode) { for (let index = 0; index < this.children.length; index++) { const node = this.children[index]; if (node.isValid(preprocessors)) { return node.process(preprocessors, options, preProcessorsFromCode); } } return ""; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeTestNode.js var ShaderCodeTestNode; var init_shaderCodeTestNode = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderCodeTestNode.js"() { init_shaderCodeNode(); ShaderCodeTestNode = class extends ShaderCodeNode { static { __name(this, "ShaderCodeTestNode"); } isValid(preprocessors) { return this.testExpression.isTrue(preprocessors); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/shaderDefineExpression.js var ShaderDefineExpression; var init_shaderDefineExpression = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/shaderDefineExpression.js"() { ShaderDefineExpression = class _ShaderDefineExpression { static { __name(this, "ShaderDefineExpression"); } // eslint-disable-next-line @typescript-eslint/no-unused-vars isTrue(preprocessors) { return true; } static postfixToInfix(postfix) { const stack = []; for (const c of postfix) { if (_ShaderDefineExpression._OperatorPriority[c] === void 0) { stack.push(c); } else { const v1 = stack[stack.length - 1], v2 = stack[stack.length - 2]; stack.length -= 2; stack.push(`(${v2}${c}${v1})`); } } return stack[stack.length - 1]; } /** * Converts an infix expression to a postfix expression. * * This method is used to transform infix expressions, which are more human-readable, * into postfix expressions, also known as Reverse Polish Notation (RPN), that can be * evaluated more efficiently by a computer. The conversion is based on the operator * priority defined in _OperatorPriority. * * The function employs a stack-based algorithm for the conversion and caches the result * to improve performance. The cache keeps track of each converted expression's access time * to manage the cache size and optimize memory usage. When the cache size exceeds a specified * limit, the least recently accessed items in the cache are deleted. * * The cache mechanism is particularly helpful for shader compilation, where the same infix * expressions might be encountered repeatedly, hence the caching can speed up the process. * * @param infix - The infix expression to be converted. * @returns The postfix expression as an array of strings. */ static infixToPostfix(infix) { const cacheItem = _ShaderDefineExpression._InfixToPostfixCache.get(infix); if (cacheItem) { cacheItem.accessTime = Date.now(); return cacheItem.result; } if (!infix.includes("&&") && !infix.includes("||") && !infix.includes(")") && !infix.includes("(")) { return [infix]; } const result = []; let stackIdx = -1; const pushOperand = /* @__PURE__ */ __name(() => { operand = operand.trim(); if (operand !== "") { result.push(operand); operand = ""; } }, "pushOperand"); const push = /* @__PURE__ */ __name((s) => { if (stackIdx < _ShaderDefineExpression._Stack.length - 1) { _ShaderDefineExpression._Stack[++stackIdx] = s; } }, "push"); const peek = /* @__PURE__ */ __name(() => _ShaderDefineExpression._Stack[stackIdx], "peek"); const pop = /* @__PURE__ */ __name(() => stackIdx === -1 ? "!!INVALID EXPRESSION!!" : _ShaderDefineExpression._Stack[stackIdx--], "pop"); let idx = 0, operand = ""; while (idx < infix.length) { const c = infix.charAt(idx), token = idx < infix.length - 1 ? infix.substring(idx, 2 + idx) : ""; 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()); } } if (_ShaderDefineExpression._InfixToPostfixCache.size >= _ShaderDefineExpression.InfixToPostfixCacheLimitSize) { _ShaderDefineExpression.ClearCache(); } _ShaderDefineExpression._InfixToPostfixCache.set(infix, { result, accessTime: Date.now() }); return result; } static ClearCache() { const sortedCache = Array.from(_ShaderDefineExpression._InfixToPostfixCache.entries()).sort((a, b) => a[1].accessTime - b[1].accessTime); for (let i = 0; i < _ShaderDefineExpression.InfixToPostfixCacheCleanupSize; i++) { _ShaderDefineExpression._InfixToPostfixCache.delete(sortedCache[i][0]); } } }; ShaderDefineExpression.InfixToPostfixCacheLimitSize = 5e4; ShaderDefineExpression.InfixToPostfixCacheCleanupSize = 25e3; ShaderDefineExpression._InfixToPostfixCache = /* @__PURE__ */ new Map(); ShaderDefineExpression._OperatorPriority = { ")": 0, "(": 1, "||": 2, "&&": 3 }; ShaderDefineExpression._Stack = ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineIsDefinedOperator.js var ShaderDefineIsDefinedOperator; var init_shaderDefineIsDefinedOperator = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineIsDefinedOperator.js"() { init_shaderDefineExpression(); ShaderDefineIsDefinedOperator = class extends ShaderDefineExpression { static { __name(this, "ShaderDefineIsDefinedOperator"); } constructor(define, not = false) { super(); this.define = define; this.not = not; } isTrue(preprocessors) { let condition = preprocessors[this.define] !== void 0; if (this.not) { condition = !condition; } return condition; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineOrOperator.js var ShaderDefineOrOperator; var init_shaderDefineOrOperator = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineOrOperator.js"() { init_shaderDefineExpression(); ShaderDefineOrOperator = class extends ShaderDefineExpression { static { __name(this, "ShaderDefineOrOperator"); } isTrue(preprocessors) { return this.leftOperand.isTrue(preprocessors) || this.rightOperand.isTrue(preprocessors); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineAndOperator.js var ShaderDefineAndOperator; var init_shaderDefineAndOperator = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineAndOperator.js"() { init_shaderDefineExpression(); ShaderDefineAndOperator = class extends ShaderDefineExpression { static { __name(this, "ShaderDefineAndOperator"); } isTrue(preprocessors) { return this.leftOperand.isTrue(preprocessors) && this.rightOperand.isTrue(preprocessors); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineArithmeticOperator.js var ShaderDefineArithmeticOperator; var init_shaderDefineArithmeticOperator = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/Expressions/Operators/shaderDefineArithmeticOperator.js"() { init_shaderDefineExpression(); ShaderDefineArithmeticOperator = class extends ShaderDefineExpression { static { __name(this, "ShaderDefineArithmeticOperator"); } constructor(define, operand, testValue) { super(); this.define = define; this.operand = operand; this.testValue = testValue; } toString() { return `${this.define} ${this.operand} ${this.testValue}`; } isTrue(preprocessors) { let condition = false; const left = parseInt(preprocessors[this.define] != void 0 ? preprocessors[this.define] : this.define); const right = parseInt(preprocessors[this.testValue] != void 0 ? preprocessors[this.testValue] : this.testValue); if (isNaN(left) || isNaN(right)) { return false; } 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; case "!=": condition = left !== right; break; } return condition; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/abstractEngine.functions.js function _ConcatenateShader(source, defines, shaderVersion = "") { return shaderVersion + (defines ? defines + "\n" : "") + source; } function _LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, injectedLoadFile) { const loadFile = injectedLoadFile || EngineFunctionContext.loadFile; if (loadFile) { const request = loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError); return request; } throw _WarnImport("FileTools"); } function getHostDocument(renderingCanvas = null) { if (renderingCanvas && renderingCanvas.ownerDocument) { return renderingCanvas.ownerDocument; } return IsDocumentAvailable() ? document : null; } function _GetGlobalDefines(defines, isNDCHalfZRange, useReverseDepthBuffer, useExactSrgbConversions) { if (defines) { if (isNDCHalfZRange) { defines["IS_NDC_HALF_ZRANGE"] = ""; } else { delete defines["IS_NDC_HALF_ZRANGE"]; } if (useReverseDepthBuffer) { defines["USE_REVERSE_DEPTHBUFFER"] = ""; } else { delete defines["USE_REVERSE_DEPTHBUFFER"]; } if (useExactSrgbConversions) { defines["USE_EXACT_SRGB_CONVERSIONS"] = ""; } else { delete defines["USE_EXACT_SRGB_CONVERSIONS"]; } return; } else { let s = ""; if (isNDCHalfZRange) { s += "#define IS_NDC_HALF_ZRANGE"; } if (useReverseDepthBuffer) { if (s) { s += "\n"; } s += "#define USE_REVERSE_DEPTHBUFFER"; } if (useExactSrgbConversions) { if (s) { s += "\n"; } s += "#define USE_EXACT_SRGB_CONVERSIONS"; } return s; } } function allocateAndCopyTypedBuffer(type, sizeOrDstBuffer, sizeInBytes = false, copyBuffer) { switch (type) { case 3: { const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Int8Array(sizeOrDstBuffer) : new Int8Array(sizeOrDstBuffer); if (copyBuffer) { buffer2.set(new Int8Array(copyBuffer)); } return buffer2; } case 0: { const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer); if (copyBuffer) { buffer2.set(new Uint8Array(copyBuffer)); } return buffer2; } case 4: { const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Int16Array(sizeOrDstBuffer) : new Int16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer); if (copyBuffer) { buffer2.set(new Int16Array(copyBuffer)); } return buffer2; } case 5: case 8: case 9: case 10: case 2: { const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint16Array(sizeOrDstBuffer) : new Uint16Array(sizeInBytes ? sizeOrDstBuffer / 2 : sizeOrDstBuffer); if (copyBuffer) { buffer2.set(new Uint16Array(copyBuffer)); } return buffer2; } case 6: { const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Int32Array(sizeOrDstBuffer) : new Int32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer); if (copyBuffer) { buffer2.set(new Int32Array(copyBuffer)); } return buffer2; } case 7: case 11: case 12: case 13: case 14: case 15: { const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint32Array(sizeOrDstBuffer) : new Uint32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer); if (copyBuffer) { buffer2.set(new Uint32Array(copyBuffer)); } return buffer2; } case 1: { const buffer2 = sizeOrDstBuffer instanceof ArrayBuffer ? new Float32Array(sizeOrDstBuffer) : new Float32Array(sizeInBytes ? sizeOrDstBuffer / 4 : sizeOrDstBuffer); if (copyBuffer) { buffer2.set(new Float32Array(copyBuffer)); } return buffer2; } } const buffer = sizeOrDstBuffer instanceof ArrayBuffer ? new Uint8Array(sizeOrDstBuffer) : new Uint8Array(sizeOrDstBuffer); if (copyBuffer) { buffer.set(new Uint8Array(copyBuffer)); } return buffer; } var EngineFunctionContext; var init_abstractEngine_functions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/abstractEngine.functions.js"() { init_devTools(); init_domManagement(); EngineFunctionContext = {}; __name(_ConcatenateShader, "_ConcatenateShader"); __name(_LoadFile, "_LoadFile"); __name(getHostDocument, "getHostDocument"); __name(_GetGlobalDefines, "_GetGlobalDefines"); __name(allocateAndCopyTypedBuffer, "allocateAndCopyTypedBuffer"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderProcessor.js function Initialize(options) { if (options.processor && options.processor.initializeShaders) { options.processor.initializeShaders(options.processingContext); } } function Process(sourceCode, options, callback, engine) { if (options.processor?.preProcessShaderCode) { sourceCode = options.processor.preProcessShaderCode(sourceCode, options.isFragment); } ProcessIncludes(sourceCode, options, (codeWithIncludes) => { if (options.processCodeAfterIncludes) { codeWithIncludes = options.processCodeAfterIncludes(options.isFragment ? "fragment" : "vertex", codeWithIncludes, options.defines); } const migratedCode = ProcessShaderConversion(codeWithIncludes, options, engine); callback(migratedCode, codeWithIncludes); }); } function PreProcess(sourceCode, options, callback, engine) { if (options.processor?.preProcessShaderCode) { sourceCode = options.processor.preProcessShaderCode(sourceCode, options.isFragment); } ProcessIncludes(sourceCode, options, (codeWithIncludes) => { if (options.processCodeAfterIncludes) { codeWithIncludes = options.processCodeAfterIncludes(options.isFragment ? "fragment" : "vertex", codeWithIncludes, options.defines); } const migratedCode = ApplyPreProcessing(codeWithIncludes, options, engine); callback(migratedCode, codeWithIncludes); }); } function Finalize(vertexCode, fragmentCode, options) { if (!options.processor || !options.processor.finalizeShaders) { return { vertexCode, fragmentCode }; } return options.processor.finalizeShaders(vertexCode, fragmentCode, options.processingContext); } function ProcessPrecision(source, options) { if (options.processor?.noPrecision) { return source; } const 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) { source = source.replace("precision highp float", "precision mediump float"); } } return source; } function ExtractOperation(expression) { const regex = /defined\((.+)\)/; const match = regex.exec(expression); if (match && match.length) { return new ShaderDefineIsDefinedOperator(match[1].trim(), expression[0] === "!"); } const operators = ["==", "!=", ">=", "<=", "<", ">"]; let operator = ""; let indexOperator = 0; for (operator of operators) { indexOperator = expression.indexOf(operator); if (indexOperator > -1) { break; } } if (indexOperator === -1) { return new ShaderDefineIsDefinedOperator(expression); } const define = expression.substring(0, indexOperator).trim(); const value = expression.substring(indexOperator + operator.length).trim(); return new ShaderDefineArithmeticOperator(define, operator, value); } function BuildSubExpression(expression) { expression = expression.replace(RegexSe, "defined[$1]"); const postfix = ShaderDefineExpression.infixToPostfix(expression); const stack = []; for (const c of postfix) { if (c !== "||" && c !== "&&") { stack.push(c); } else if (stack.length >= 2) { let v1 = stack[stack.length - 1], v2 = stack[stack.length - 2]; stack.length -= 2; const operator = c == "&&" ? new ShaderDefineAndOperator() : new 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" ? ExtractOperation(v2) : v2; operator.rightOperand = typeof v1 === "string" ? ExtractOperation(v1) : v1; stack.push(operator); } } let result = stack[stack.length - 1]; if (typeof result === "string") { result = result.replace(RegexSeRevert, "defined($1)"); } return typeof result === "string" ? ExtractOperation(result) : result; } function BuildExpression(line, start) { const node = new ShaderCodeTestNode(); const command = line.substring(0, start); let expression = line.substring(start); expression = expression.substring(0, (expression.indexOf("//") + 1 || expression.length + 1) - 1).trim(); if (command === "#ifdef") { node.testExpression = new ShaderDefineIsDefinedOperator(expression); } else if (command === "#ifndef") { node.testExpression = new ShaderDefineIsDefinedOperator(expression, true); } else { node.testExpression = BuildSubExpression(expression); } return node; } function MoveCursorWithinIf(cursor, rootNode, ifNode, preProcessorsFromCode) { let line = cursor.currentLine; while (MoveCursor(cursor, ifNode, preProcessorsFromCode)) { line = cursor.currentLine; const first5 = line.substring(0, 5).toLowerCase(); if (first5 === "#else") { const elseNode = new ShaderCodeNode(); rootNode.children.push(elseNode); MoveCursor(cursor, elseNode, preProcessorsFromCode); return; } else if (first5 === "#elif") { const elifNode = BuildExpression(line, 5); rootNode.children.push(elifNode); ifNode = elifNode; } } } function MoveCursor(cursor, rootNode, preProcessorsFromCode) { while (cursor.canRead) { cursor.lineIndex++; const line = cursor.currentLine; if (line.indexOf("#") >= 0) { const matches = MoveCursorRegex.exec(line); if (matches && matches.length) { const keyword = matches[0]; switch (keyword) { case "#ifdef": { const newRootNode = new ShaderCodeConditionNode(); rootNode.children.push(newRootNode); const ifNode = BuildExpression(line, 6); newRootNode.children.push(ifNode); MoveCursorWithinIf(cursor, newRootNode, ifNode, preProcessorsFromCode); break; } case "#else": case "#elif": return true; case "#endif": return false; case "#ifndef": { const newRootNode = new ShaderCodeConditionNode(); rootNode.children.push(newRootNode); const ifNode = BuildExpression(line, 7); newRootNode.children.push(ifNode); MoveCursorWithinIf(cursor, newRootNode, ifNode, preProcessorsFromCode); break; } case "#if": { const newRootNode = new ShaderCodeConditionNode(); const ifNode = BuildExpression(line, 3); rootNode.children.push(newRootNode); newRootNode.children.push(ifNode); MoveCursorWithinIf(cursor, newRootNode, ifNode, preProcessorsFromCode); break; } } continue; } } const newNode = new ShaderCodeNode(); newNode.line = line; rootNode.children.push(newNode); if (line[0] === "#" && line[1] === "d") { const split = line.replace(";", "").split(" "); newNode.additionalDefineKey = split[1]; if (split.length === 3) { newNode.additionalDefineValue = split[2]; } } } return false; } function EvaluatePreProcessors(sourceCode, preprocessors, options, preProcessorsFromCode) { const rootNode = new ShaderCodeNode(); const cursor = new ShaderCodeCursor(); cursor.lineIndex = -1; cursor.lines = sourceCode.split("\n"); MoveCursor(cursor, rootNode, preProcessorsFromCode); return rootNode.process(preprocessors, options, preProcessorsFromCode); } function PreparePreProcessors(options, engine) { const defines = options.defines; const preprocessors = {}; for (const define of defines) { const keyValue = define.replace("#define", "").replace(";", "").trim(); const split = keyValue.split(" "); preprocessors[split[0]] = split.length > 1 ? split[1] : ""; } if (options.processor?.shaderLanguage === 0) { preprocessors["GL_ES"] = "true"; } preprocessors["__VERSION__"] = options.version; preprocessors[options.platformName] = "true"; _GetGlobalDefines(preprocessors, engine?.isNDCHalfZRange, engine?.useReverseDepthBuffer, engine?.useExactSrgbConversions); return preprocessors; } function ProcessShaderConversion(sourceCode, options, engine) { let preparedSourceCode = ProcessPrecision(sourceCode, options); if (!options.processor) { return preparedSourceCode; } if (options.processor.shaderLanguage === 0 && preparedSourceCode.indexOf("#version 3") !== -1) { preparedSourceCode = preparedSourceCode.replace("#version 300 es", ""); if (!options.processor.parseGLES3) { return preparedSourceCode; } } const defines = options.defines; const preprocessors = PreparePreProcessors(options, engine); if (options.processor.preProcessor) { preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, preprocessors, options.isFragment, options.processingContext); } const preProcessorsFromCode = {}; preparedSourceCode = EvaluatePreProcessors(preparedSourceCode, preprocessors, options, preProcessorsFromCode); if (options.processor.postProcessor) { preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine ? { drawBuffersExtensionDisabled: engine.getCaps().drawBuffersExtension ? false : true } : {}, preprocessors, preProcessorsFromCode); } if (engine?._features.needShaderCodeInlining) { preparedSourceCode = engine.inlineShaderCode(preparedSourceCode); } return preparedSourceCode; } function ApplyPreProcessing(sourceCode, options, engine) { let preparedSourceCode = sourceCode; const defines = options.defines; const preprocessors = PreparePreProcessors(options, engine); if (options.processor?.preProcessor) { preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, preprocessors, options.isFragment, options.processingContext); } const preProcessorsFromCode = {}; preparedSourceCode = EvaluatePreProcessors(preparedSourceCode, preprocessors, options, preProcessorsFromCode); if (options.processor?.postProcessor) { preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment, options.processingContext, engine ? { drawBuffersExtensionDisabled: engine.getCaps().drawBuffersExtension ? false : true } : {}, preprocessors, preProcessorsFromCode); } if (engine._features.needShaderCodeInlining) { preparedSourceCode = engine.inlineShaderCode(preparedSourceCode); } return preparedSourceCode; } function ProcessIncludes(sourceCode, options, callback) { ReusableMatches.length = 0; let match; while ((match = RegexShaderInclude.exec(sourceCode)) !== null) { ReusableMatches.push(match); } let returnValue = String(sourceCode); let parts = [sourceCode]; let keepProcessing = false; for (const match2 of ReusableMatches) { let includeFile = match2[1]; if (includeFile.indexOf("__decl__") !== -1) { includeFile = includeFile.replace(RegexShaderDecl, ""); if (options.supportsUniformBuffers) { includeFile = includeFile.replace("Vertex", "Ubo").replace("Fragment", "Ubo"); } includeFile = includeFile + "Declaration"; } if (options.includesShadersStore[includeFile]) { let includeContent = options.includesShadersStore[includeFile]; if (match2[2]) { const splits = match2[3].split(","); for (let index = 0; index < splits.length; index += 2) { const source = new RegExp(splits[index], "g"); const dest = splits[index + 1]; includeContent = includeContent.replace(source, dest); } } if (match2[4]) { const indexString = match2[5]; if (indexString.indexOf("..") !== -1) { const indexSplits = indexString.split(".."); const minIndex = parseInt(indexSplits[0]); let maxIndex = parseInt(indexSplits[1]); let sourceIncludeContent = includeContent.slice(0); includeContent = ""; if (isNaN(maxIndex)) { maxIndex = options.indexParameters[indexSplits[1]]; } for (let i = minIndex; i < maxIndex; i++) { if (!options.supportsUniformBuffers) { sourceIncludeContent = sourceIncludeContent.replace(RegexLightX, (str, p1) => { return p1 + "{X}"; }); } includeContent += sourceIncludeContent.replace(RegexX, i.toString()) + "\n"; } } else { if (!options.supportsUniformBuffers) { includeContent = includeContent.replace(RegexLightX, (str, p1) => { return p1 + "{X}"; }); } includeContent = includeContent.replace(RegexX, indexString); } } const newParts = []; for (const part of parts) { const splitPart = part.split(match2[0]); for (let i = 0; i < splitPart.length - 1; i++) { newParts.push(splitPart[i]); newParts.push(includeContent); } newParts.push(splitPart[splitPart.length - 1]); } parts = newParts; keepProcessing = keepProcessing || includeContent.indexOf("#include<") >= 0 || includeContent.indexOf("#include <") >= 0; } else { const includeShaderUrl = options.shadersRepository + "ShadersInclude/" + includeFile + ".fx"; _FunctionContainer.loadFile(includeShaderUrl, (fileContent) => { options.includesShadersStore[includeFile] = fileContent; ProcessIncludes(parts.join(""), options, callback); }); return; } } ReusableMatches.length = 0; returnValue = parts.join(""); if (keepProcessing) { ProcessIncludes(returnValue.toString(), options, callback); } else { callback(returnValue); } } var RegexSe, RegexSeRevert, RegexShaderInclude, RegexShaderDecl, RegexLightX, RegexX, ReusableMatches, MoveCursorRegex, _FunctionContainer; var init_shaderProcessor = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Processors/shaderProcessor.js"() { init_shaderCodeNode(); init_shaderCodeCursor(); init_shaderCodeConditionNode(); init_shaderCodeTestNode(); init_shaderDefineIsDefinedOperator(); init_shaderDefineOrOperator(); init_shaderDefineAndOperator(); init_shaderDefineExpression(); init_shaderDefineArithmeticOperator(); init_devTools(); init_abstractEngine_functions(); RegexSe = /defined\s*?\((.+?)\)/g; RegexSeRevert = /defined\s*?\[(.+?)\]/g; RegexShaderInclude = /#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g; RegexShaderDecl = /__decl__/; RegexLightX = /light\{X\}.(\w*)/g; RegexX = /\{X\}/g; ReusableMatches = []; MoveCursorRegex = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/; __name(Initialize, "Initialize"); __name(Process, "Process"); __name(PreProcess, "PreProcess"); __name(Finalize, "Finalize"); __name(ProcessPrecision, "ProcessPrecision"); __name(ExtractOperation, "ExtractOperation"); __name(BuildSubExpression, "BuildSubExpression"); __name(BuildExpression, "BuildExpression"); __name(MoveCursorWithinIf, "MoveCursorWithinIf"); __name(MoveCursor, "MoveCursor"); __name(EvaluatePreProcessors, "EvaluatePreProcessors"); __name(PreparePreProcessors, "PreparePreProcessors"); __name(ProcessShaderConversion, "ProcessShaderConversion"); __name(ApplyPreProcessing, "ApplyPreProcessing"); __name(ProcessIncludes, "ProcessIncludes"); _FunctionContainer = { /** * 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 * @internal */ loadFile: /* @__PURE__ */ __name((url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) => { throw _WarnImport("FileTools"); }, "loadFile") }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/timingTools.js function RunWithCondition(condition, onSuccess, onError) { try { if (condition()) { onSuccess(); return true; } } catch (e) { onError?.(e); return true; } return false; } var ImmediateQueue, TimingTools, _RetryWithInterval; var init_timingTools = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/timingTools.js"() { ImmediateQueue = []; TimingTools = class { static { __name(this, "TimingTools"); } /** * Execute a function after the current execution block * @param action defines the action to execute after the current execution block */ static SetImmediate(action) { if (ImmediateQueue.length === 0) { setTimeout(() => { const functionsToCall = ImmediateQueue; ImmediateQueue = []; for (const func of functionsToCall) { func(); } }, 1); } ImmediateQueue.push(action); } }; __name(RunWithCondition, "RunWithCondition"); _RetryWithInterval = /* @__PURE__ */ __name((condition, onSuccess, onError, step = 16, maxTimeout = 3e4, checkConditionOnCall = true, additionalStringOnTimeout) => { if (checkConditionOnCall) { if (RunWithCondition(condition, onSuccess, onError)) { return null; } } const int = setInterval(() => { if (RunWithCondition(condition, onSuccess, onError)) { clearInterval(int); } else { maxTimeout -= step; if (maxTimeout < 0) { clearInterval(int); onError?.(new Error("Operation timed out after maximum retries. " + (additionalStringOnTimeout || "")), true); } } }, step); return () => clearInterval(int); }, "_RetryWithInterval"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/shaderStore.js var ShaderStore; var init_shaderStore = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/shaderStore.js"() { ShaderStore = class _ShaderStore { static { __name(this, "ShaderStore"); } /** * Gets the shaders repository path for a given shader language * @param shaderLanguage the shader language * @returns the path to the shaders repository */ static GetShadersRepository(shaderLanguage = 0) { return shaderLanguage === 0 ? _ShaderStore.ShadersRepository : _ShaderStore.ShadersRepositoryWGSL; } /** * Gets the shaders store of a given shader language * @param shaderLanguage the shader language * @returns the shaders store */ static GetShadersStore(shaderLanguage = 0) { return shaderLanguage === 0 ? _ShaderStore.ShadersStore : _ShaderStore.ShadersStoreWGSL; } /** * Gets the include shaders store of a given shader language * @param shaderLanguage the shader language * @returns the include shaders store */ static GetIncludesShadersStore(shaderLanguage = 0) { return shaderLanguage === 0 ? _ShaderStore.IncludesShadersStore : _ShaderStore.IncludesShadersStoreWGSL; } }; ShaderStore.ShadersRepository = "src/Shaders/"; ShaderStore.ShadersStore = {}; ShaderStore.IncludesShadersStore = {}; ShaderStore.ShadersRepositoryWGSL = "src/ShadersWGSL/"; ShaderStore.ShadersStoreWGSL = {}; ShaderStore.IncludesShadersStoreWGSL = {}; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLPipelineContext.js var WebGLPipelineContext; var init_webGLPipelineContext = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLPipelineContext.js"() { WebGLPipelineContext = class { static { __name(this, "WebGLPipelineContext"); } constructor() { this._valueCache = {}; this.vertexCompilationError = null; this.fragmentCompilationError = null; this.programLinkError = null; this.programValidationError = null; this._isDisposed = false; } // eslint-disable-next-line no-restricted-syntax get isAsync() { return this.isParallelCompiled; } get isReady() { if (this.program) { if (this.isParallelCompiled) { return this.engine._isRenderingStateCompiled(this); } return true; } return false; } _handlesSpectorRebuildCallback(onCompiled) { if (onCompiled && this.program) { onCompiled(this.program); } } setEngine(engine) { this.engine = engine; } _fillEffectInformation(effect, uniformBuffersNames, uniformsNames, uniforms, samplerList, samplers, attributesNames, attributes) { const engine = this.engine; if (engine.supportsUniformBuffers) { for (const name260 in uniformBuffersNames) { effect.bindUniformBlock(name260, uniformBuffersNames[name260]); } } const effectAvailableUniforms = this.engine.getUniforms(this, uniformsNames); effectAvailableUniforms.forEach((uniform, index2) => { uniforms[uniformsNames[index2]] = uniform; }); this._uniforms = uniforms; let index; for (index = 0; index < samplerList.length; index++) { const sampler = effect.getUniform(samplerList[index]); if (sampler == null) { samplerList.splice(index, 1); index--; } } samplerList.forEach((name260, index2) => { samplers[name260] = index2; }); for (const attr of engine.getAttributes(this, attributesNames)) { attributes.push(attr); } } /** * Release all associated resources. **/ dispose() { this._uniforms = {}; this._isDisposed = true; } /** * @internal */ _cacheMatrix(uniformName, matrix) { const cache = this._valueCache[uniformName]; const flag = matrix.updateFlag; if (cache !== void 0 && cache === flag) { return false; } this._valueCache[uniformName] = flag; return true; } /** * @internal */ _cacheFloat2(uniformName, x, y) { let cache = this._valueCache[uniformName]; if (!cache || cache.length !== 2) { cache = [x, y]; this._valueCache[uniformName] = cache; return true; } let changed = false; if (cache[0] !== x) { cache[0] = x; changed = true; } if (cache[1] !== y) { cache[1] = y; changed = true; } return changed; } /** * @internal */ _cacheFloat3(uniformName, x, y, z) { let cache = this._valueCache[uniformName]; if (!cache || cache.length !== 3) { cache = [x, y, z]; this._valueCache[uniformName] = cache; return true; } let changed = false; if (cache[0] !== x) { cache[0] = x; changed = true; } if (cache[1] !== y) { cache[1] = y; changed = true; } if (cache[2] !== z) { cache[2] = z; changed = true; } return changed; } /** * @internal */ _cacheFloat4(uniformName, x, y, z, w) { let cache = this._valueCache[uniformName]; if (!cache || cache.length !== 4) { cache = [x, y, z, w]; this._valueCache[uniformName] = cache; return true; } let changed = false; if (cache[0] !== x) { cache[0] = x; changed = true; } if (cache[1] !== y) { cache[1] = y; changed = true; } if (cache[2] !== z) { cache[2] = z; changed = true; } if (cache[3] !== w) { cache[3] = w; changed = true; } return changed; } /** * Sets an integer value on a uniform variable. * @param uniformName Name of the variable. * @param value Value to be set. */ setInt(uniformName, value) { const cache = this._valueCache[uniformName]; if (cache !== void 0 && cache === value) { return; } if (this.engine.setInt(this._uniforms[uniformName], value)) { this._valueCache[uniformName] = value; } } /** * Sets a int2 on a uniform variable. * @param uniformName Name of the variable. * @param x First int in int2. * @param y Second int in int2. */ setInt2(uniformName, x, y) { if (this._cacheFloat2(uniformName, x, y)) { if (!this.engine.setInt2(this._uniforms[uniformName], x, y)) { this._valueCache[uniformName] = null; } } } /** * Sets a int3 on a uniform variable. * @param uniformName Name of the variable. * @param x First int in int3. * @param y Second int in int3. * @param z Third int in int3. */ setInt3(uniformName, x, y, z) { if (this._cacheFloat3(uniformName, x, y, z)) { if (!this.engine.setInt3(this._uniforms[uniformName], x, y, z)) { this._valueCache[uniformName] = null; } } } /** * Sets a int4 on a uniform variable. * @param uniformName Name of the variable. * @param x First int in int4. * @param y Second int in int4. * @param z Third int in int4. * @param w Fourth int in int4. */ setInt4(uniformName, x, y, z, w) { if (this._cacheFloat4(uniformName, x, y, z, w)) { if (!this.engine.setInt4(this._uniforms[uniformName], x, y, z, w)) { this._valueCache[uniformName] = null; } } } /** * Sets an int array on a uniform variable. * @param uniformName Name of the variable. * @param array array to be set. */ setIntArray(uniformName, array) { this._valueCache[uniformName] = null; this.engine.setIntArray(this._uniforms[uniformName], array); } /** * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. */ setIntArray2(uniformName, array) { this._valueCache[uniformName] = null; this.engine.setIntArray2(this._uniforms[uniformName], array); } /** * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. */ setIntArray3(uniformName, array) { this._valueCache[uniformName] = null; this.engine.setIntArray3(this._uniforms[uniformName], array); } /** * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. */ setIntArray4(uniformName, array) { this._valueCache[uniformName] = null; this.engine.setIntArray4(this._uniforms[uniformName], array); } /** * Sets an unsigned integer value on a uniform variable. * @param uniformName Name of the variable. * @param value Value to be set. */ setUInt(uniformName, value) { const cache = this._valueCache[uniformName]; if (cache !== void 0 && cache === value) { return; } if (this.engine.setUInt(this._uniforms[uniformName], value)) { this._valueCache[uniformName] = value; } } /** * Sets an unsigned int2 value on a uniform variable. * @param uniformName Name of the variable. * @param x First unsigned int in uint2. * @param y Second unsigned int in uint2. */ setUInt2(uniformName, x, y) { if (this._cacheFloat2(uniformName, x, y)) { if (!this.engine.setUInt2(this._uniforms[uniformName], x, y)) { this._valueCache[uniformName] = null; } } } /** * Sets an unsigned int3 value on a uniform variable. * @param uniformName Name of the variable. * @param x First unsigned int in uint3. * @param y Second unsigned int in uint3. * @param z Third unsigned int in uint3. */ setUInt3(uniformName, x, y, z) { if (this._cacheFloat3(uniformName, x, y, z)) { if (!this.engine.setUInt3(this._uniforms[uniformName], x, y, z)) { this._valueCache[uniformName] = null; } } } /** * Sets an unsigned int4 value on a uniform variable. * @param uniformName Name of the variable. * @param x First unsigned int in uint4. * @param y Second unsigned int in uint4. * @param z Third unsigned int in uint4. * @param w Fourth unsigned int in uint4. */ setUInt4(uniformName, x, y, z, w) { if (this._cacheFloat4(uniformName, x, y, z, w)) { if (!this.engine.setUInt4(this._uniforms[uniformName], x, y, z, w)) { this._valueCache[uniformName] = null; } } } /** * Sets an unsigned int array on a uniform variable. * @param uniformName Name of the variable. * @param array array to be set. */ setUIntArray(uniformName, array) { this._valueCache[uniformName] = null; this.engine.setUIntArray(this._uniforms[uniformName], array); } /** * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. */ setUIntArray2(uniformName, array) { this._valueCache[uniformName] = null; this.engine.setUIntArray2(this._uniforms[uniformName], array); } /** * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. */ setUIntArray3(uniformName, array) { this._valueCache[uniformName] = null; this.engine.setUIntArray3(this._uniforms[uniformName], array); } /** * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. */ setUIntArray4(uniformName, array) { this._valueCache[uniformName] = null; this.engine.setUIntArray4(this._uniforms[uniformName], array); } /** * Sets an array on a uniform variable. * @param uniformName Name of the variable. * @param array array to be set. */ setArray(uniformName, array) { this._valueCache[uniformName] = null; this.engine.setArray(this._uniforms[uniformName], array); } /** * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. */ setArray2(uniformName, array) { this._valueCache[uniformName] = null; this.engine.setArray2(this._uniforms[uniformName], array); } /** * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. */ setArray3(uniformName, array) { this._valueCache[uniformName] = null; this.engine.setArray3(this._uniforms[uniformName], array); } /** * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. */ setArray4(uniformName, array) { this._valueCache[uniformName] = null; this.engine.setArray4(this._uniforms[uniformName], array); } /** * Sets matrices on a uniform variable. * @param uniformName Name of the variable. * @param matrices matrices to be set. */ setMatrices(uniformName, matrices) { if (!matrices) { return; } this._valueCache[uniformName] = null; this.engine.setMatrices(this._uniforms[uniformName], matrices); } /** * Sets matrix on a uniform variable. * @param uniformName Name of the variable. * @param matrix matrix to be set. */ setMatrix(uniformName, matrix) { if (this._cacheMatrix(uniformName, matrix)) { if (!this.engine.setMatrices(this._uniforms[uniformName], matrix.asArray())) { this._valueCache[uniformName] = null; } } } /** * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix) * @param uniformName Name of the variable. * @param matrix matrix to be set. */ setMatrix3x3(uniformName, matrix) { this._valueCache[uniformName] = null; this.engine.setMatrix3x3(this._uniforms[uniformName], matrix); } /** * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix) * @param uniformName Name of the variable. * @param matrix matrix to be set. */ setMatrix2x2(uniformName, matrix) { this._valueCache[uniformName] = null; this.engine.setMatrix2x2(this._uniforms[uniformName], matrix); } /** * Sets a float on a uniform variable. * @param uniformName Name of the variable. * @param value value to be set. */ setFloat(uniformName, value) { const cache = this._valueCache[uniformName]; if (cache !== void 0 && cache === value) { return; } if (this.engine.setFloat(this._uniforms[uniformName], value)) { this._valueCache[uniformName] = value; } } /** * Sets a Vector2 on a uniform variable. * @param uniformName Name of the variable. * @param vector2 vector2 to be set. */ setVector2(uniformName, vector2) { if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) { if (!this.engine.setFloat2(this._uniforms[uniformName], vector2.x, vector2.y)) { this._valueCache[uniformName] = null; } } } /** * Sets a float2 on a uniform variable. * @param uniformName Name of the variable. * @param x First float in float2. * @param y Second float in float2. */ setFloat2(uniformName, x, y) { if (this._cacheFloat2(uniformName, x, y)) { if (!this.engine.setFloat2(this._uniforms[uniformName], x, y)) { this._valueCache[uniformName] = null; } } } /** * Sets a Vector3 on a uniform variable. * @param uniformName Name of the variable. * @param vector3 Value to be set. */ setVector3(uniformName, vector3) { if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) { if (!this.engine.setFloat3(this._uniforms[uniformName], vector3.x, vector3.y, vector3.z)) { this._valueCache[uniformName] = null; } } } /** * Sets a float3 on a uniform variable. * @param uniformName Name of the variable. * @param x First float in float3. * @param y Second float in float3. * @param z Third float in float3. */ setFloat3(uniformName, x, y, z) { if (this._cacheFloat3(uniformName, x, y, z)) { if (!this.engine.setFloat3(this._uniforms[uniformName], x, y, z)) { this._valueCache[uniformName] = null; } } } /** * Sets a Vector4 on a uniform variable. * @param uniformName Name of the variable. * @param vector4 Value to be set. */ setVector4(uniformName, vector4) { if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) { if (!this.engine.setFloat4(this._uniforms[uniformName], vector4.x, vector4.y, vector4.z, vector4.w)) { this._valueCache[uniformName] = null; } } } /** * Sets a Quaternion on a uniform variable. * @param uniformName Name of the variable. * @param quaternion Value to be set. */ setQuaternion(uniformName, quaternion) { if (this._cacheFloat4(uniformName, quaternion.x, quaternion.y, quaternion.z, quaternion.w)) { if (!this.engine.setFloat4(this._uniforms[uniformName], quaternion.x, quaternion.y, quaternion.z, quaternion.w)) { this._valueCache[uniformName] = null; } } } /** * Sets a float4 on a uniform variable. * @param uniformName Name of the variable. * @param x First float in float4. * @param y Second float in float4. * @param z Third float in float4. * @param w Fourth float in float4. */ setFloat4(uniformName, x, y, z, w) { if (this._cacheFloat4(uniformName, x, y, z, w)) { if (!this.engine.setFloat4(this._uniforms[uniformName], x, y, z, w)) { this._valueCache[uniformName] = null; } } } /** * Sets a Color3 on a uniform variable. * @param uniformName Name of the variable. * @param color3 Value to be set. */ setColor3(uniformName, color3) { if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) { if (!this.engine.setFloat3(this._uniforms[uniformName], color3.r, color3.g, color3.b)) { this._valueCache[uniformName] = null; } } } /** * Sets a Color4 on a uniform variable. * @param uniformName Name of the variable. * @param color3 Value to be set. * @param alpha Alpha value to be set. */ setColor4(uniformName, color3, alpha) { if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) { if (!this.engine.setFloat4(this._uniforms[uniformName], color3.r, color3.g, color3.b, alpha)) { this._valueCache[uniformName] = null; } } } /** * Sets a Color4 on a uniform variable * @param uniformName defines the name of the variable * @param color4 defines the value to be set */ setDirectColor4(uniformName, color4) { if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) { if (!this.engine.setFloat4(this._uniforms[uniformName], color4.r, color4.g, color4.b, color4.a)) { this._valueCache[uniformName] = null; } } } _getVertexShaderCode() { return this.vertexShader ? this.engine._getShaderSource(this.vertexShader) : null; } _getFragmentShaderCode() { return this.fragmentShader ? this.engine._getShaderSource(this.fragmentShader) : null; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/thinEngine.functions.js function getStateObject(context) { let state = StateObject.get(context); if (!state) { if (!context) { return SingleStateObject; } state = { // use feature detection. instanceof returns false. This only exists on WebGL2 context _webGLVersion: context.TEXTURE_BINDING_3D ? 2 : 1, _context: context, // when using the function without an engine we need to set it to enable parallel compilation parallelShaderCompile: context.getExtension("KHR_parallel_shader_compile") || void 0, cachedPipelines: {} }; StateObject.set(context, state); } return state; } function deleteStateObject(context) { StateObject.delete(context); } function createRawShaderProgram(pipelineContext, vertexCode, fragmentCode, context, transformFeedbackVaryings, _createShaderProgramInjection) { const stateObject = getStateObject(context); if (!_createShaderProgramInjection) { _createShaderProgramInjection = stateObject._createShaderProgramInjection ?? _createShaderProgram; } const vertexShader = CompileRawShader(vertexCode, "vertex", context, stateObject._contextWasLost); const fragmentShader = CompileRawShader(fragmentCode, "fragment", context, stateObject._contextWasLost); return _createShaderProgramInjection(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings, stateObject.validateShaderPrograms); } function createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings = null, _createShaderProgramInjection) { const stateObject = getStateObject(context); if (!_createShaderProgramInjection) { _createShaderProgramInjection = stateObject._createShaderProgramInjection ?? _createShaderProgram; } const shaderVersion = stateObject._webGLVersion > 1 ? "#version 300 es\n#define WEBGL2 \n" : ""; const vertexShader = CompileShader(vertexCode, "vertex", defines, shaderVersion, context, stateObject._contextWasLost); const fragmentShader = CompileShader(fragmentCode, "fragment", defines, shaderVersion, context, stateObject._contextWasLost); return _createShaderProgramInjection(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings, stateObject.validateShaderPrograms); } function createPipelineContext(context, _shaderProcessingContext) { const pipelineContext = new WebGLPipelineContext(); const stateObject = getStateObject(context); if (stateObject.parallelShaderCompile && !stateObject.disableParallelShaderCompile) { pipelineContext.isParallelCompiled = true; } pipelineContext.context = stateObject._context; return pipelineContext; } function _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, _transformFeedbackVaryings = null, validateShaderPrograms) { const 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) { _finalizePipelineContext(pipelineContext, context, validateShaderPrograms); } return shaderProgram; } function _isRenderingStateCompiled(pipelineContext, gl, validateShaderPrograms) { const webGLPipelineContext = pipelineContext; if (webGLPipelineContext._isDisposed) { return false; } const stateObject = getStateObject(gl); if (stateObject && stateObject.parallelShaderCompile && stateObject.parallelShaderCompile.COMPLETION_STATUS_KHR && webGLPipelineContext.program) { if (gl.getProgramParameter(webGLPipelineContext.program, stateObject.parallelShaderCompile.COMPLETION_STATUS_KHR)) { _finalizePipelineContext(webGLPipelineContext, gl, validateShaderPrograms); return true; } } return false; } function _finalizePipelineContext(pipelineContext, gl, validateShaderPrograms) { const context = pipelineContext.context; const vertexShader = pipelineContext.vertexShader; const fragmentShader = pipelineContext.fragmentShader; const program = pipelineContext.program; const linked = context.getProgramParameter(program, context.LINK_STATUS); if (!linked) { if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) { const log = gl.getShaderInfoLog(vertexShader); if (log) { pipelineContext.vertexCompilationError = log; throw new Error("VERTEX SHADER " + log); } } if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) { const log = gl.getShaderInfoLog(fragmentShader); if (log) { pipelineContext.fragmentCompilationError = log; throw new Error("FRAGMENT SHADER " + log); } } const error = context.getProgramInfoLog(program); if (error) { pipelineContext.programLinkError = error; throw new Error(error); } } if ( /*this.*/ validateShaderPrograms ) { context.validateProgram(program); const validated = context.getProgramParameter(program, context.VALIDATE_STATUS); if (!validated) { const error = context.getProgramInfoLog(program); if (error) { pipelineContext.programValidationError = error; throw new Error(error); } } } context.deleteShader(vertexShader); context.deleteShader(fragmentShader); pipelineContext.vertexShader = void 0; pipelineContext.fragmentShader = void 0; if (pipelineContext.onCompiled) { pipelineContext.onCompiled(); pipelineContext.onCompiled = void 0; } } function _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, _rawVertexSourceCode, _rawFragmentSourceCode, rebuildRebind, defines, transformFeedbackVaryings, _key = "", onReady, createRawShaderProgramInjection, createShaderProgramInjection) { const stateObject = getStateObject(pipelineContext.context); if (!createRawShaderProgramInjection) { createRawShaderProgramInjection = stateObject.createRawShaderProgramInjection ?? createRawShaderProgram; } if (!createShaderProgramInjection) { createShaderProgramInjection = stateObject.createShaderProgramInjection ?? createShaderProgram; } const webGLRenderingState = pipelineContext; if (createAsRaw) { webGLRenderingState.program = createRawShaderProgramInjection(webGLRenderingState, vertexSourceCode, fragmentSourceCode, webGLRenderingState.context, transformFeedbackVaryings); } else { webGLRenderingState.program = createShaderProgramInjection(webGLRenderingState, vertexSourceCode, fragmentSourceCode, defines, webGLRenderingState.context, transformFeedbackVaryings); } webGLRenderingState.program.__SPECTOR_rebuildProgram = rebuildRebind; onReady(); } function CompileShader(source, type, defines, shaderVersion, gl, _contextWasLost) { return CompileRawShader(_ConcatenateShader(source, defines, shaderVersion), type, gl, _contextWasLost); } function CompileRawShader(source, type, gl, _contextWasLost) { const shader260 = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER); if (!shader260) { let error = gl.NO_ERROR; let tempError = gl.NO_ERROR; while ((tempError = gl.getError()) !== gl.NO_ERROR) { error = tempError; } throw new Error(`Something went wrong while creating a gl ${type} shader object. gl error=${error}, gl isContextLost=${gl.isContextLost()}, _contextWasLost=${_contextWasLost}`); } gl.shaderSource(shader260, source); gl.compileShader(shader260); return shader260; } function _setProgram(program, gl) { gl.useProgram(program); } function _executeWhenRenderingStateIsCompiled(pipelineContext, action) { const webGLPipelineContext = pipelineContext; if (!webGLPipelineContext.isParallelCompiled) { action(pipelineContext); return; } const oldHandler = webGLPipelineContext.onCompiled; webGLPipelineContext.onCompiled = () => { oldHandler?.(); action(pipelineContext); }; } var StateObject, SingleStateObject; var init_thinEngine_functions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/thinEngine.functions.js"() { init_webGLPipelineContext(); init_abstractEngine_functions(); StateObject = /* @__PURE__ */ new WeakMap(); SingleStateObject = { _webGLVersion: 2, cachedPipelines: {} }; __name(getStateObject, "getStateObject"); __name(deleteStateObject, "deleteStateObject"); __name(createRawShaderProgram, "createRawShaderProgram"); __name(createShaderProgram, "createShaderProgram"); __name(createPipelineContext, "createPipelineContext"); __name(_createShaderProgram, "_createShaderProgram"); __name(_isRenderingStateCompiled, "_isRenderingStateCompiled"); __name(_finalizePipelineContext, "_finalizePipelineContext"); __name(_preparePipelineContext, "_preparePipelineContext"); __name(CompileShader, "CompileShader"); __name(CompileRawShader, "CompileRawShader"); __name(_setProgram, "_setProgram"); __name(_executeWhenRenderingStateIsCompiled, "_executeWhenRenderingStateIsCompiled"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effect.functions.js function getCachedPipeline(name260, context) { const stateObject = getStateObject(context); return stateObject.cachedPipelines[name260]; } function resetCachedPipeline(pipeline) { const name260 = pipeline._name; const context = pipeline.context; if (name260 && context) { const stateObject = getStateObject(context); const cachedPipeline = stateObject.cachedPipelines[name260]; cachedPipeline?.dispose(); delete stateObject.cachedPipelines[name260]; } } function _ProcessShaderCode(processorOptions, baseName, processFinalCode, onFinalCodeReady, shaderLanguage, engine, effectContext) { let vertexSource; let fragmentSource; const hostDocument = IsWindowObjectExist() ? engine?.getHostDocument() : null; if (typeof baseName === "string") { vertexSource = baseName; } else if (baseName.vertexSource) { vertexSource = "source:" + baseName.vertexSource; } else if (baseName.vertexElement) { vertexSource = hostDocument?.getElementById(baseName.vertexElement) || baseName.vertexElement; } else { vertexSource = baseName.vertex || baseName; } if (typeof baseName === "string") { fragmentSource = baseName; } else if (baseName.fragmentSource) { fragmentSource = "source:" + baseName.fragmentSource; } else if (baseName.fragmentElement) { fragmentSource = hostDocument?.getElementById(baseName.fragmentElement) || baseName.fragmentElement; } else { fragmentSource = baseName.fragment || baseName; } const shaderCodes = [void 0, void 0]; const shadersLoaded = /* @__PURE__ */ __name(() => { if (shaderCodes[0] && shaderCodes[1]) { processorOptions.isFragment = true; const [migratedVertexCode, fragmentCode] = shaderCodes; Process(fragmentCode, processorOptions, (migratedFragmentCode, codeBeforeMigration) => { if (effectContext) { effectContext._fragmentSourceCodeBeforeMigration = codeBeforeMigration; } if (processFinalCode) { migratedFragmentCode = processFinalCode("fragment", migratedFragmentCode); } const finalShaders = Finalize(migratedVertexCode, migratedFragmentCode, processorOptions); processorOptions = null; const finalCode = UseFinalCode(finalShaders.vertexCode, finalShaders.fragmentCode, baseName, shaderLanguage); onFinalCodeReady?.(finalCode.vertexSourceCode, finalCode.fragmentSourceCode); }, engine); } }, "shadersLoaded"); LoadShader(vertexSource, "Vertex", "", (vertexCode) => { Initialize(processorOptions); Process(vertexCode, processorOptions, (migratedVertexCode, codeBeforeMigration) => { if (effectContext) { effectContext._rawVertexSourceCode = vertexCode; effectContext._vertexSourceCodeBeforeMigration = codeBeforeMigration; } if (processFinalCode) { migratedVertexCode = processFinalCode("vertex", migratedVertexCode); } shaderCodes[0] = migratedVertexCode; shadersLoaded(); }, engine); }, shaderLanguage); LoadShader(fragmentSource, "Fragment", "Pixel", (fragmentCode) => { if (effectContext) { effectContext._rawFragmentSourceCode = fragmentCode; } shaderCodes[1] = fragmentCode; shadersLoaded(); }, shaderLanguage); } function LoadShader(shader260, key, optionalKey, callback, shaderLanguage, _loadFileInjection) { if (typeof HTMLElement !== "undefined") { if (shader260 instanceof HTMLElement) { const shaderCode = GetDOMTextContent(shader260); callback(shaderCode); return; } } if (shader260.substring(0, 7) === "source:") { callback(shader260.substring(7)); return; } if (shader260.substring(0, 7) === "base64:") { const shaderBinary = window.atob(shader260.substring(7)); callback(shaderBinary); return; } const shaderStore = ShaderStore.GetShadersStore(shaderLanguage); if (shaderStore[shader260 + key + "Shader"]) { callback(shaderStore[shader260 + key + "Shader"]); return; } if (optionalKey && shaderStore[shader260 + optionalKey + "Shader"]) { callback(shaderStore[shader260 + optionalKey + "Shader"]); return; } let shaderUrl; if (shader260[0] === "." || shader260[0] === "/" || shader260.indexOf("http") > -1) { shaderUrl = shader260; } else { shaderUrl = ShaderStore.GetShadersRepository(shaderLanguage) + shader260; } _loadFileInjection = _loadFileInjection || _LoadFile; if (!_loadFileInjection) { throw new Error("loadFileInjection is not defined"); } _loadFileInjection(shaderUrl + "." + key.toLowerCase() + ".fx", callback); } function UseFinalCode(migratedVertexCode, migratedFragmentCode, baseName, shaderLanguage) { if (baseName) { const vertex = baseName.vertexElement || baseName.vertex || baseName.spectorName || baseName; const fragment = baseName.fragmentElement || baseName.fragment || baseName.spectorName || baseName; return { vertexSourceCode: (shaderLanguage === 1 ? "//" : "") + "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode, fragmentSourceCode: (shaderLanguage === 1 ? "//" : "") + "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode }; } else { return { vertexSourceCode: migratedVertexCode, fragmentSourceCode: migratedFragmentCode }; } } var createAndPreparePipelineContext; var init_effect_functions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effect.functions.js"() { init_domManagement(); init_thinEngine_functions(); init_shaderStore(); init_logger(); init_shaderProcessor(); init_abstractEngine_functions(); __name(getCachedPipeline, "getCachedPipeline"); __name(resetCachedPipeline, "resetCachedPipeline"); __name(_ProcessShaderCode, "_ProcessShaderCode"); __name(LoadShader, "LoadShader"); __name(UseFinalCode, "UseFinalCode"); createAndPreparePipelineContext = /* @__PURE__ */ __name((options, createPipelineContext2, _preparePipelineContext2, _executeWhenRenderingStateIsCompiled2) => { try { const stateObject = options.context ? getStateObject(options.context) : null; if (stateObject) { stateObject.disableParallelShaderCompile = options.disableParallelCompilation; } const pipelineContext = options.existingPipelineContext || createPipelineContext2(options.shaderProcessingContext); pipelineContext._name = options.name; if (options.name && stateObject) { stateObject.cachedPipelines[options.name] = pipelineContext; } _preparePipelineContext2(pipelineContext, options.vertex, options.fragment, !!options.createAsRaw, "", "", options.rebuildRebind, options.defines, options.transformFeedbackVaryings, "", () => { _executeWhenRenderingStateIsCompiled2(pipelineContext, () => { options.onRenderingStateCompiled?.(pipelineContext); }); }); return pipelineContext; } catch (e) { Logger.Error("Error compiling effect"); throw e; } }, "createAndPreparePipelineContext"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effect.js var Effect; var init_effect = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effect.js"() { init_observable(); init_logger(); init_shaderStore(); init_effect_functions(); init_timingTools(); Effect = class _Effect { static { __name(this, "Effect"); } /** * Gets or sets the relative url used to load shaders if using the engine in non-minified mode */ static get ShadersRepository() { return ShaderStore.ShadersRepository; } static set ShadersRepository(repo) { ShaderStore.ShadersRepository = repo; } /** * Gets a boolean indicating that the effect was already disposed */ get isDisposed() { return this._isDisposed; } /** * Observable that will be called when effect is bound. */ get onBindObservable() { if (!this._onBindObservable) { this._onBindObservable = new Observable(); } return this._onBindObservable; } /** * Gets the shader language type used to write vertex and fragment source code. */ get shaderLanguage() { return this._shaderLanguage; } /** * Instantiates an effect. * An effect can be used to create/manage/execute vertex and fragment shaders. * @param baseName Name of the effect. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect. * @param samplers List of sampler variables that will be passed to the shader. * @param engine Engine to be used to render the effect * @param defines Define statements to be added to the shader. * @param fallbacks Possible fallbacks for this effect to improve performance when needed. * @param onCompiled Callback that will be called when the shader is compiled. * @param onError Callback that will be called if an error occurs during shader compilation. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. \{lights: 10\}) * @param key Effect Key identifying uniquely compiled shader variants * @param shaderLanguage the language the shader is written in (default: GLSL) * @param extraInitializationsAsync additional async code to run before preparing the effect */ constructor(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers = null, engine, defines = null, fallbacks = null, onCompiled = null, onError = null, indexParameters, key = "", shaderLanguage = 0, extraInitializationsAsync) { this.defines = ""; this.onCompiled = null; this.onError = null; this.onBind = null; this.uniqueId = 0; this.onCompileObservable = new Observable(); this.onErrorObservable = new Observable(); this._onBindObservable = null; this._isDisposed = false; this._refCount = 1; this._bonesComputationForcedToCPU = false; this._uniformBuffersNames = {}; this._multiTarget = false; this._samplers = {}; this._isReady = false; this._compilationError = ""; this._allFallbacksProcessed = false; this._uniforms = {}; this._key = ""; this._fallbacks = null; this._vertexSourceCodeOverride = ""; this._fragmentSourceCodeOverride = ""; this._transformFeedbackVaryings = null; this._disableParallelShaderCompilation = false; this._pipelineContext = null; this._vertexSourceCode = ""; this._fragmentSourceCode = ""; this._vertexSourceCodeBeforeMigration = ""; this._fragmentSourceCodeBeforeMigration = ""; this._rawVertexSourceCode = ""; this._rawFragmentSourceCode = ""; this._processCodeAfterIncludes = void 0; this._processFinalCode = null; this._onReleaseEffectsObserver = null; this.name = baseName; this._key = key; const pipelineName = this._key.replace(/\r/g, "").replace(/\n/g, "|"); let cachedPipeline = void 0; if (attributesNamesOrOptions.attributes) { const options = attributesNamesOrOptions; this._engine = uniformsNamesOrEngine; this._attributesNames = options.attributes; this._uniformsNames = options.uniformsNames.concat(options.samplers); this._samplerList = options.samplers.slice(); this.defines = options.defines; this.onError = options.onError; this.onCompiled = options.onCompiled; this._fallbacks = options.fallbacks; this._indexParameters = options.indexParameters; this._transformFeedbackVaryings = options.transformFeedbackVaryings || null; this._multiTarget = !!options.multiTarget; this._shaderLanguage = options.shaderLanguage ?? 0; this._disableParallelShaderCompilation = !!options.disableParallelShaderCompilation; if (options.uniformBuffersNames) { this._uniformBuffersNamesList = options.uniformBuffersNames.slice(); for (let i = 0; i < options.uniformBuffersNames.length; i++) { this._uniformBuffersNames[options.uniformBuffersNames[i]] = i; } } this._processFinalCode = options.processFinalCode ?? null; this._processCodeAfterIncludes = options.processCodeAfterIncludes ?? void 0; extraInitializationsAsync = options.extraInitializationsAsync; cachedPipeline = options.existingPipelineContext; } else { this._engine = engine; this.defines = defines == null ? "" : defines; this._uniformsNames = uniformsNamesOrEngine.concat(samplers); this._samplerList = samplers ? samplers.slice() : []; this._attributesNames = attributesNamesOrOptions; this._uniformBuffersNamesList = []; this._shaderLanguage = shaderLanguage; this.onError = onError; this.onCompiled = onCompiled; this._indexParameters = indexParameters; this._fallbacks = fallbacks; } if (this._engine.shaderPlatformName === "WEBGL2") { cachedPipeline = getCachedPipeline(pipelineName, this._engine._gl) ?? cachedPipeline; } this._attributeLocationByName = {}; this.uniqueId = _Effect._UniqueIdSeed++; if (!cachedPipeline) { this._processShaderCodeAsync(null, false, null, extraInitializationsAsync); } else { this._pipelineContext = cachedPipeline; this._pipelineContext.setEngine(this._engine); this._onRenderingStateCompiled(this._pipelineContext); if (this._pipelineContext.program) { this._pipelineContext.program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this); } } this._onReleaseEffectsObserver = this._engine.onReleaseEffectsObservable.addOnce(() => { this._onReleaseEffectsObserver = null; if (this.isDisposed) { return; } this.dispose(true); }); } /** @internal */ async _processShaderCodeAsync(shaderProcessor = null, keepExistingPipelineContext = false, shaderProcessingContext = null, extraInitializationsAsync) { if (extraInitializationsAsync) { await extraInitializationsAsync(); } this._processingContext = shaderProcessingContext || this._engine._getShaderProcessingContext(this._shaderLanguage, false); const processorOptions = { defines: this.defines.split("\n"), indexParameters: this._indexParameters, isFragment: false, shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader, processor: shaderProcessor ?? this._engine._getShaderProcessor(this._shaderLanguage), supportsUniformBuffers: this._engine.supportsUniformBuffers, shadersRepository: ShaderStore.GetShadersRepository(this._shaderLanguage), includesShadersStore: ShaderStore.GetIncludesShadersStore(this._shaderLanguage), version: (this._engine.version * 100).toString(), platformName: this._engine.shaderPlatformName, processingContext: this._processingContext, isNDCHalfZRange: this._engine.isNDCHalfZRange, useReverseDepthBuffer: this._engine.useReverseDepthBuffer, processCodeAfterIncludes: this._processCodeAfterIncludes }; _ProcessShaderCode(processorOptions, this.name, this._processFinalCode, (migratedVertexCode, migratedFragmentCode) => { this._vertexSourceCode = migratedVertexCode; this._fragmentSourceCode = migratedFragmentCode; this._prepareEffect(keepExistingPipelineContext); }, this._shaderLanguage, this._engine, this); } /** * Unique key for this effect */ get key() { return this._key; } /** * If the effect has been compiled and prepared. * @returns if the effect is compiled and prepared. */ isReady() { try { return this._isReadyInternal(); } catch { return false; } } _isReadyInternal() { if (this._engine.isDisposed) { return true; } if (this._isReady) { return true; } if (this._pipelineContext) { return this._pipelineContext.isReady; } return false; } /** * The engine the effect was initialized with. * @returns the engine. */ getEngine() { return this._engine; } /** * The pipeline context for this effect * @returns the associated pipeline context */ getPipelineContext() { return this._pipelineContext; } /** * The set of names of attribute variables for the shader. * @returns An array of attribute names. */ getAttributesNames() { return this._attributesNames; } /** * Returns the attribute at the given index. * @param index The index of the attribute. * @returns The location of the attribute. */ getAttributeLocation(index) { return this._attributes[index]; } /** * Returns the attribute based on the name of the variable. * @param name of the attribute to look up. * @returns the attribute location. */ getAttributeLocationByName(name260) { return this._attributeLocationByName[name260]; } /** * The number of attributes. * @returns the number of attributes. */ getAttributesCount() { return this._attributes.length; } /** * Gets the index of a uniform variable. * @param uniformName of the uniform to look up. * @returns the index. */ getUniformIndex(uniformName) { return this._uniformsNames.indexOf(uniformName); } /** * Returns the attribute based on the name of the variable. * @param uniformName of the uniform to look up. * @returns the location of the uniform. */ getUniform(uniformName) { return this._uniforms[uniformName]; } /** * Returns an array of sampler variable names * @returns The array of sampler variable names. */ getSamplers() { return this._samplerList; } /** * Returns an array of uniform variable names * @returns The array of uniform variable names. */ getUniformNames() { return this._uniformsNames; } /** * Returns an array of uniform buffer variable names * @returns The array of uniform buffer variable names. */ getUniformBuffersNames() { return this._uniformBuffersNamesList; } /** * Returns the index parameters used to create the effect * @returns The index parameters object */ getIndexParameters() { return this._indexParameters; } /** * The error from the last compilation. * @returns the error string. */ getCompilationError() { return this._compilationError; } /** * Gets a boolean indicating that all fallbacks were used during compilation * @returns true if all fallbacks were used */ allFallbacksProcessed() { return this._allFallbacksProcessed; } /** * Wait until compilation before fulfilling. * @returns a promise to wait for completion. */ async whenCompiledAsync() { return await new Promise((resolve) => { this.executeWhenCompiled(resolve); }); } /** * Adds a callback to the onCompiled observable and call the callback immediately if already ready. * @param func The callback to be used. */ executeWhenCompiled(func) { if (this.isReady()) { func(this); return; } this.onCompileObservable.add((effect) => { func(effect); }); if (!this._pipelineContext || this._pipelineContext.isAsync) { this._checkIsReady(null); } } _checkIsReady(previousPipelineContext) { _RetryWithInterval(() => { return this._isReadyInternal() || this._isDisposed; }, () => { }, (e) => { this._processCompilationErrors(e, previousPipelineContext); }, 16, 12e4, true, ` - Effect: ${typeof this.name === "string" ? this.name : this.key}`); } /** * Gets the vertex shader source code of this effect * This is the final source code that will be compiled, after all the processing has been done (pre-processing applied, code injection/replacement, etc) */ get vertexSourceCode() { return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? this._vertexSourceCodeOverride : this._pipelineContext?._getVertexShaderCode() ?? this._vertexSourceCode; } /** * Gets the fragment shader source code of this effect * This is the final source code that will be compiled, after all the processing has been done (pre-processing applied, code injection/replacement, etc) */ get fragmentSourceCode() { return this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride ? this._fragmentSourceCodeOverride : this._pipelineContext?._getFragmentShaderCode() ?? this._fragmentSourceCode; } /** * Gets the vertex shader source code before migration. * This is the source code after the include directives have been replaced by their contents but before the code is migrated, i.e. before ShaderProcess._ProcessShaderConversion is executed. * This method is, among other things, responsible for parsing #if/#define directives as well as converting GLES2 syntax to GLES3 (in the case of WebGL). */ get vertexSourceCodeBeforeMigration() { return this._vertexSourceCodeBeforeMigration; } /** * Gets the fragment shader source code before migration. * This is the source code after the include directives have been replaced by their contents but before the code is migrated, i.e. before ShaderProcess._ProcessShaderConversion is executed. * This method is, among other things, responsible for parsing #if/#define directives as well as converting GLES2 syntax to GLES3 (in the case of WebGL). */ get fragmentSourceCodeBeforeMigration() { return this._fragmentSourceCodeBeforeMigration; } /** * Gets the vertex shader source code before it has been modified by any processing */ get rawVertexSourceCode() { return this._rawVertexSourceCode; } /** * Gets the fragment shader source code before it has been modified by any processing */ get rawFragmentSourceCode() { return this._rawFragmentSourceCode; } getPipelineGenerationOptions() { return { platformName: this._engine.shaderPlatformName, shaderLanguage: this._shaderLanguage, shaderNameOrContent: this.name, key: this._key, defines: this.defines.split("\n"), addGlobalDefines: false, extendedProcessingOptions: { indexParameters: this._indexParameters, isNDCHalfZRange: this._engine.isNDCHalfZRange, useReverseDepthBuffer: this._engine.useReverseDepthBuffer, supportsUniformBuffers: this._engine.supportsUniformBuffers }, extendedCreatePipelineOptions: { transformFeedbackVaryings: this._transformFeedbackVaryings, createAsRaw: !!(this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) } }; } /** * Recompiles the webGL program * @param vertexSourceCode The source code for the vertex shader. * @param fragmentSourceCode The source code for the fragment shader. * @param onCompiled Callback called when completed. * @param onError Callback called on error. * @internal */ _rebuildProgram(vertexSourceCode, fragmentSourceCode, onCompiled, onError) { this._isReady = false; this._vertexSourceCodeOverride = vertexSourceCode; this._fragmentSourceCodeOverride = fragmentSourceCode; this.onError = (effect, error) => { if (onError) { onError(error); } }; this.onCompiled = () => { const scenes = this.getEngine().scenes; if (scenes) { for (let i = 0; i < scenes.length; i++) { scenes[i].markAllMaterialsAsDirty(127); } } this._pipelineContext._handlesSpectorRebuildCallback?.(onCompiled); }; this._fallbacks = null; this._prepareEffect(); } _onRenderingStateCompiled(pipelineContext) { this._pipelineContext = pipelineContext; this._pipelineContext.setEngine(this._engine); this._attributes = []; this._pipelineContext._fillEffectInformation(this, this._uniformBuffersNames, this._uniformsNames, this._uniforms, this._samplerList, this._samplers, this._attributesNames, this._attributes); if (this._attributesNames) { for (let i = 0; i < this._attributesNames.length; i++) { const name260 = this._attributesNames[i]; this._attributeLocationByName[name260] = this._attributes[i]; } } this._engine.bindSamplers(this); this._compilationError = ""; this._isReady = true; if (this.onCompiled) { this.onCompiled(this); } this.onCompileObservable.notifyObservers(this); this.onCompileObservable.clear(); if (this._fallbacks) { this._fallbacks.unBindMesh(); } if (_Effect.AutomaticallyClearCodeCache) { this.clearCodeCache(); } } /** * Prepares the effect * @internal */ _prepareEffect(keepExistingPipelineContext = false) { const previousPipelineContext = this._pipelineContext; this._isReady = false; try { const overrides = !!(this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride); const defines = overrides ? null : this.defines; const vertex = overrides ? this._vertexSourceCodeOverride : this._vertexSourceCode; const fragment = overrides ? this._fragmentSourceCodeOverride : this._fragmentSourceCode; const engine = this._engine; this._pipelineContext = createAndPreparePipelineContext({ existingPipelineContext: keepExistingPipelineContext ? previousPipelineContext : null, vertex, fragment, context: engine.shaderPlatformName === "WEBGL2" || engine.shaderPlatformName === "WEBGL1" ? engine._gl : void 0, rebuildRebind: /* @__PURE__ */ __name((vertexSourceCode, fragmentSourceCode, onCompiled, onError) => this._rebuildProgram(vertexSourceCode, fragmentSourceCode, onCompiled, onError), "rebuildRebind"), defines, transformFeedbackVaryings: this._transformFeedbackVaryings, name: this._key.replace(/\r/g, "").replace(/\n/g, "|"), createAsRaw: overrides, disableParallelCompilation: this._disableParallelShaderCompilation, shaderProcessingContext: this._processingContext, onRenderingStateCompiled: /* @__PURE__ */ __name((pipelineContext) => { if (previousPipelineContext && !keepExistingPipelineContext) { this._engine._deletePipelineContext(previousPipelineContext); } if (pipelineContext) { this._onRenderingStateCompiled(pipelineContext); } }, "onRenderingStateCompiled") }, this._engine.createPipelineContext.bind(this._engine), this._engine._preparePipelineContextAsync.bind(this._engine), this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)); if (this._pipelineContext.isAsync) { this._checkIsReady(previousPipelineContext); } } catch (e) { this._processCompilationErrors(e, previousPipelineContext); } } _getShaderCodeAndErrorLine(code, error, isFragment) { const regexp = isFragment ? /FRAGMENT SHADER ERROR: 0:(\d+?):/ : /VERTEX SHADER ERROR: 0:(\d+?):/; let errorLine = null; if (error && code) { const res = error.match(regexp); if (res && res.length === 2) { const lineNumber = parseInt(res[1]); const lines = code.split("\n", -1); if (lines.length >= lineNumber) { errorLine = `Offending line [${lineNumber}] in ${isFragment ? "fragment" : "vertex"} code: ${lines[lineNumber - 1]}`; } } } return [code, errorLine]; } _processCompilationErrors(e, previousPipelineContext = null) { this._compilationError = e.message; const attributesNames = this._attributesNames; const fallbacks = this._fallbacks; Logger.Error("Unable to compile effect:"); Logger.Error(`Uniforms: ${this._uniformsNames.join(" ")}`); Logger.Error(`Attributes: ${attributesNames.join(" ")}`); Logger.Error("Defines:\n" + this.defines); if (_Effect.LogShaderCodeOnCompilationError) { let lineErrorVertex = null, lineErrorFragment = null, code = null; if (this._pipelineContext?._getVertexShaderCode()) { [code, lineErrorVertex] = this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(), this._compilationError, false); if (code) { Logger.Error("Vertex code:"); Logger.Error(code); } } if (this._pipelineContext?._getFragmentShaderCode()) { [code, lineErrorFragment] = this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(), this._compilationError, true); if (code) { Logger.Error("Fragment code:"); Logger.Error(code); } } if (lineErrorVertex) { Logger.Error(lineErrorVertex); } if (lineErrorFragment) { Logger.Error(lineErrorFragment); } } Logger.Error("Error: " + this._compilationError); const notifyErrors = /* @__PURE__ */ __name(() => { if (this.onError) { this.onError(this, this._compilationError); } this.onErrorObservable.notifyObservers(this); this._engine.onEffectErrorObservable.notifyObservers({ effect: this, errors: this._compilationError }); }, "notifyErrors"); if (previousPipelineContext) { this._pipelineContext = previousPipelineContext; this._isReady = true; notifyErrors(); } if (fallbacks) { this._pipelineContext = null; if (fallbacks.hasMoreFallbacks) { this._allFallbacksProcessed = false; Logger.Error("Trying next fallback."); this.defines = fallbacks.reduce(this.defines, this); this._prepareEffect(); } else { this._allFallbacksProcessed = true; notifyErrors(); this.onErrorObservable.clear(); if (this._fallbacks) { this._fallbacks.unBindMesh(); } } } else { this._allFallbacksProcessed = true; if (!previousPipelineContext) { notifyErrors(); } } } /** * Checks if the effect is supported. (Must be called after compilation) */ get isSupported() { return this._compilationError === ""; } /** * Binds a texture to the engine to be used as output of the shader. * @param channel Name of the output variable. * @param texture Texture to bind. * @internal */ _bindTexture(channel, texture) { this._engine._bindTexture(this._samplers[channel], texture, channel); } /** * Sets a texture on the engine to be used in the shader. * @param channel Name of the sampler variable. * @param texture Texture to set. */ setTexture(channel, texture) { this._engine.setTexture(this._samplers[channel], this._uniforms[channel], texture, channel); } /** * Sets an array of textures on the engine to be used in the shader. * @param channel Name of the variable. * @param textures Textures to set. */ setTextureArray(channel, textures) { const exName = channel + "Ex"; if (this._samplerList.indexOf(exName + "0") === -1) { const initialPos = this._samplerList.indexOf(channel); for (let index = 1; index < textures.length; index++) { const currentExName = exName + (index - 1).toString(); this._samplerList.splice(initialPos + index, 0, currentExName); } let channelIndex = 0; for (const key of this._samplerList) { this._samplers[key] = channelIndex; channelIndex += 1; } } this._engine.setTextureArray(this._samplers[channel], this._uniforms[channel], textures, channel); } /** * Binds a buffer to a uniform. * @param buffer Buffer to bind. * @param name Name of the uniform variable to bind to. */ bindUniformBuffer(buffer, name260) { const bufferName = this._uniformBuffersNames[name260]; if (bufferName === void 0 || _Effect._BaseCache[bufferName] === buffer && this._engine._features.useUBOBindingCache) { return; } _Effect._BaseCache[bufferName] = buffer; this._engine.bindUniformBufferBase(buffer, bufferName, name260); } /** * Binds block to a uniform. * @param blockName Name of the block to bind. * @param index Index to bind. */ bindUniformBlock(blockName, index) { this._engine.bindUniformBlock(this._pipelineContext, blockName, index); } /** * Sets an integer value on a uniform variable. * @param uniformName Name of the variable. * @param value Value to be set. * @returns this effect. */ setInt(uniformName, value) { this._pipelineContext.setInt(uniformName, value); return this; } /** * Sets an int2 value on a uniform variable. * @param uniformName Name of the variable. * @param x First int in int2. * @param y Second int in int2. * @returns this effect. */ setInt2(uniformName, x, y) { this._pipelineContext.setInt2(uniformName, x, y); return this; } /** * Sets an int3 value on a uniform variable. * @param uniformName Name of the variable. * @param x First int in int3. * @param y Second int in int3. * @param z Third int in int3. * @returns this effect. */ setInt3(uniformName, x, y, z) { this._pipelineContext.setInt3(uniformName, x, y, z); return this; } /** * Sets an int4 value on a uniform variable. * @param uniformName Name of the variable. * @param x First int in int4. * @param y Second int in int4. * @param z Third int in int4. * @param w Fourth int in int4. * @returns this effect. */ setInt4(uniformName, x, y, z, w) { this._pipelineContext.setInt4(uniformName, x, y, z, w); return this; } /** * Sets an int array on a uniform variable. * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setIntArray(uniformName, array) { this._pipelineContext.setIntArray(uniformName, array); return this; } /** * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setIntArray2(uniformName, array) { this._pipelineContext.setIntArray2(uniformName, array); return this; } /** * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setIntArray3(uniformName, array) { this._pipelineContext.setIntArray3(uniformName, array); return this; } /** * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setIntArray4(uniformName, array) { this._pipelineContext.setIntArray4(uniformName, array); return this; } /** * Sets an unsigned integer value on a uniform variable. * @param uniformName Name of the variable. * @param value Value to be set. * @returns this effect. */ setUInt(uniformName, value) { this._pipelineContext.setUInt(uniformName, value); return this; } /** * Sets an unsigned int2 value on a uniform variable. * @param uniformName Name of the variable. * @param x First unsigned int in uint2. * @param y Second unsigned int in uint2. * @returns this effect. */ setUInt2(uniformName, x, y) { this._pipelineContext.setUInt2(uniformName, x, y); return this; } /** * Sets an unsigned int3 value on a uniform variable. * @param uniformName Name of the variable. * @param x First unsigned int in uint3. * @param y Second unsigned int in uint3. * @param z Third unsigned int in uint3. * @returns this effect. */ setUInt3(uniformName, x, y, z) { this._pipelineContext.setUInt3(uniformName, x, y, z); return this; } /** * Sets an unsigned int4 value on a uniform variable. * @param uniformName Name of the variable. * @param x First unsigned int in uint4. * @param y Second unsigned int in uint4. * @param z Third unsigned int in uint4. * @param w Fourth unsigned int in uint4. * @returns this effect. */ setUInt4(uniformName, x, y, z, w) { this._pipelineContext.setUInt4(uniformName, x, y, z, w); return this; } /** * Sets an unsigned int array on a uniform variable. * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setUIntArray(uniformName, array) { this._pipelineContext.setUIntArray(uniformName, array); return this; } /** * Sets an unsigned int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setUIntArray2(uniformName, array) { this._pipelineContext.setUIntArray2(uniformName, array); return this; } /** * Sets an unsigned int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setUIntArray3(uniformName, array) { this._pipelineContext.setUIntArray3(uniformName, array); return this; } /** * Sets an unsigned int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setUIntArray4(uniformName, array) { this._pipelineContext.setUIntArray4(uniformName, array); return this; } /** * Sets an float array on a uniform variable. * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setFloatArray(uniformName, array) { this._pipelineContext.setArray(uniformName, array); return this; } /** * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setFloatArray2(uniformName, array) { this._pipelineContext.setArray2(uniformName, array); return this; } /** * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setFloatArray3(uniformName, array) { this._pipelineContext.setArray3(uniformName, array); return this; } /** * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setFloatArray4(uniformName, array) { this._pipelineContext.setArray4(uniformName, array); return this; } /** * Sets an array on a uniform variable. * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setArray(uniformName, array) { this._pipelineContext.setArray(uniformName, array); return this; } /** * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setArray2(uniformName, array) { this._pipelineContext.setArray2(uniformName, array); return this; } /** * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setArray3(uniformName, array) { this._pipelineContext.setArray3(uniformName, array); return this; } /** * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader) * @param uniformName Name of the variable. * @param array array to be set. * @returns this effect. */ setArray4(uniformName, array) { this._pipelineContext.setArray4(uniformName, array); return this; } /** * Sets matrices on a uniform variable. * @param uniformName Name of the variable. * @param matrices matrices to be set. * @returns this effect. */ setMatrices(uniformName, matrices) { this._pipelineContext.setMatrices(uniformName, matrices); return this; } /** * Sets matrix on a uniform variable. * @param uniformName Name of the variable. * @param matrix matrix to be set. * @returns this effect. */ setMatrix(uniformName, matrix) { this._pipelineContext.setMatrix(uniformName, matrix); return this; } /** * Sets a 3x3 matrix on a uniform variable. (Specified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix) * @param uniformName Name of the variable. * @param matrix matrix to be set. * @returns this effect. */ setMatrix3x3(uniformName, matrix) { this._pipelineContext.setMatrix3x3(uniformName, matrix); return this; } /** * Sets a 2x2 matrix on a uniform variable. (Specified as [1,2,3,4] will result in [1,2][3,4] matrix) * @param uniformName Name of the variable. * @param matrix matrix to be set. * @returns this effect. */ setMatrix2x2(uniformName, matrix) { this._pipelineContext.setMatrix2x2(uniformName, matrix); return this; } /** * Sets a float on a uniform variable. * @param uniformName Name of the variable. * @param value value to be set. * @returns this effect. */ setFloat(uniformName, value) { this._pipelineContext.setFloat(uniformName, value); return this; } /** * Sets a boolean on a uniform variable. * @param uniformName Name of the variable. * @param bool value to be set. * @returns this effect. */ setBool(uniformName, bool) { this._pipelineContext.setInt(uniformName, bool ? 1 : 0); return this; } /** * Sets a Vector2 on a uniform variable. * @param uniformName Name of the variable. * @param vector2 vector2 to be set. * @returns this effect. */ setVector2(uniformName, vector2) { this._pipelineContext.setVector2(uniformName, vector2); return this; } /** * Sets a float2 on a uniform variable. * @param uniformName Name of the variable. * @param x First float in float2. * @param y Second float in float2. * @returns this effect. */ setFloat2(uniformName, x, y) { this._pipelineContext.setFloat2(uniformName, x, y); return this; } /** * Sets a Vector3 on a uniform variable. * @param uniformName Name of the variable. * @param vector3 Value to be set. * @returns this effect. */ setVector3(uniformName, vector3) { this._pipelineContext.setVector3(uniformName, vector3); return this; } /** * Sets a float3 on a uniform variable. * @param uniformName Name of the variable. * @param x First float in float3. * @param y Second float in float3. * @param z Third float in float3. * @returns this effect. */ setFloat3(uniformName, x, y, z) { this._pipelineContext.setFloat3(uniformName, x, y, z); return this; } /** * Sets a Vector4 on a uniform variable. * @param uniformName Name of the variable. * @param vector4 Value to be set. * @returns this effect. */ setVector4(uniformName, vector4) { this._pipelineContext.setVector4(uniformName, vector4); return this; } /** * Sets a Quaternion on a uniform variable. * @param uniformName Name of the variable. * @param quaternion Value to be set. * @returns this effect. */ setQuaternion(uniformName, quaternion) { this._pipelineContext.setQuaternion(uniformName, quaternion); return this; } /** * Sets a float4 on a uniform variable. * @param uniformName Name of the variable. * @param x First float in float4. * @param y Second float in float4. * @param z Third float in float4. * @param w Fourth float in float4. * @returns this effect. */ setFloat4(uniformName, x, y, z, w) { this._pipelineContext.setFloat4(uniformName, x, y, z, w); return this; } /** * Sets a Color3 on a uniform variable. * @param uniformName Name of the variable. * @param color3 Value to be set. * @returns this effect. */ setColor3(uniformName, color3) { this._pipelineContext.setColor3(uniformName, color3); return this; } /** * Sets a Color4 on a uniform variable. * @param uniformName Name of the variable. * @param color3 Value to be set. * @param alpha Alpha value to be set. * @returns this effect. */ setColor4(uniformName, color3, alpha) { this._pipelineContext.setColor4(uniformName, color3, alpha); return this; } /** * Sets a Color4 on a uniform variable * @param uniformName defines the name of the variable * @param color4 defines the value to be set * @returns this effect. */ setDirectColor4(uniformName, color4) { this._pipelineContext.setDirectColor4(uniformName, color4); return this; } /** * Use this wisely: It will remove the cached code from this effect * It is probably ok to call it if you are not using ShadowDepthWrapper or if everything is already up and running * DO NOT CALL IT if you want to have support for context lost recovery */ clearCodeCache() { this._vertexSourceCode = ""; this._fragmentSourceCode = ""; this._fragmentSourceCodeBeforeMigration = ""; this._vertexSourceCodeBeforeMigration = ""; } /** * Release all associated resources. * @param force specifies if the effect must be released no matter what **/ dispose(force = false) { if (force) { this._refCount = 0; } else { if (_Effect.PersistentMode) { return; } this._refCount--; } if (this._refCount > 0 || this._isDisposed) { return; } if (this._onReleaseEffectsObserver) { this._engine.onReleaseEffectsObservable.remove(this._onReleaseEffectsObserver); this._onReleaseEffectsObserver = null; } if (this._pipelineContext) { resetCachedPipeline(this._pipelineContext); } this._engine._releaseEffect(this); this.clearCodeCache(); this._isDisposed = true; } /** * This function will add a new shader to the shader store * @param name the name of the shader * @param pixelShader optional pixel shader content * @param vertexShader optional vertex shader content * @param shaderLanguage the language the shader is written in (default: GLSL) */ static RegisterShader(name260, pixelShader, vertexShader, shaderLanguage = 0) { if (pixelShader) { ShaderStore.GetShadersStore(shaderLanguage)[`${name260}PixelShader`] = pixelShader; } if (vertexShader) { ShaderStore.GetShadersStore(shaderLanguage)[`${name260}VertexShader`] = vertexShader; } } /** * Resets the cache of effects. */ static ResetCache() { _Effect._BaseCache = {}; } }; Effect.LogShaderCodeOnCompilationError = true; Effect.PersistentMode = false; Effect.AutomaticallyClearCodeCache = false; Effect._UniqueIdSeed = 0; Effect._BaseCache = {}; Effect.ShadersStore = ShaderStore.ShadersStore; Effect.IncludesShadersStore = ShaderStore.IncludesShadersStore; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/depthCullingState.js var DepthCullingState; var init_depthCullingState = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/depthCullingState.js"() { DepthCullingState = class { static { __name(this, "DepthCullingState"); } /** * Initializes the state. * @param reset */ constructor(reset = true) { this._isDepthTestDirty = false; this._isDepthMaskDirty = false; this._isDepthFuncDirty = false; this._isCullFaceDirty = false; this._isCullDirty = false; this._isZOffsetDirty = false; this._isFrontFaceDirty = false; if (reset) { this.reset(); } } get isDirty() { return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty; } get zOffset() { return this._zOffset; } set zOffset(value) { if (this._zOffset === value) { return; } this._zOffset = value; this._isZOffsetDirty = true; } get zOffsetUnits() { return this._zOffsetUnits; } set zOffsetUnits(value) { if (this._zOffsetUnits === value) { return; } this._zOffsetUnits = value; this._isZOffsetDirty = true; } get cullFace() { return this._cullFace; } set cullFace(value) { if (this._cullFace === value) { return; } this._cullFace = value; this._isCullFaceDirty = true; } get cull() { return this._cull; } set cull(value) { if (this._cull === value) { return; } this._cull = value; this._isCullDirty = true; } get depthFunc() { return this._depthFunc; } set depthFunc(value) { if (this._depthFunc === value) { return; } this._depthFunc = value; this._isDepthFuncDirty = true; } get depthMask() { return this._depthMask; } set depthMask(value) { if (this._depthMask === value) { return; } this._depthMask = value; this._isDepthMaskDirty = true; } get depthTest() { return this._depthTest; } set depthTest(value) { if (this._depthTest === value) { return; } this._depthTest = value; this._isDepthTestDirty = true; } get frontFace() { return this._frontFace; } set frontFace(value) { if (this._frontFace === value) { return; } this._frontFace = value; this._isFrontFaceDirty = true; } reset() { this._depthMask = true; this._depthTest = true; this._depthFunc = null; this._cullFace = null; this._cull = null; this._zOffset = 0; this._zOffsetUnits = 0; this._frontFace = null; this._isDepthTestDirty = true; this._isDepthMaskDirty = true; this._isDepthFuncDirty = false; this._isCullFaceDirty = false; this._isCullDirty = false; this._isZOffsetDirty = true; this._isFrontFaceDirty = false; } apply(gl) { if (!this.isDirty) { return; } if (this._isCullDirty) { if (this.cull) { gl.enable(gl.CULL_FACE); } else { gl.disable(gl.CULL_FACE); } this._isCullDirty = false; } if (this._isCullFaceDirty) { gl.cullFace(this.cullFace); this._isCullFaceDirty = false; } if (this._isDepthMaskDirty) { gl.depthMask(this.depthMask); this._isDepthMaskDirty = false; } if (this._isDepthTestDirty) { if (this.depthTest) { gl.enable(gl.DEPTH_TEST); } else { gl.disable(gl.DEPTH_TEST); } this._isDepthTestDirty = false; } if (this._isDepthFuncDirty) { gl.depthFunc(this.depthFunc); this._isDepthFuncDirty = false; } if (this._isZOffsetDirty) { if (this.zOffset || this.zOffsetUnits) { gl.enable(gl.POLYGON_OFFSET_FILL); gl.polygonOffset(this.zOffset, this.zOffsetUnits); } else { gl.disable(gl.POLYGON_OFFSET_FILL); } this._isZOffsetDirty = false; } if (this._isFrontFaceDirty) { gl.frontFace(this.frontFace); this._isFrontFaceDirty = false; } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/stencilStateComposer.js var StencilStateComposer; var init_stencilStateComposer = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/stencilStateComposer.js"() { StencilStateComposer = class { static { __name(this, "StencilStateComposer"); } get isDirty() { return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty; } get func() { return this._func; } set func(value) { if (this._func === value) { return; } this._func = value; this._isStencilFuncDirty = true; } get backFunc() { return this._func; } set backFunc(value) { if (this._backFunc === value) { return; } this._backFunc = value; this._isStencilFuncDirty = true; } get funcRef() { return this._funcRef; } set funcRef(value) { if (this._funcRef === value) { return; } this._funcRef = value; this._isStencilFuncDirty = true; } get funcMask() { return this._funcMask; } set funcMask(value) { if (this._funcMask === value) { return; } this._funcMask = value; this._isStencilFuncDirty = true; } get opStencilFail() { return this._opStencilFail; } set opStencilFail(value) { if (this._opStencilFail === value) { return; } this._opStencilFail = value; this._isStencilOpDirty = true; } get opDepthFail() { return this._opDepthFail; } set opDepthFail(value) { if (this._opDepthFail === value) { return; } this._opDepthFail = value; this._isStencilOpDirty = true; } get opStencilDepthPass() { return this._opStencilDepthPass; } set opStencilDepthPass(value) { if (this._opStencilDepthPass === value) { return; } this._opStencilDepthPass = value; this._isStencilOpDirty = true; } get backOpStencilFail() { return this._backOpStencilFail; } set backOpStencilFail(value) { if (this._backOpStencilFail === value) { return; } this._backOpStencilFail = value; this._isStencilOpDirty = true; } get backOpDepthFail() { return this._backOpDepthFail; } set backOpDepthFail(value) { if (this._backOpDepthFail === value) { return; } this._backOpDepthFail = value; this._isStencilOpDirty = true; } get backOpStencilDepthPass() { return this._backOpStencilDepthPass; } set backOpStencilDepthPass(value) { if (this._backOpStencilDepthPass === value) { return; } this._backOpStencilDepthPass = value; this._isStencilOpDirty = true; } get mask() { return this._mask; } set mask(value) { if (this._mask === value) { return; } this._mask = value; this._isStencilMaskDirty = true; } get enabled() { return this._enabled; } set enabled(value) { if (this._enabled === value) { return; } this._enabled = value; this._isStencilTestDirty = true; } constructor(reset = true) { this._isStencilTestDirty = false; this._isStencilMaskDirty = false; this._isStencilFuncDirty = false; this._isStencilOpDirty = false; this.useStencilGlobalOnly = false; if (reset) { this.reset(); } } reset() { this.stencilMaterial = void 0; this.stencilGlobal?.reset(); this._isStencilTestDirty = true; this._isStencilMaskDirty = true; this._isStencilFuncDirty = true; this._isStencilOpDirty = true; } apply(gl) { if (!gl) { return; } const stencilMaterialEnabled = !this.useStencilGlobalOnly && !!this.stencilMaterial?.enabled; this.enabled = stencilMaterialEnabled ? this.stencilMaterial.enabled : this.stencilGlobal.enabled; this.func = stencilMaterialEnabled ? this.stencilMaterial.func : this.stencilGlobal.func; this.backFunc = stencilMaterialEnabled ? this.stencilMaterial.backFunc : this.stencilGlobal.backFunc; this.funcRef = stencilMaterialEnabled ? this.stencilMaterial.funcRef : this.stencilGlobal.funcRef; this.funcMask = stencilMaterialEnabled ? this.stencilMaterial.funcMask : this.stencilGlobal.funcMask; this.opStencilFail = stencilMaterialEnabled ? this.stencilMaterial.opStencilFail : this.stencilGlobal.opStencilFail; this.opDepthFail = stencilMaterialEnabled ? this.stencilMaterial.opDepthFail : this.stencilGlobal.opDepthFail; this.opStencilDepthPass = stencilMaterialEnabled ? this.stencilMaterial.opStencilDepthPass : this.stencilGlobal.opStencilDepthPass; this.backOpStencilFail = stencilMaterialEnabled ? this.stencilMaterial.backOpStencilFail : this.stencilGlobal.backOpStencilFail; this.backOpDepthFail = stencilMaterialEnabled ? this.stencilMaterial.backOpDepthFail : this.stencilGlobal.backOpDepthFail; this.backOpStencilDepthPass = stencilMaterialEnabled ? this.stencilMaterial.backOpStencilDepthPass : this.stencilGlobal.backOpStencilDepthPass; this.mask = stencilMaterialEnabled ? this.stencilMaterial.mask : this.stencilGlobal.mask; if (!this.isDirty) { return; } if (this._isStencilTestDirty) { if (this.enabled) { gl.enable(gl.STENCIL_TEST); } else { gl.disable(gl.STENCIL_TEST); } this._isStencilTestDirty = false; } if (this._isStencilMaskDirty) { gl.stencilMask(this.mask); this._isStencilMaskDirty = false; } if (this._isStencilFuncDirty) { gl.stencilFuncSeparate(gl.FRONT, this.func, this.funcRef, this.funcMask); gl.stencilFuncSeparate(gl.BACK, this.backFunc, this.funcRef, this.funcMask); this._isStencilFuncDirty = false; } if (this._isStencilOpDirty) { gl.stencilOpSeparate(gl.FRONT, this.opStencilFail, this.opDepthFail, this.opStencilDepthPass); gl.stencilOpSeparate(gl.BACK, this.backOpStencilFail, this.backOpDepthFail, this.backOpStencilDepthPass); this._isStencilOpDirty = false; } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/stencilState.js var StencilState; var init_stencilState = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/stencilState.js"() { StencilState = class _StencilState { static { __name(this, "StencilState"); } constructor() { this.reset(); } reset() { this.enabled = false; this.mask = 255; this.funcRef = 1; this.funcMask = 255; this.func = _StencilState.ALWAYS; this.opStencilFail = _StencilState.KEEP; this.opDepthFail = _StencilState.KEEP; this.opStencilDepthPass = _StencilState.REPLACE; this.backFunc = _StencilState.ALWAYS; this.backOpStencilFail = _StencilState.KEEP; this.backOpDepthFail = _StencilState.KEEP; this.backOpStencilDepthPass = _StencilState.REPLACE; } get stencilFunc() { return this.func; } set stencilFunc(value) { this.func = value; } get stencilBackFunc() { return this.backFunc; } set stencilBackFunc(value) { this.backFunc = value; } get stencilFuncRef() { return this.funcRef; } set stencilFuncRef(value) { this.funcRef = value; } get stencilFuncMask() { return this.funcMask; } set stencilFuncMask(value) { this.funcMask = value; } get stencilOpStencilFail() { return this.opStencilFail; } set stencilOpStencilFail(value) { this.opStencilFail = value; } get stencilOpDepthFail() { return this.opDepthFail; } set stencilOpDepthFail(value) { this.opDepthFail = value; } get stencilOpStencilDepthPass() { return this.opStencilDepthPass; } set stencilOpStencilDepthPass(value) { this.opStencilDepthPass = value; } get stencilBackOpStencilFail() { return this.backOpStencilFail; } set stencilBackOpStencilFail(value) { this.backOpStencilFail = value; } get stencilBackOpDepthFail() { return this.backOpDepthFail; } set stencilBackOpDepthFail(value) { this.backOpDepthFail = value; } get stencilBackOpStencilDepthPass() { return this.backOpStencilDepthPass; } set stencilBackOpStencilDepthPass(value) { this.backOpStencilDepthPass = value; } get stencilMask() { return this.mask; } set stencilMask(value) { this.mask = value; } get stencilTest() { return this.enabled; } set stencilTest(value) { this.enabled = value; } }; StencilState.ALWAYS = 519; StencilState.KEEP = 7680; StencilState.REPLACE = 7681; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/alphaCullingState.js var AlphaState; var init_alphaCullingState = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/States/alphaCullingState.js"() { AlphaState = class { static { __name(this, "AlphaState"); } /** * Initializes the state. * @param _supportBlendParametersPerTarget - Whether blend parameters per target is supported */ constructor(_supportBlendParametersPerTarget) { this._supportBlendParametersPerTarget = _supportBlendParametersPerTarget; this._blendFunctionParameters = new Array(4 * 8); this._blendEquationParameters = new Array(2 * 8); this._blendConstants = new Array(4); this._isBlendConstantsDirty = false; this._alphaBlend = Array(8).fill(false); this._numTargetEnabled = 0; this._isAlphaBlendDirty = false; this._isBlendFunctionParametersDirty = false; this._isBlendEquationParametersDirty = false; this.reset(); } get isDirty() { return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty || this._isBlendEquationParametersDirty; } get alphaBlend() { return this._numTargetEnabled > 0; } setAlphaBlend(value, targetIndex = 0) { if (this._alphaBlend[targetIndex] === value) { return; } if (value) { this._numTargetEnabled++; } else { this._numTargetEnabled--; } this._alphaBlend[targetIndex] = value; this._isAlphaBlendDirty = true; } setAlphaBlendConstants(r, g, b, a) { if (this._blendConstants[0] === r && this._blendConstants[1] === g && this._blendConstants[2] === b && this._blendConstants[3] === a) { return; } this._blendConstants[0] = r; this._blendConstants[1] = g; this._blendConstants[2] = b; this._blendConstants[3] = a; this._isBlendConstantsDirty = true; } setAlphaBlendFunctionParameters(srcRGBFactor, dstRGBFactor, srcAlphaFactor, dstAlphaFactor, targetIndex = 0) { const offset = targetIndex * 4; if (this._blendFunctionParameters[offset + 0] === srcRGBFactor && this._blendFunctionParameters[offset + 1] === dstRGBFactor && this._blendFunctionParameters[offset + 2] === srcAlphaFactor && this._blendFunctionParameters[offset + 3] === dstAlphaFactor) { return; } this._blendFunctionParameters[offset + 0] = srcRGBFactor; this._blendFunctionParameters[offset + 1] = dstRGBFactor; this._blendFunctionParameters[offset + 2] = srcAlphaFactor; this._blendFunctionParameters[offset + 3] = dstAlphaFactor; this._isBlendFunctionParametersDirty = true; } setAlphaEquationParameters(rgbEquation, alphaEquation, targetIndex = 0) { const offset = targetIndex * 2; if (this._blendEquationParameters[offset + 0] === rgbEquation && this._blendEquationParameters[offset + 1] === alphaEquation) { return; } this._blendEquationParameters[offset + 0] = rgbEquation; this._blendEquationParameters[offset + 1] = alphaEquation; this._isBlendEquationParametersDirty = true; } reset() { this._alphaBlend.fill(false); this._numTargetEnabled = 0; this._blendFunctionParameters.fill(null); this._blendEquationParameters.fill(null); this._blendConstants[0] = null; this._blendConstants[1] = null; this._blendConstants[2] = null; this._blendConstants[3] = null; this._isAlphaBlendDirty = true; this._isBlendFunctionParametersDirty = false; this._isBlendEquationParametersDirty = false; this._isBlendConstantsDirty = false; } apply(gl, numTargets = 1) { if (!this.isDirty) { return; } if (this._isBlendConstantsDirty) { gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]); this._isBlendConstantsDirty = false; } if (numTargets === 1 || !this._supportBlendParametersPerTarget) { if (this._isAlphaBlendDirty) { if (this._alphaBlend[0]) { gl.enable(gl.BLEND); } else { gl.disable(gl.BLEND); } this._isAlphaBlendDirty = false; } if (this._isBlendFunctionParametersDirty) { gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]); this._isBlendFunctionParametersDirty = false; } if (this._isBlendEquationParametersDirty) { gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]); this._isBlendEquationParametersDirty = false; } return; } const gl2 = gl; if (this._isAlphaBlendDirty) { for (let i = 0; i < numTargets; i++) { const index = i < this._numTargetEnabled ? i : 0; if (this._alphaBlend[index]) { gl2.enableIndexed(gl.BLEND, i); } else { gl2.disableIndexed(gl.BLEND, i); } } this._isAlphaBlendDirty = false; } if (this._isBlendFunctionParametersDirty) { for (let i = 0; i < numTargets; i++) { const offset = i < this._numTargetEnabled ? i * 4 : 0; gl2.blendFuncSeparateIndexed(i, this._blendFunctionParameters[offset + 0], this._blendFunctionParameters[offset + 1], this._blendFunctionParameters[offset + 2], this._blendFunctionParameters[offset + 3]); } this._isBlendFunctionParametersDirty = false; } if (this._isBlendEquationParametersDirty) { for (let i = 0; i < numTargets; i++) { const offset = i < this._numTargetEnabled ? i * 2 : 0; gl2.blendEquationSeparateIndexed(i, this._blendEquationParameters[offset + 0], this._blendEquationParameters[offset + 1]); } this._isBlendEquationParametersDirty = false; } } setAlphaMode(mode, targetIndex) { let equation = 32774; switch (mode) { case 0: break; case 7: this.setAlphaBlendFunctionParameters(1, 771, 1, 1, targetIndex); break; case 8: this.setAlphaBlendFunctionParameters(1, 771, 1, 771, targetIndex); break; case 2: this.setAlphaBlendFunctionParameters(770, 771, 1, 1, targetIndex); break; case 6: this.setAlphaBlendFunctionParameters(1, 1, 0, 1, targetIndex); break; case 1: this.setAlphaBlendFunctionParameters(770, 1, 0, 1, targetIndex); break; case 3: this.setAlphaBlendFunctionParameters(0, 769, 1, 1, targetIndex); equation = 32778; break; case 4: this.setAlphaBlendFunctionParameters(774, 0, 1, 1, targetIndex); break; case 5: this.setAlphaBlendFunctionParameters(770, 769, 1, 1, targetIndex); break; case 9: this.setAlphaBlendFunctionParameters(32769, 32770, 32771, 32772, targetIndex); break; case 10: this.setAlphaBlendFunctionParameters(1, 769, 1, 771, targetIndex); break; case 11: this.setAlphaBlendFunctionParameters(1, 1, 1, 1, targetIndex); break; case 12: this.setAlphaBlendFunctionParameters(772, 1, 0, 0, targetIndex); break; case 13: this.setAlphaBlendFunctionParameters(775, 769, 773, 771, targetIndex); break; case 14: this.setAlphaBlendFunctionParameters(1, 771, 1, 771, targetIndex); break; case 15: this.setAlphaBlendFunctionParameters(1, 1, 1, 0, targetIndex); break; case 16: this.setAlphaBlendFunctionParameters(775, 769, 0, 1, targetIndex); break; case 17: this.setAlphaBlendFunctionParameters(770, 771, 1, 771, targetIndex); break; case 18: this.setAlphaBlendFunctionParameters(1, 1, 1, 1, targetIndex); equation = 32775; break; case 19: this.setAlphaBlendFunctionParameters(1, 1, 1, 1, targetIndex); equation = 32776; break; case 20: this.setAlphaBlendFunctionParameters(1, 35065, 0, 1, targetIndex); break; } this.setAlphaEquationParameters(equation, equation, targetIndex); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/textureSampler.js var TextureSampler; var init_textureSampler = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/textureSampler.js"() { TextureSampler = class { static { __name(this, "TextureSampler"); } /** * | Value | Type | Description | * | ----- | ------------------ | ----------- | * | 0 | CLAMP_ADDRESSMODE | | * | 1 | WRAP_ADDRESSMODE | | * | 2 | MIRROR_ADDRESSMODE | | */ get wrapU() { return this._cachedWrapU; } set wrapU(value) { this._cachedWrapU = value; } /** * | Value | Type | Description | * | ----- | ------------------ | ----------- | * | 0 | CLAMP_ADDRESSMODE | | * | 1 | WRAP_ADDRESSMODE | | * | 2 | MIRROR_ADDRESSMODE | | */ get wrapV() { return this._cachedWrapV; } set wrapV(value) { this._cachedWrapV = value; } /** * | Value | Type | Description | * | ----- | ------------------ | ----------- | * | 0 | CLAMP_ADDRESSMODE | | * | 1 | WRAP_ADDRESSMODE | | * | 2 | MIRROR_ADDRESSMODE | | */ get wrapR() { return this._cachedWrapR; } set wrapR(value) { this._cachedWrapR = value; } /** * With compliant hardware and browser (supporting anisotropic filtering) * this defines the level of anisotropic filtering in the texture. * The higher the better but the slower. */ get anisotropicFilteringLevel() { return this._cachedAnisotropicFilteringLevel; } set anisotropicFilteringLevel(value) { this._cachedAnisotropicFilteringLevel = value; } /** * Gets or sets the comparison function (513, 514, etc). Set 0 to not use a comparison function */ get comparisonFunction() { return this._comparisonFunction; } set comparisonFunction(value) { this._comparisonFunction = value; } /** * Indicates to use the mip maps (if available on the texture). * Thanks to this flag, you can instruct the sampler to not sample the mipmaps even if they exist (and if the sampling mode is set to a value that normally samples the mipmaps!) */ get useMipMaps() { return this._useMipMaps; } set useMipMaps(value) { this._useMipMaps = value; } /** * Creates a Sampler instance */ constructor() { this.samplingMode = -1; this._useMipMaps = true; this._cachedWrapU = null; this._cachedWrapV = null; this._cachedWrapR = null; this._cachedAnisotropicFilteringLevel = null; this._comparisonFunction = 0; } /** * Sets all the parameters of the sampler * @param wrapU u address mode (default: TEXTURE_WRAP_ADDRESSMODE) * @param wrapV v address mode (default: TEXTURE_WRAP_ADDRESSMODE) * @param wrapR r address mode (default: TEXTURE_WRAP_ADDRESSMODE) * @param anisotropicFilteringLevel anisotropic level (default: 1) * @param samplingMode sampling mode (default: 2) * @param comparisonFunction comparison function (default: 0 - no comparison function) * @returns the current sampler instance */ setParameters(wrapU = 1, wrapV = 1, wrapR = 1, anisotropicFilteringLevel = 1, samplingMode = 2, comparisonFunction = 0) { this._cachedWrapU = wrapU; this._cachedWrapV = wrapV; this._cachedWrapR = wrapR; this._cachedAnisotropicFilteringLevel = anisotropicFilteringLevel; this.samplingMode = samplingMode; this._comparisonFunction = comparisonFunction; return this; } /** * Compares this sampler with another one * @param other sampler to compare with * @returns true if the samplers have the same parametres, else false */ compareSampler(other) { return this._cachedWrapU === other._cachedWrapU && this._cachedWrapV === other._cachedWrapV && this._cachedWrapR === other._cachedWrapR && this._cachedAnisotropicFilteringLevel === other._cachedAnisotropicFilteringLevel && this.samplingMode === other.samplingMode && this._comparisonFunction === other._comparisonFunction && this._useMipMaps === other._useMipMaps; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/internalTexture.js var InternalTextureSource, InternalTexture; var init_internalTexture = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/internalTexture.js"() { init_observable(); init_textureSampler(); (function(InternalTextureSource2) { InternalTextureSource2[InternalTextureSource2["Unknown"] = 0] = "Unknown"; InternalTextureSource2[InternalTextureSource2["Url"] = 1] = "Url"; InternalTextureSource2[InternalTextureSource2["Temp"] = 2] = "Temp"; InternalTextureSource2[InternalTextureSource2["Raw"] = 3] = "Raw"; InternalTextureSource2[InternalTextureSource2["Dynamic"] = 4] = "Dynamic"; InternalTextureSource2[InternalTextureSource2["RenderTarget"] = 5] = "RenderTarget"; InternalTextureSource2[InternalTextureSource2["MultiRenderTarget"] = 6] = "MultiRenderTarget"; InternalTextureSource2[InternalTextureSource2["Cube"] = 7] = "Cube"; InternalTextureSource2[InternalTextureSource2["CubeRaw"] = 8] = "CubeRaw"; InternalTextureSource2[InternalTextureSource2["CubePrefiltered"] = 9] = "CubePrefiltered"; InternalTextureSource2[InternalTextureSource2["Raw3D"] = 10] = "Raw3D"; InternalTextureSource2[InternalTextureSource2["Raw2DArray"] = 11] = "Raw2DArray"; InternalTextureSource2[InternalTextureSource2["DepthStencil"] = 12] = "DepthStencil"; InternalTextureSource2[InternalTextureSource2["CubeRawRGBD"] = 13] = "CubeRawRGBD"; InternalTextureSource2[InternalTextureSource2["Depth"] = 14] = "Depth"; })(InternalTextureSource || (InternalTextureSource = {})); InternalTexture = class _InternalTexture extends TextureSampler { static { __name(this, "InternalTexture"); } /** * Gets a boolean indicating if the texture uses mipmaps * TODO implements useMipMaps as a separate setting from generateMipMaps */ get useMipMaps() { return this.generateMipMaps; } set useMipMaps(value) { this.generateMipMaps = value; } /** Gets the unique id of the internal texture */ get uniqueId() { return this._uniqueId; } /** @internal */ _setUniqueId(id) { this._uniqueId = id; } /** * Gets the Engine the texture belongs to. * @returns The babylon engine */ getEngine() { return this._engine; } /** * Gets the data source type of the texture */ get source() { return this._source; } /** * Creates a new InternalTexture * @param engine defines the engine to use * @param source defines the type of data that will be used * @param delayAllocation if the texture allocation should be delayed (default: false) */ constructor(engine, source, delayAllocation = false) { super(); this.isReady = false; this.isCube = false; this.is3D = false; this.is2DArray = false; this.isMultiview = false; this.url = ""; this.generateMipMaps = false; this.samples = 0; this.type = -1; this.format = -1; this.onLoadedObservable = new Observable(); this.onErrorObservable = new Observable(); this.onRebuildCallback = null; this.width = 0; this.height = 0; this.depth = 0; this.baseWidth = 0; this.baseHeight = 0; this.baseDepth = 0; this.invertY = false; this._invertVScale = false; this._associatedChannel = -1; this._source = 0; this._buffer = null; this._bufferView = null; this._bufferViewArray = null; this._bufferViewArrayArray = null; this._size = 0; this._extension = ""; this._files = null; this._workingCanvas = null; this._workingContext = null; this._cachedCoordinatesMode = null; this._isDisabled = false; this._compression = null; this._sphericalPolynomial = null; this._sphericalPolynomialPromise = null; this._sphericalPolynomialComputed = false; this._lodGenerationScale = 0; this._lodGenerationOffset = 0; this._useSRGBBuffer = false; this._creationFlags = 0; this._lodTextureHigh = null; this._lodTextureMid = null; this._lodTextureLow = null; this._isRGBD = false; this._linearSpecularLOD = false; this._irradianceTexture = null; this._hardwareTexture = null; this._maxLodLevel = null; this._references = 1; this._gammaSpace = null; this._premulAlpha = false; this._dynamicTextureSource = null; this._autoMSAAManagement = false; this._engine = engine; this._source = source; this._uniqueId = _InternalTexture._Counter++; if (!delayAllocation) { this._hardwareTexture = engine._createHardwareTexture(); } } /** * Increments the number of references (ie. the number of Texture that point to it) */ incrementReferences() { this._references++; } /** * Change the size of the texture (not the size of the content) * @param width defines the new width * @param height defines the new height * @param depth defines the new depth (1 by default) */ updateSize(width, height, depth = 1) { this._engine.updateTextureDimensions(this, width, height, depth); this.width = width; this.height = height; this.depth = depth; this.baseWidth = width; this.baseHeight = height; this.baseDepth = depth; this._size = width * height * depth; } /** @internal */ _rebuild() { this.isReady = false; this._cachedCoordinatesMode = null; this._cachedWrapU = null; this._cachedWrapV = null; this._cachedWrapR = null; this._cachedAnisotropicFilteringLevel = null; if (this.onRebuildCallback) { const data = this.onRebuildCallback(this); const swapAndSetIsReady = /* @__PURE__ */ __name((proxyInternalTexture) => { proxyInternalTexture._swapAndDie(this, false); this.isReady = data.isReady; }, "swapAndSetIsReady"); if (data.isAsync) { data.proxy.then(swapAndSetIsReady); } else { swapAndSetIsReady(data.proxy); } return; } let proxy; switch (this.source) { case 2: break; case 1: proxy = this._engine.createTexture( this._originalUrl ?? this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, // Do not use Proxy here as it could be fully synchronous // and proxy would be undefined. (temp) => { temp._swapAndDie(this, false); this.isReady = true; }, null, this._buffer, void 0, this.format, this._extension, void 0, void 0, void 0, this._useSRGBBuffer ); return; case 3: proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type, this._creationFlags, this._useSRGBBuffer); proxy._swapAndDie(this, false); this.isReady = true; break; case 10: proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type); proxy._swapAndDie(this, false); this.isReady = true; break; case 11: proxy = this._engine.createRawTexture2DArray(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression, this.type); proxy._swapAndDie(this, false); this.isReady = true; break; case 4: proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode); proxy._swapAndDie(this, false); if (this._dynamicTextureSource) { this._engine.updateDynamicTexture(this, this._dynamicTextureSource, this.invertY, this._premulAlpha, this.format, true); } break; case 7: proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, () => { proxy._swapAndDie(this, false); this.isReady = true; }, null, this.format, this._extension, false, 0, 0, null, void 0, this._useSRGBBuffer, ArrayBuffer.isView(this._buffer) ? this._buffer : null); return; case 8: proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this._originalFormat ?? this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression); proxy._swapAndDie(this, false); this.isReady = true; break; case 13: return; case 9: proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, (proxy2) => { if (proxy2) { proxy2._swapAndDie(this, false); } this.isReady = true; }, null, this.format, this._extension); proxy._sphericalPolynomial = this._sphericalPolynomial; return; case 12: case 14: { break; } } } /** * @internal */ _swapAndDie(target, swapAll = true) { this._hardwareTexture?.setUsage(target._source, this.generateMipMaps, this.is2DArray, this.isCube, this.is3D, this.width, this.height, this.depth); target._hardwareTexture = this._hardwareTexture; if (swapAll) { target._isRGBD = this._isRGBD; } if (this._lodTextureHigh) { if (target._lodTextureHigh) { target._lodTextureHigh.dispose(); } target._lodTextureHigh = this._lodTextureHigh; } if (this._lodTextureMid) { if (target._lodTextureMid) { target._lodTextureMid.dispose(); } target._lodTextureMid = this._lodTextureMid; } if (this._lodTextureLow) { if (target._lodTextureLow) { target._lodTextureLow.dispose(); } target._lodTextureLow = this._lodTextureLow; } if (this._irradianceTexture) { if (target._irradianceTexture) { target._irradianceTexture.dispose(); } target._irradianceTexture = this._irradianceTexture; } const cache = this._engine.getLoadedTexturesCache(); let index = cache.indexOf(this); if (index !== -1) { cache.splice(index, 1); } index = cache.indexOf(target); if (index === -1) { cache.push(target); } } /** * Dispose the current allocated resources */ dispose() { this._references--; if (this._references === 0) { this.onLoadedObservable.clear(); this.onErrorObservable.clear(); this._engine._releaseTexture(this); this._hardwareTexture = null; this._dynamicTextureSource = null; } } }; InternalTexture._Counter = 0; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/IES/iesLoader.js function LineToArray(line) { return line.split(" ").filter((x) => x !== "").map((x) => parseFloat(x)); } function ReadArray(dataPointer, count, targetArray) { while (targetArray.length !== count) { const line = LineToArray(dataPointer.lines[dataPointer.index++]); targetArray.push(...line); } } function InterpolateCandelaValues(data, phi, theta) { let phiIndex = 0; let thetaIndex = 0; let startTheta = 0; let endTheta = 0; let startPhi = 0; let endPhi = 0; for (let index = 0; index < data.numberOfHorizontalAngles - 1; index++) { if (theta < data.horizontalAngles[index + 1] || index === data.numberOfHorizontalAngles - 2) { thetaIndex = index; startTheta = data.horizontalAngles[index]; endTheta = data.horizontalAngles[index + 1]; break; } } for (let index = 0; index < data.numberOfVerticalAngles - 1; index++) { if (phi < data.verticalAngles[index + 1] || index === data.numberOfVerticalAngles - 2) { phiIndex = index; startPhi = data.verticalAngles[index]; endPhi = data.verticalAngles[index + 1]; break; } } const deltaTheta = endTheta - startTheta; const deltaPhi = endPhi - startPhi; if (deltaPhi === 0) { return 0; } const t1 = deltaTheta === 0 ? 0 : (theta - startTheta) / deltaTheta; const t2 = (phi - startPhi) / deltaPhi; const nextThetaIndex = deltaTheta === 0 ? thetaIndex : thetaIndex + 1; const v1 = Lerp(data.candelaValues[thetaIndex][phiIndex], data.candelaValues[nextThetaIndex][phiIndex], t1); const v2 = Lerp(data.candelaValues[thetaIndex][phiIndex + 1], data.candelaValues[nextThetaIndex][phiIndex + 1], t1); const v = Lerp(v1, v2, t2); return v; } function LoadIESData(uint8Array) { const decoder = new TextDecoder("utf-8"); const source = decoder.decode(uint8Array); const dataPointer = { lines: source.split("\n"), index: 0 }; const data = { version: dataPointer.lines[0], candelaValues: [], horizontalAngles: [], verticalAngles: [], numberOfHorizontalAngles: 0, numberOfVerticalAngles: 0 }; dataPointer.index = 1; while (dataPointer.lines.length > 0 && !dataPointer.lines[dataPointer.index].includes("TILT=")) { dataPointer.index++; } if (dataPointer.lines[dataPointer.index].includes("INCLUDE")) { } dataPointer.index++; const header = LineToArray(dataPointer.lines[dataPointer.index++]); data.numberOfLights = header[0]; data.lumensPerLamp = header[1]; data.candelaMultiplier = header[2]; data.numberOfVerticalAngles = header[3]; data.numberOfHorizontalAngles = header[4]; data.photometricType = header[5]; data.unitsType = header[6]; data.width = header[7]; data.length = header[8]; data.height = header[9]; const additionalData = LineToArray(dataPointer.lines[dataPointer.index++]); data.ballastFactor = additionalData[0]; data.fileGenerationType = additionalData[1]; data.inputWatts = additionalData[2]; for (let index = 0; index < data.numberOfHorizontalAngles; index++) { data.candelaValues[index] = []; } ReadArray(dataPointer, data.numberOfVerticalAngles, data.verticalAngles); ReadArray(dataPointer, data.numberOfHorizontalAngles, data.horizontalAngles); for (let index = 0; index < data.numberOfHorizontalAngles; index++) { ReadArray(dataPointer, data.numberOfVerticalAngles, data.candelaValues[index]); } let maxCandela = -1; for (let index = 0; index < data.numberOfHorizontalAngles; index++) { for (let subIndex = 0; subIndex < data.numberOfVerticalAngles; subIndex++) { data.candelaValues[index][subIndex] *= data.candelaValues[index][subIndex] * data.candelaMultiplier * data.ballastFactor * data.fileGenerationType; maxCandela = Math.max(maxCandela, data.candelaValues[index][subIndex]); } } if (maxCandela > 0) { for (let index = 0; index < data.numberOfHorizontalAngles; index++) { for (let subIndex = 0; subIndex < data.numberOfVerticalAngles; subIndex++) { data.candelaValues[index][subIndex] /= maxCandela; } } } const height = 180; const width = height * 2; const size = width * height; const arrayBuffer = new Float32Array(width * height); const startTheta = data.horizontalAngles[0]; const endTheta = data.horizontalAngles[data.numberOfHorizontalAngles - 1]; for (let index = 0; index < size; index++) { let theta = index % width; const phi = Math.floor(index / width); if (endTheta - startTheta !== 0 && (theta < startTheta || theta >= endTheta)) { theta %= endTheta * 2; if (theta > endTheta) { theta = endTheta * 2 - theta; } } arrayBuffer[phi + theta * height] = InterpolateCandelaValues(data, phi, theta); } return { width: width / 2, height: 1, data: arrayBuffer }; } var init_iesLoader = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/IES/iesLoader.js"() { init_math_scalar_functions(); __name(LineToArray, "LineToArray"); __name(ReadArray, "ReadArray"); __name(InterpolateCandelaValues, "InterpolateCandelaValues"); __name(LoadIESData, "LoadIESData"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/iesTextureLoader.js var iesTextureLoader_exports = {}; __export(iesTextureLoader_exports, { _IESTextureLoader: () => _IESTextureLoader }); var _IESTextureLoader; var init_iesTextureLoader = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/iesTextureLoader.js"() { init_iesLoader(); _IESTextureLoader = class { static { __name(this, "_IESTextureLoader"); } constructor() { this.supportCascades = false; } /** * Uploads the cube texture data to the WebGL texture. It has already been bound. */ loadCubeData() { throw ".ies 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 */ loadData(data, texture, callback) { const uint8array = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); const textureData = LoadIESData(uint8array); callback(textureData.width, textureData.height, texture.useMipMaps, false, () => { const engine = texture.getEngine(); texture.type = 1; texture.format = 6; texture._gammaSpace = false; engine._uploadDataToTextureDirectly(texture, textureData.data); }); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.axis.js var Space, Axis, Coordinate; var init_math_axis = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.axis.js"() { init_math_vector(); (function(Space2) { Space2[Space2["LOCAL"] = 0] = "LOCAL"; Space2[Space2["WORLD"] = 1] = "WORLD"; Space2[Space2["BONE"] = 2] = "BONE"; })(Space || (Space = {})); Axis = class { static { __name(this, "Axis"); } }; Axis.X = new Vector3(1, 0, 0); Axis.Y = new Vector3(0, 1, 0); Axis.Z = new Vector3(0, 0, 1); (function(Coordinate2) { Coordinate2[Coordinate2["X"] = 0] = "X"; Coordinate2[Coordinate2["Y"] = 1] = "Y"; Coordinate2[Coordinate2["Z"] = 2] = "Z"; })(Coordinate || (Coordinate = {})); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.color.js function ColorChannelToLinearSpace(color) { return Math.pow(color, ToLinearSpace); } function ColorChannelToLinearSpaceExact(color) { if (color <= 0.04045) { return 0.0773993808 * color; } return Math.pow(0.947867299 * (color + 0.055), 2.4); } function ColorChannelToGammaSpace(color) { return Math.pow(color, ToGammaSpace); } function ColorChannelToGammaSpaceExact(color) { if (color <= 31308e-7) { return 12.92 * color; } return 1.055 * Math.pow(color, 0.41666) - 0.055; } var Color3, Color4, TmpColors; var init_math_color = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.color.js"() { init_arrayTools(); init_typeStore(); init_math_constants(); init_math_scalar_functions(); __name(ColorChannelToLinearSpace, "ColorChannelToLinearSpace"); __name(ColorChannelToLinearSpaceExact, "ColorChannelToLinearSpaceExact"); __name(ColorChannelToGammaSpace, "ColorChannelToGammaSpace"); __name(ColorChannelToGammaSpaceExact, "ColorChannelToGammaSpaceExact"); Color3 = class _Color3 { static { __name(this, "Color3"); } /** * Creates a new Color3 object from red, green, blue values, all between 0 and 1 * @param r defines the red component (between 0 and 1, default is 0) * @param g defines the green component (between 0 and 1, default is 0) * @param b defines the blue component (between 0 and 1, default is 0) */ constructor(r = 0, g = 0, b = 0) { this.r = r; this.g = g; this.b = b; } /** * Creates a string with the Color3 current values * @returns the string representation of the Color3 object */ toString() { return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}"; } /** * Returns the string "Color3" * @returns "Color3" */ getClassName() { return "Color3"; } /** * Compute the Color3 hash code * @returns an unique number that can be used to hash Color3 objects */ getHashCode() { let hash = this.r * 255 | 0; hash = hash * 397 ^ (this.g * 255 | 0); hash = hash * 397 ^ (this.b * 255 | 0); return hash; } // Operators /** * Stores in the given array from the given starting index the red, green, blue values as successive elements * @param array defines the array where to store the r,g,b components * @param index defines an optional index in the target array to define where to start storing values * @returns the current Color3 object */ toArray(array, index = 0) { array[index] = this.r; array[index + 1] = this.g; array[index + 2] = this.b; return this; } /** * Update the current color with values stored in an array from the starting index of the given array * @param array defines the source array * @param offset defines an offset in the source array * @returns the current Color3 object */ fromArray(array, offset = 0) { _Color3.FromArrayToRef(array, offset, this); return this; } /** * Returns a new Color4 object from the current Color3 and the given alpha * @param alpha defines the alpha component on the new Color4 object (default is 1) * @returns a new Color4 object */ toColor4(alpha = 1) { return new Color4(this.r, this.g, this.b, alpha); } /** * Returns a new array populated with 3 numeric elements : red, green and blue values * @returns the new array */ asArray() { return [this.r, this.g, this.b]; } /** * Returns the luminance value * @returns a float value */ toLuminance() { return this.r * 0.3 + this.g * 0.59 + this.b * 0.11; } /** * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object * @param otherColor defines the second operand * @returns the new Color3 object */ multiply(otherColor) { return new _Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b); } /** * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result" * @param otherColor defines the second operand * @param result defines the Color3 object where to store the result * @returns the result Color3 */ multiplyToRef(otherColor, result) { result.r = this.r * otherColor.r; result.g = this.g * otherColor.g; result.b = this.b * otherColor.b; return result; } /** * Multiplies the current Color3 coordinates by the given ones * @param otherColor defines the second operand * @returns the current updated Color3 */ multiplyInPlace(otherColor) { this.r *= otherColor.r; this.g *= otherColor.g; this.b *= otherColor.b; return this; } /** * Returns a new Color3 set with the result of the multiplication of the current Color3 coordinates by the given floats * @param r defines the r coordinate of the operand * @param g defines the g coordinate of the operand * @param b defines the b coordinate of the operand * @returns the new Color3 */ multiplyByFloats(r, g, b) { return new _Color3(this.r * r, this.g * g, this.b * b); } /** * @internal * Do not use */ divide(_other) { throw new ReferenceError("Can not divide a color"); } /** * @internal * Do not use */ divideToRef(_other, _result) { throw new ReferenceError("Can not divide a color"); } /** * @internal * Do not use */ divideInPlace(_other) { throw new ReferenceError("Can not divide a color"); } /** * Updates the current Color3 with the minimal coordinate values between its and the given color ones * @param other defines the second operand * @returns the current updated Color3 */ minimizeInPlace(other) { return this.minimizeInPlaceFromFloats(other.r, other.g, other.b); } /** * Updates the current Color3 with the maximal coordinate values between its and the given color ones. * @param other defines the second operand * @returns the current updated Color3 */ maximizeInPlace(other) { return this.maximizeInPlaceFromFloats(other.r, other.g, other.b); } /** * Updates the current Color3 with the minimal coordinate values between its and the given coordinates * @param r defines the r coordinate of the operand * @param g defines the g coordinate of the operand * @param b defines the b coordinate of the operand * @returns the current updated Color3 */ minimizeInPlaceFromFloats(r, g, b) { this.r = Math.min(r, this.r); this.g = Math.min(g, this.g); this.b = Math.min(b, this.b); return this; } /** * Updates the current Color3 with the maximal coordinate values between its and the given coordinates. * @param r defines the r coordinate of the operand * @param g defines the g coordinate of the operand * @param b defines the b coordinate of the operand * @returns the current updated Color3 */ maximizeInPlaceFromFloats(r, g, b) { this.r = Math.max(r, this.r); this.g = Math.max(g, this.g); this.b = Math.max(b, this.b); return this; } /** * @internal * Do not use */ floorToRef(_result) { throw new ReferenceError("Can not floor a color"); } /** * @internal * Do not use */ floor() { throw new ReferenceError("Can not floor a color"); } /** * @internal * Do not use */ fractToRef(_result) { throw new ReferenceError("Can not fract a color"); } /** * @internal * Do not use */ fract() { throw new ReferenceError("Can not fract a color"); } /** * Determines equality between Color3 objects * @param otherColor defines the second operand * @returns true if the rgb values are equal to the given ones */ equals(otherColor) { return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b; } /** * Alias for equalsToFloats * @param r red color component * @param g green color component * @param b blue color component * @returns boolean */ equalsFloats(r, g, b) { return this.equalsToFloats(r, g, b); } /** * Determines equality between the current Color3 object and a set of r,b,g values * @param r defines the red component to check * @param g defines the green component to check * @param b defines the blue component to check * @returns true if the rgb values are equal to the given ones */ equalsToFloats(r, g, b) { return this.r === r && this.g === g && this.b === b; } /** * Returns true if the current Color3 and the given color coordinates are distant less than epsilon * @param otherColor defines the second operand * @param epsilon defines the minimal distance to define values as equals * @returns true if both colors are distant less than epsilon */ equalsWithEpsilon(otherColor, epsilon = Epsilon) { return WithinEpsilon(this.r, otherColor.r, epsilon) && WithinEpsilon(this.g, otherColor.g, epsilon) && WithinEpsilon(this.b, otherColor.b, epsilon); } /** * @internal * Do not use */ negate() { throw new ReferenceError("Can not negate a color"); } /** * @internal * Do not use */ negateInPlace() { throw new ReferenceError("Can not negate a color"); } /** * @internal * Do not use */ negateToRef(_result) { throw new ReferenceError("Can not negate a color"); } /** * Creates a new Color3 with the current Color3 values multiplied by scale * @param scale defines the scaling factor to apply * @returns a new Color3 object */ scale(scale) { return new _Color3(this.r * scale, this.g * scale, this.b * scale); } /** * Multiplies the Color3 values by the float "scale" * @param scale defines the scaling factor to apply * @returns the current updated Color3 */ scaleInPlace(scale) { this.r *= scale; this.g *= scale; this.b *= scale; return this; } /** * Multiplies the rgb values by scale and stores the result into "result" * @param scale defines the scaling factor * @param result defines the Color3 object where to store the result * @returns the result Color3 */ scaleToRef(scale, result) { result.r = this.r * scale; result.g = this.g * scale; result.b = this.b * scale; return result; } /** * Scale the current Color3 values by a factor and add the result to a given Color3 * @param scale defines the scale factor * @param result defines color to store the result into * @returns the result Color3 */ scaleAndAddToRef(scale, result) { result.r += this.r * scale; result.g += this.g * scale; result.b += this.b * scale; return result; } /** * Clamps the rgb values by the min and max values and stores the result into "result" * @param min defines minimum clamping value (default is 0) * @param max defines maximum clamping value (default is 1) * @param result defines color to store the result into * @returns the result Color3 */ clampToRef(min = 0, max = 1, result) { result.r = Clamp(this.r, min, max); result.g = Clamp(this.g, min, max); result.b = Clamp(this.b, min, max); return result; } /** * Creates a new Color3 set with the added values of the current Color3 and of the given one * @param otherColor defines the second operand * @returns the new Color3 */ add(otherColor) { return new _Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b); } /** * Adds the given color to the current Color3 * @param otherColor defines the second operand * @returns the current updated Color3 */ addInPlace(otherColor) { this.r += otherColor.r; this.g += otherColor.g; this.b += otherColor.b; return this; } /** * Adds the given coordinates to the current Color3 * @param r defines the r coordinate of the operand * @param g defines the g coordinate of the operand * @param b defines the b coordinate of the operand * @returns the current updated Color3 */ addInPlaceFromFloats(r, g, b) { this.r += r; this.g += g; this.b += b; return this; } /** * Stores the result of the addition of the current Color3 and given one rgb values into "result" * @param otherColor defines the second operand * @param result defines Color3 object to store the result into * @returns the unmodified current Color3 */ addToRef(otherColor, result) { result.r = this.r + otherColor.r; result.g = this.g + otherColor.g; result.b = this.b + otherColor.b; return result; } /** * Returns a new Color3 set with the subtracted values of the given one from the current Color3 * @param otherColor defines the second operand * @returns the new Color3 */ subtract(otherColor) { return new _Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b); } /** * Stores the result of the subtraction of given one from the current Color3 rgb values into "result" * @param otherColor defines the second operand * @param result defines Color3 object to store the result into * @returns the unmodified current Color3 */ subtractToRef(otherColor, result) { result.r = this.r - otherColor.r; result.g = this.g - otherColor.g; result.b = this.b - otherColor.b; return result; } /** * Subtract the given color from the current Color3 * @param otherColor defines the second operand * @returns the current updated Color3 */ subtractInPlace(otherColor) { this.r -= otherColor.r; this.g -= otherColor.g; this.b -= otherColor.b; return this; } /** * Returns a new Color3 set with the subtraction of the given floats from the current Color3 coordinates * @param r defines the r coordinate of the operand * @param g defines the g coordinate of the operand * @param b defines the b coordinate of the operand * @returns the resulting Color3 */ subtractFromFloats(r, g, b) { return new _Color3(this.r - r, this.g - g, this.b - b); } /** * Subtracts the given floats from the current Color3 coordinates and set the given color "result" with this result * @param r defines the r coordinate of the operand * @param g defines the g coordinate of the operand * @param b defines the b coordinate of the operand * @param result defines the Color3 object where to store the result * @returns the result */ subtractFromFloatsToRef(r, g, b, result) { result.r = this.r - r; result.g = this.g - g; result.b = this.b - b; return result; } /** * Copy the current object * @returns a new Color3 copied the current one */ clone() { return new _Color3(this.r, this.g, this.b); } /** * Copies the rgb values from the source in the current Color3 * @param source defines the source Color3 object * @returns the updated Color3 object */ copyFrom(source) { this.r = source.r; this.g = source.g; this.b = source.b; return this; } /** * Updates the Color3 rgb values from the given floats * @param r defines the red component to read from * @param g defines the green component to read from * @param b defines the blue component to read from * @returns the current Color3 object */ copyFromFloats(r, g, b) { this.r = r; this.g = g; this.b = b; return this; } /** * Updates the Color3 rgb values from the given floats * @param r defines the red component to read from * @param g defines the green component to read from * @param b defines the blue component to read from * @returns the current Color3 object */ set(r, g, b) { return this.copyFromFloats(r, g, b); } /** * Copies the given float to the current Color3 coordinates * @param v defines the r, g and b coordinates of the operand * @returns the current updated Color3 */ setAll(v) { this.r = this.g = this.b = v; return this; } /** * Compute the Color3 hexadecimal code as a string * @returns a string containing the hexadecimal representation of the Color3 object */ toHexString() { const intR = Math.round(this.r * 255); const intG = Math.round(this.g * 255); const intB = Math.round(this.b * 255); return "#" + ToHex(intR) + ToHex(intG) + ToHex(intB); } /** * Updates the Color3 rgb values from the string containing valid hexadecimal values * @param hex defines a string containing valid hexadecimal values * @returns the current Color3 object */ fromHexString(hex) { if (hex.substring(0, 1) !== "#" || hex.length !== 7) { return this; } this.r = parseInt(hex.substring(1, 3), 16) / 255; this.g = parseInt(hex.substring(3, 5), 16) / 255; this.b = parseInt(hex.substring(5, 7), 16) / 255; return this; } /** * Converts current color in rgb space to HSV values * @returns a new color3 representing the HSV values */ toHSV() { return this.toHSVToRef(new _Color3()); } /** * Converts current color in rgb space to HSV values * @param result defines the Color3 where to store the HSV values * @returns the updated result */ toHSVToRef(result) { const r = this.r; const g = this.g; const b = this.b; const max = Math.max(r, g, b); const min = Math.min(r, g, b); let h = 0; let s = 0; const v = max; const dm = max - min; if (max !== 0) { s = dm / max; } if (max != min) { if (max == r) { h = (g - b) / dm; if (g < b) { h += 6; } } else if (max == g) { h = (b - r) / dm + 2; } else if (max == b) { h = (r - g) / dm + 4; } h *= 60; } result.r = h; result.g = s; result.b = v; return result; } /** * Computes a new Color3 converted from the current one to linear space * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) * @returns a new Color3 object */ toLinearSpace(exact = false) { const convertedColor = new _Color3(); this.toLinearSpaceToRef(convertedColor, exact); return convertedColor; } /** * Converts the Color3 values to linear space and stores the result in "convertedColor" * @param convertedColor defines the Color3 object where to store the linear space version * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) * @returns the unmodified Color3 */ toLinearSpaceToRef(convertedColor, exact = false) { if (exact) { convertedColor.r = ColorChannelToLinearSpaceExact(this.r); convertedColor.g = ColorChannelToLinearSpaceExact(this.g); convertedColor.b = ColorChannelToLinearSpaceExact(this.b); } else { convertedColor.r = ColorChannelToLinearSpace(this.r); convertedColor.g = ColorChannelToLinearSpace(this.g); convertedColor.b = ColorChannelToLinearSpace(this.b); } return this; } /** * Computes a new Color3 converted from the current one to gamma space * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) * @returns a new Color3 object */ toGammaSpace(exact = false) { const convertedColor = new _Color3(); this.toGammaSpaceToRef(convertedColor, exact); return convertedColor; } /** * Converts the Color3 values to gamma space and stores the result in "convertedColor" * @param convertedColor defines the Color3 object where to store the gamma space version * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) * @returns the unmodified Color3 */ toGammaSpaceToRef(convertedColor, exact = false) { if (exact) { convertedColor.r = ColorChannelToGammaSpaceExact(this.r); convertedColor.g = ColorChannelToGammaSpaceExact(this.g); convertedColor.b = ColorChannelToGammaSpaceExact(this.b); } else { convertedColor.r = ColorChannelToGammaSpace(this.r); convertedColor.g = ColorChannelToGammaSpace(this.g); convertedColor.b = ColorChannelToGammaSpace(this.b); } return this; } /** * Converts Hue, saturation and value to a Color3 (RGB) * @param hue defines the hue (value between 0 and 360) * @param saturation defines the saturation (value between 0 and 1) * @param value defines the value (value between 0 and 1) * @param result defines the Color3 where to store the RGB values * @returns the updated result */ static HSVtoRGBToRef(hue, saturation, value, result) { const chroma = value * saturation; const h = hue / 60; const x = chroma * (1 - Math.abs(h % 2 - 1)); let r = 0; let g = 0; let b = 0; if (h >= 0 && h <= 1) { r = chroma; g = x; } else if (h >= 1 && h <= 2) { r = x; g = chroma; } else if (h >= 2 && h <= 3) { g = chroma; b = x; } else if (h >= 3 && h <= 4) { g = x; b = chroma; } else if (h >= 4 && h <= 5) { r = x; b = chroma; } else if (h >= 5 && h <= 6) { r = chroma; b = x; } const m = value - chroma; result.r = r + m; result.g = g + m; result.b = b + m; return result; } /** * Converts Hue, saturation and value to a new Color3 (RGB) * @param hue defines the hue (value between 0 and 360) * @param saturation defines the saturation (value between 0 and 1) * @param value defines the value (value between 0 and 1) * @returns a new Color3 object */ static FromHSV(hue, saturation, value) { const result = new _Color3(0, 0, 0); _Color3.HSVtoRGBToRef(hue, saturation, value, result); return result; } /** * Creates a new Color3 from the string containing valid hexadecimal values * @param hex defines a string containing valid hexadecimal values * @returns a new Color3 object */ static FromHexString(hex) { return new _Color3(0, 0, 0).fromHexString(hex); } /** * Creates a new Color3 from the starting index of the given array * @param array defines the source array * @param offset defines an offset in the source array * @returns a new Color3 object */ static FromArray(array, offset = 0) { return new _Color3(array[offset], array[offset + 1], array[offset + 2]); } /** * Creates a new Color3 from the starting index element of the given array * @param array defines the source array to read from * @param offset defines the offset in the source array * @param result defines the target Color3 object */ static FromArrayToRef(array, offset = 0, result) { result.r = array[offset]; result.g = array[offset + 1]; result.b = array[offset + 2]; } /** * Creates a new Color3 from integer values (\< 256) * @param r defines the red component to read from (value between 0 and 255) * @param g defines the green component to read from (value between 0 and 255) * @param b defines the blue component to read from (value between 0 and 255) * @returns a new Color3 object */ static FromInts(r, g, b) { return new _Color3(r / 255, g / 255, b / 255); } /** * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3 * @param start defines the start Color3 value * @param end defines the end Color3 value * @param amount defines the gradient value between start and end * @returns a new Color3 object */ static Lerp(start, end, amount) { const result = new _Color3(0, 0, 0); _Color3.LerpToRef(start, end, amount, result); return result; } /** * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3 * @param left defines the start value * @param right defines the end value * @param amount defines the gradient factor * @param result defines the Color3 object where to store the result */ static LerpToRef(left, right, amount, result) { result.r = left.r + (right.r - left.r) * amount; result.g = left.g + (right.g - left.g) * amount; result.b = left.b + (right.b - left.b) * amount; } /** * Returns a new Color3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2" * @param value1 defines the first control point * @param tangent1 defines the first tangent Color3 * @param value2 defines the second control point * @param tangent2 defines the second tangent Color3 * @param amount defines the amount on the interpolation spline (between 0 and 1) * @returns the new Color3 */ static Hermite(value1, tangent1, value2, tangent2, amount) { const squared = amount * amount; const cubed = amount * squared; const part1 = 2 * cubed - 3 * squared + 1; const part2 = -2 * cubed + 3 * squared; const part3 = cubed - 2 * squared + amount; const part4 = cubed - squared; const r = value1.r * part1 + value2.r * part2 + tangent1.r * part3 + tangent2.r * part4; const g = value1.g * part1 + value2.g * part2 + tangent1.g * part3 + tangent2.g * part4; const b = value1.b * part1 + value2.b * part2 + tangent1.b * part3 + tangent2.b * part4; return new _Color3(r, g, b); } /** * Returns a new Color3 which is the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2". * @param value1 defines the first control point * @param tangent1 defines the first tangent * @param value2 defines the second control point * @param tangent2 defines the second tangent * @param time define where the derivative must be done * @returns 1st derivative */ static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { const result = _Color3.Black(); this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result); return result; } /** * Returns a new Color3 which is the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2". * @param value1 defines the first control point * @param tangent1 defines the first tangent * @param value2 defines the second control point * @param tangent2 defines the second tangent * @param time define where the derivative must be done * @param result define where to store the derivative */ static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { const t2 = time * time; result.r = (t2 - time) * 6 * value1.r + (3 * t2 - 4 * time + 1) * tangent1.r + (-t2 + time) * 6 * value2.r + (3 * t2 - 2 * time) * tangent2.r; result.g = (t2 - time) * 6 * value1.g + (3 * t2 - 4 * time + 1) * tangent1.g + (-t2 + time) * 6 * value2.g + (3 * t2 - 2 * time) * tangent2.g; result.b = (t2 - time) * 6 * value1.b + (3 * t2 - 4 * time + 1) * tangent1.b + (-t2 + time) * 6 * value2.b + (3 * t2 - 2 * time) * tangent2.b; } /** * Returns a Color3 value containing a red color * @returns a new Color3 object */ static Red() { return new _Color3(1, 0, 0); } /** * Returns a Color3 value containing a green color * @returns a new Color3 object */ static Green() { return new _Color3(0, 1, 0); } /** * Returns a Color3 value containing a blue color * @returns a new Color3 object */ static Blue() { return new _Color3(0, 0, 1); } /** * Returns a Color3 value containing a black color * @returns a new Color3 object */ static Black() { return new _Color3(0, 0, 0); } /** * Gets a Color3 value containing a black color that must not be updated */ static get BlackReadOnly() { return _Color3._BlackReadOnly; } /** * Returns a Color3 value containing a white color * @returns a new Color3 object */ static White() { return new _Color3(1, 1, 1); } /** * Returns a Color3 value containing a purple color * @returns a new Color3 object */ static Purple() { return new _Color3(0.5, 0, 0.5); } /** * Returns a Color3 value containing a magenta color * @returns a new Color3 object */ static Magenta() { return new _Color3(1, 0, 1); } /** * Returns a Color3 value containing a yellow color * @returns a new Color3 object */ static Yellow() { return new _Color3(1, 1, 0); } /** * Returns a Color3 value containing a gray color * @returns a new Color3 object */ static Gray() { return new _Color3(0.5, 0.5, 0.5); } /** * Returns a Color3 value containing a teal color * @returns a new Color3 object */ static Teal() { return new _Color3(0, 1, 1); } /** * Returns a Color3 value containing a random color * @returns a new Color3 object */ static Random() { return new _Color3(Math.random(), Math.random(), Math.random()); } }; Color3._V8PerformanceHack = new Color3(0.5, 0.5, 0.5); Color3._BlackReadOnly = Color3.Black(); Object.defineProperties(Color3.prototype, { dimension: { value: [3] }, rank: { value: 1 } }); Color4 = class _Color4 { static { __name(this, "Color4"); } /** * Creates a new Color4 object from red, green, blue values, all between 0 and 1 * @param r defines the red component (between 0 and 1, default is 0) * @param g defines the green component (between 0 and 1, default is 0) * @param b defines the blue component (between 0 and 1, default is 0) * @param a defines the alpha component (between 0 and 1, default is 1) */ constructor(r = 0, g = 0, b = 0, a = 1) { this.r = r; this.g = g; this.b = b; this.a = a; } // Operators /** * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values * @returns the new array */ asArray() { return [this.r, this.g, this.b, this.a]; } /** * Stores from the starting index in the given array the Color4 successive values * @param array defines the array where to store the r,g,b components * @param index defines an optional index in the target array to define where to start storing values * @returns the current Color4 object */ toArray(array, index = 0) { array[index] = this.r; array[index + 1] = this.g; array[index + 2] = this.b; array[index + 3] = this.a; return this; } /** * Update the current color with values stored in an array from the starting index of the given array * @param array defines the source array * @param offset defines an offset in the source array * @returns the current Color4 object */ fromArray(array, offset = 0) { this.r = array[offset]; this.g = array[offset + 1]; this.b = array[offset + 2]; this.a = array[offset + 3]; return this; } /** * Determines equality between Color4 objects * @param otherColor defines the second operand * @returns true if the rgba values are equal to the given ones */ equals(otherColor) { return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b && this.a === otherColor.a; } /** * Creates a new Color4 set with the added values of the current Color4 and of the given one * @param otherColor defines the second operand * @returns a new Color4 object */ add(otherColor) { return new _Color4(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b, this.a + otherColor.a); } /** * Updates the given color "result" with the result of the addition of the current Color4 and the given one. * @param otherColor the color to add * @param result the color to store the result * @returns result input */ addToRef(otherColor, result) { result.r = this.r + otherColor.r; result.g = this.g + otherColor.g; result.b = this.b + otherColor.b; result.a = this.a + otherColor.a; return result; } /** * Adds in place the given Color4 values to the current Color4 object * @param otherColor defines the second operand * @returns the current updated Color4 object */ addInPlace(otherColor) { this.r += otherColor.r; this.g += otherColor.g; this.b += otherColor.b; this.a += otherColor.a; return this; } /** * Adds the given coordinates to the current Color4 * @param r defines the r coordinate of the operand * @param g defines the g coordinate of the operand * @param b defines the b coordinate of the operand * @param a defines the a coordinate of the operand * @returns the current updated Color4 */ addInPlaceFromFloats(r, g, b, a) { this.r += r; this.g += g; this.b += b; this.a += a; return this; } /** * Creates a new Color4 set with the subtracted values of the given one from the current Color4 * @param otherColor defines the second operand * @returns a new Color4 object */ subtract(otherColor) { return new _Color4(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b, this.a - otherColor.a); } /** * Subtracts the given ones from the current Color4 values and stores the results in "result" * @param otherColor defines the second operand * @param result defines the Color4 object where to store the result * @returns the result Color4 object */ subtractToRef(otherColor, result) { result.r = this.r - otherColor.r; result.g = this.g - otherColor.g; result.b = this.b - otherColor.b; result.a = this.a - otherColor.a; return result; } /** * Subtract in place the given color from the current Color4. * @param otherColor the color to subtract * @returns the updated Color4. */ subtractInPlace(otherColor) { this.r -= otherColor.r; this.g -= otherColor.g; this.b -= otherColor.b; this.a -= otherColor.a; return this; } /** * Returns a new Color4 set with the result of the subtraction of the given floats from the current Color4 coordinates. * @param r value to subtract * @param g value to subtract * @param b value to subtract * @param a value to subtract * @returns new color containing the result */ subtractFromFloats(r, g, b, a) { return new _Color4(this.r - r, this.g - g, this.b - b, this.a - a); } /** * Sets the given color "result" set with the result of the subtraction of the given floats from the current Color4 coordinates. * @param r value to subtract * @param g value to subtract * @param b value to subtract * @param a value to subtract * @param result the color to store the result in * @returns result input */ subtractFromFloatsToRef(r, g, b, a, result) { result.r = this.r - r; result.g = this.g - g; result.b = this.b - b; result.a = this.a - a; return result; } /** * Creates a new Color4 with the current Color4 values multiplied by scale * @param scale defines the scaling factor to apply * @returns a new Color4 object */ scale(scale) { return new _Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale); } /** * Multiplies the Color4 values by the float "scale" * @param scale defines the scaling factor to apply * @returns the current updated Color4 */ scaleInPlace(scale) { this.r *= scale; this.g *= scale; this.b *= scale; this.a *= scale; return this; } /** * Multiplies the current Color4 values by scale and stores the result in "result" * @param scale defines the scaling factor to apply * @param result defines the Color4 object where to store the result * @returns the result Color4 */ scaleToRef(scale, result) { result.r = this.r * scale; result.g = this.g * scale; result.b = this.b * scale; result.a = this.a * scale; return result; } /** * Scale the current Color4 values by a factor and add the result to a given Color4 * @param scale defines the scale factor * @param result defines the Color4 object where to store the result * @returns the result Color4 */ scaleAndAddToRef(scale, result) { result.r += this.r * scale; result.g += this.g * scale; result.b += this.b * scale; result.a += this.a * scale; return result; } /** * Clamps the rgb values by the min and max values and stores the result into "result" * @param min defines minimum clamping value (default is 0) * @param max defines maximum clamping value (default is 1) * @param result defines color to store the result into. * @returns the result Color4 */ clampToRef(min = 0, max = 1, result) { result.r = Clamp(this.r, min, max); result.g = Clamp(this.g, min, max); result.b = Clamp(this.b, min, max); result.a = Clamp(this.a, min, max); return result; } /** * Multiply an Color4 value by another and return a new Color4 object * @param color defines the Color4 value to multiply by * @returns a new Color4 object */ multiply(color) { return new _Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a); } /** * Multiply a Color4 value by another and push the result in a reference value * @param color defines the Color4 value to multiply by * @param result defines the Color4 to fill the result in * @returns the result Color4 */ multiplyToRef(color, result) { result.r = this.r * color.r; result.g = this.g * color.g; result.b = this.b * color.b; result.a = this.a * color.a; return result; } /** * Multiplies in place the current Color4 by the given one. * @param otherColor color to multiple with * @returns the updated Color4. */ multiplyInPlace(otherColor) { this.r *= otherColor.r; this.g *= otherColor.g; this.b *= otherColor.b; this.a *= otherColor.a; return this; } /** * Returns a new Color4 set with the multiplication result of the given floats and the current Color4 coordinates. * @param r value multiply with * @param g value multiply with * @param b value multiply with * @param a value multiply with * @returns resulting new color */ multiplyByFloats(r, g, b, a) { return new _Color4(this.r * r, this.g * g, this.b * b, this.a * a); } /** * @internal * Do not use */ divide(_other) { throw new ReferenceError("Can not divide a color"); } /** * @internal * Do not use */ divideToRef(_other, _result) { throw new ReferenceError("Can not divide a color"); } /** * @internal * Do not use */ divideInPlace(_other) { throw new ReferenceError("Can not divide a color"); } /** * Updates the Color4 coordinates with the minimum values between its own and the given color ones * @param other defines the second operand * @returns the current updated Color4 */ minimizeInPlace(other) { this.r = Math.min(this.r, other.r); this.g = Math.min(this.g, other.g); this.b = Math.min(this.b, other.b); this.a = Math.min(this.a, other.a); return this; } /** * Updates the Color4 coordinates with the maximum values between its own and the given color ones * @param other defines the second operand * @returns the current updated Color4 */ maximizeInPlace(other) { this.r = Math.max(this.r, other.r); this.g = Math.max(this.g, other.g); this.b = Math.max(this.b, other.b); this.a = Math.max(this.a, other.a); return this; } /** * Updates the current Color4 with the minimal coordinate values between its and the given coordinates * @param r defines the r coordinate of the operand * @param g defines the g coordinate of the operand * @param b defines the b coordinate of the operand * @param a defines the a coordinate of the operand * @returns the current updated Color4 */ minimizeInPlaceFromFloats(r, g, b, a) { this.r = Math.min(r, this.r); this.g = Math.min(g, this.g); this.b = Math.min(b, this.b); this.a = Math.min(a, this.a); return this; } /** * Updates the current Color4 with the maximal coordinate values between its and the given coordinates. * @param r defines the r coordinate of the operand * @param g defines the g coordinate of the operand * @param b defines the b coordinate of the operand * @param a defines the a coordinate of the operand * @returns the current updated Color4 */ maximizeInPlaceFromFloats(r, g, b, a) { this.r = Math.max(r, this.r); this.g = Math.max(g, this.g); this.b = Math.max(b, this.b); this.a = Math.max(a, this.a); return this; } /** * @internal * Do not use */ floorToRef(_result) { throw new ReferenceError("Can not floor a color"); } /** * @internal * Do not use */ floor() { throw new ReferenceError("Can not floor a color"); } /** * @internal * Do not use */ fractToRef(_result) { throw new ReferenceError("Can not fract a color"); } /** * @internal * Do not use */ fract() { throw new ReferenceError("Can not fract a color"); } /** * @internal * Do not use */ negate() { throw new ReferenceError("Can not negate a color"); } /** * @internal * Do not use */ negateInPlace() { throw new ReferenceError("Can not negate a color"); } /** * @internal * Do not use */ negateToRef(_result) { throw new ReferenceError("Can not negate a color"); } /** * Boolean : True if the current Color4 coordinates are each beneath the distance "epsilon" from the given color ones. * @param otherColor color to compare against * @param epsilon (Default: very small number) * @returns true if they are equal */ equalsWithEpsilon(otherColor, epsilon = Epsilon) { return WithinEpsilon(this.r, otherColor.r, epsilon) && WithinEpsilon(this.g, otherColor.g, epsilon) && WithinEpsilon(this.b, otherColor.b, epsilon) && WithinEpsilon(this.a, otherColor.a, epsilon); } /** * Boolean : True if the given floats are strictly equal to the current Color4 coordinates. * @param x x value to compare against * @param y y value to compare against * @param z z value to compare against * @param w w value to compare against * @returns true if equal */ equalsToFloats(x, y, z, w) { return this.r === x && this.g === y && this.b === z && this.a === w; } /** * Creates a string with the Color4 current values * @returns the string representation of the Color4 object */ toString() { return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}"; } /** * Returns the string "Color4" * @returns "Color4" */ getClassName() { return "Color4"; } /** * Compute the Color4 hash code * @returns an unique number that can be used to hash Color4 objects */ getHashCode() { let hash = this.r * 255 | 0; hash = hash * 397 ^ (this.g * 255 | 0); hash = hash * 397 ^ (this.b * 255 | 0); hash = hash * 397 ^ (this.a * 255 | 0); return hash; } /** * Creates a new Color4 copied from the current one * @returns a new Color4 object */ clone() { const result = new _Color4(); return result.copyFrom(this); } /** * Copies the given Color4 values into the current one * @param source defines the source Color4 object * @returns the current updated Color4 object */ copyFrom(source) { this.r = source.r; this.g = source.g; this.b = source.b; this.a = source.a; return this; } /** * Copies the given float values into the current one * @param r defines the red component to read from * @param g defines the green component to read from * @param b defines the blue component to read from * @param a defines the alpha component to read from * @returns the current updated Color4 object */ copyFromFloats(r, g, b, a) { this.r = r; this.g = g; this.b = b; this.a = a; return this; } /** * Copies the given float values into the current one * @param r defines the red component to read from * @param g defines the green component to read from * @param b defines the blue component to read from * @param a defines the alpha component to read from * @returns the current updated Color4 object */ set(r, g, b, a) { return this.copyFromFloats(r, g, b, a); } /** * Copies the given float to the current Vector4 coordinates * @param v defines the r, g, b, and a coordinates of the operand * @returns the current updated Vector4 */ setAll(v) { this.r = this.g = this.b = this.a = v; return this; } /** * Compute the Color4 hexadecimal code as a string * @param returnAsColor3 defines if the string should only contains RGB values (off by default) * @returns a string containing the hexadecimal representation of the Color4 object */ toHexString(returnAsColor3 = false) { const intR = Math.round(this.r * 255); const intG = Math.round(this.g * 255); const intB = Math.round(this.b * 255); if (returnAsColor3) { return "#" + ToHex(intR) + ToHex(intG) + ToHex(intB); } const intA = Math.round(this.a * 255); return "#" + ToHex(intR) + ToHex(intG) + ToHex(intB) + ToHex(intA); } /** * Updates the Color4 rgba values from the string containing valid hexadecimal values. * * A valid hex string is either in the format #RRGGBB or #RRGGBBAA. * * When a hex string without alpha is passed, the resulting Color4 keeps * its previous alpha value. * * An invalid string does not modify this object * * @param hex defines a string containing valid hexadecimal values * @returns the current updated Color4 object */ fromHexString(hex) { if (hex.substring(0, 1) !== "#" || hex.length !== 9 && hex.length !== 7) { return this; } this.r = parseInt(hex.substring(1, 3), 16) / 255; this.g = parseInt(hex.substring(3, 5), 16) / 255; this.b = parseInt(hex.substring(5, 7), 16) / 255; if (hex.length === 9) { this.a = parseInt(hex.substring(7, 9), 16) / 255; } return this; } /** * Computes a new Color4 converted from the current one to linear space * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) * @returns a new Color4 object */ toLinearSpace(exact = false) { const convertedColor = new _Color4(); this.toLinearSpaceToRef(convertedColor, exact); return convertedColor; } /** * Converts the Color4 values to linear space and stores the result in "convertedColor" * @param convertedColor defines the Color4 object where to store the linear space version * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) * @returns the unmodified Color4 */ toLinearSpaceToRef(convertedColor, exact = false) { if (exact) { convertedColor.r = ColorChannelToLinearSpaceExact(this.r); convertedColor.g = ColorChannelToLinearSpaceExact(this.g); convertedColor.b = ColorChannelToLinearSpaceExact(this.b); } else { convertedColor.r = ColorChannelToLinearSpace(this.r); convertedColor.g = ColorChannelToLinearSpace(this.g); convertedColor.b = ColorChannelToLinearSpace(this.b); } convertedColor.a = this.a; return this; } /** * Computes a new Color4 converted from the current one to gamma space * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) * @returns a new Color4 object */ toGammaSpace(exact = false) { const convertedColor = new _Color4(); this.toGammaSpaceToRef(convertedColor, exact); return convertedColor; } /** * Converts the Color4 values to gamma space and stores the result in "convertedColor" * @param convertedColor defines the Color4 object where to store the gamma space version * @param exact defines if the conversion will be done in an exact way which is slower but more accurate (default is false) * @returns the unmodified Color4 */ toGammaSpaceToRef(convertedColor, exact = false) { if (exact) { convertedColor.r = ColorChannelToGammaSpaceExact(this.r); convertedColor.g = ColorChannelToGammaSpaceExact(this.g); convertedColor.b = ColorChannelToGammaSpaceExact(this.b); } else { convertedColor.r = ColorChannelToGammaSpace(this.r); convertedColor.g = ColorChannelToGammaSpace(this.g); convertedColor.b = ColorChannelToGammaSpace(this.b); } convertedColor.a = this.a; return this; } // Statics /** * Creates a new Color4 from the string containing valid hexadecimal values. * * A valid hex string is either in the format #RRGGBB or #RRGGBBAA. * * When a hex string without alpha is passed, the resulting Color4 has * its alpha value set to 1.0. * * An invalid string results in a Color with all its channels set to 0.0, * i.e. "transparent black". * * @param hex defines a string containing valid hexadecimal values * @returns a new Color4 object */ static FromHexString(hex) { if (hex.substring(0, 1) !== "#" || hex.length !== 9 && hex.length !== 7) { return new _Color4(0, 0, 0, 0); } return new _Color4(0, 0, 0, 1).fromHexString(hex); } /** * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object * @param left defines the start value * @param right defines the end value * @param amount defines the gradient factor * @returns a new Color4 object */ static Lerp(left, right, amount) { return _Color4.LerpToRef(left, right, amount, new _Color4()); } /** * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object * @param left defines the start value * @param right defines the end value * @param amount defines the gradient factor * @param result defines the Color4 object where to store data * @returns the updated result */ static LerpToRef(left, right, amount, result) { result.r = left.r + (right.r - left.r) * amount; result.g = left.g + (right.g - left.g) * amount; result.b = left.b + (right.b - left.b) * amount; result.a = left.a + (right.a - left.a) * amount; return result; } /** * Interpolate between two Color4 using Hermite interpolation * @param value1 defines first Color4 * @param tangent1 defines the incoming tangent * @param value2 defines second Color4 * @param tangent2 defines the outgoing tangent * @param amount defines the target Color4 * @returns the new interpolated Color4 */ static Hermite(value1, tangent1, value2, tangent2, amount) { const squared = amount * amount; const cubed = amount * squared; const part1 = 2 * cubed - 3 * squared + 1; const part2 = -2 * cubed + 3 * squared; const part3 = cubed - 2 * squared + amount; const part4 = cubed - squared; const r = value1.r * part1 + value2.r * part2 + tangent1.r * part3 + tangent2.r * part4; const g = value1.g * part1 + value2.g * part2 + tangent1.g * part3 + tangent2.g * part4; const b = value1.b * part1 + value2.b * part2 + tangent1.b * part3 + tangent2.b * part4; const a = value1.a * part1 + value2.a * part2 + tangent1.a * part3 + tangent2.a * part4; return new _Color4(r, g, b, a); } /** * Returns a new Color4 which is the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2". * @param value1 defines the first control point * @param tangent1 defines the first tangent * @param value2 defines the second control point * @param tangent2 defines the second tangent * @param time define where the derivative must be done * @returns 1st derivative */ static Hermite1stDerivative(value1, tangent1, value2, tangent2, time) { const result = new _Color4(); this.Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result); return result; } /** * Update a Color4 with the 1st derivative of the Hermite spline defined by the colors "value1", "value2", "tangent1", "tangent2". * @param value1 defines the first control point * @param tangent1 defines the first tangent * @param value2 defines the second control point * @param tangent2 defines the second tangent * @param time define where the derivative must be done * @param result define where to store the derivative */ static Hermite1stDerivativeToRef(value1, tangent1, value2, tangent2, time, result) { const t2 = time * time; result.r = (t2 - time) * 6 * value1.r + (3 * t2 - 4 * time + 1) * tangent1.r + (-t2 + time) * 6 * value2.r + (3 * t2 - 2 * time) * tangent2.r; result.g = (t2 - time) * 6 * value1.g + (3 * t2 - 4 * time + 1) * tangent1.g + (-t2 + time) * 6 * value2.g + (3 * t2 - 2 * time) * tangent2.g; result.b = (t2 - time) * 6 * value1.b + (3 * t2 - 4 * time + 1) * tangent1.b + (-t2 + time) * 6 * value2.b + (3 * t2 - 2 * time) * tangent2.b; result.a = (t2 - time) * 6 * value1.a + (3 * t2 - 4 * time + 1) * tangent1.a + (-t2 + time) * 6 * value2.a + (3 * t2 - 2 * time) * tangent2.a; } /** * Creates a new Color4 from a Color3 and an alpha value * @param color3 defines the source Color3 to read from * @param alpha defines the alpha component (1.0 by default) * @returns a new Color4 object */ static FromColor3(color3, alpha = 1) { return new _Color4(color3.r, color3.g, color3.b, alpha); } /** * Creates a new Color4 from the starting index element of the given array * @param array defines the source array to read from * @param offset defines the offset in the source array * @returns a new Color4 object */ static FromArray(array, offset = 0) { return new _Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]); } /** * Creates a new Color4 from the starting index element of the given array * @param array defines the source array to read from * @param offset defines the offset in the source array * @param result defines the target Color4 object */ static FromArrayToRef(array, offset = 0, result) { result.r = array[offset]; result.g = array[offset + 1]; result.b = array[offset + 2]; result.a = array[offset + 3]; } /** * Creates a new Color3 from integer values (less than 256) * @param r defines the red component to read from (value between 0 and 255) * @param g defines the green component to read from (value between 0 and 255) * @param b defines the blue component to read from (value between 0 and 255) * @param a defines the alpha component to read from (value between 0 and 255) * @returns a new Color3 object */ static FromInts(r, g, b, a) { return new _Color4(r / 255, g / 255, b / 255, a / 255); } /** * Check the content of a given array and convert it to an array containing RGBA data * If the original array was already containing count * 4 values then it is returned directly * @param colors defines the array to check * @param count defines the number of RGBA data to expect * @returns an array containing count * 4 values (RGBA) */ static CheckColors4(colors, count) { if (colors.length === count * 3) { const colors4 = []; for (let index = 0; index < colors.length; index += 3) { const newIndex = index / 3 * 4; colors4[newIndex] = colors[index]; colors4[newIndex + 1] = colors[index + 1]; colors4[newIndex + 2] = colors[index + 2]; colors4[newIndex + 3] = 1; } return colors4; } return colors; } }; Color4._V8PerformanceHack = new Color4(0.5, 0.5, 0.5, 0.5); Object.defineProperties(Color4.prototype, { dimension: { value: [4] }, rank: { value: 1 } }); TmpColors = class { static { __name(this, "TmpColors"); } }; TmpColors.Color3 = BuildArray(3, Color3.Black); TmpColors.Color4 = BuildArray(3, () => new Color4(0, 0, 0, 0)); RegisterClass("BABYLON.Color3", Color3); RegisterClass("BABYLON.Color4", Color4); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.plane.js var Plane; var init_math_plane = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.plane.js"() { init_math_vector(); Plane = class _Plane { static { __name(this, "Plane"); } /** * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0 * @param a a component of the plane * @param b b component of the plane * @param c c component of the plane * @param d d component of the plane */ constructor(a, b, c, d) { this.normal = new Vector3(a, b, c); this.d = d; } /** * @returns the plane coordinates as a new array of 4 elements [a, b, c, d]. */ asArray() { return [this.normal.x, this.normal.y, this.normal.z, this.d]; } // Methods /** * @returns a new plane copied from the current Plane. */ clone() { return new _Plane(this.normal.x, this.normal.y, this.normal.z, this.d); } /** * @returns the string "Plane". */ getClassName() { return "Plane"; } /** * @returns the Plane hash code. */ getHashCode() { let hash = this.normal.getHashCode(); hash = hash * 397 ^ (this.d | 0); return hash; } /** * Normalize the current Plane in place. * @returns the updated Plane. */ normalize() { const norm = Math.sqrt(this.normal.x * this.normal.x + this.normal.y * this.normal.y + this.normal.z * this.normal.z); let magnitude = 0; if (norm !== 0) { magnitude = 1 / norm; } this.normal.x *= magnitude; this.normal.y *= magnitude; this.normal.z *= magnitude; this.d *= magnitude; return this; } /** * Applies a transformation the plane and returns the result * @param transformation the transformation matrix to be applied to the plane * @returns a new Plane as the result of the transformation of the current Plane by the given matrix. */ transform(transformation) { const invertedMatrix = _Plane._TmpMatrix; transformation.invertToRef(invertedMatrix); const m = invertedMatrix.m; const x = this.normal.x; const y = this.normal.y; const z = this.normal.z; const d = this.d; const normalX = x * m[0] + y * m[1] + z * m[2] + d * m[3]; const normalY = x * m[4] + y * m[5] + z * m[6] + d * m[7]; const normalZ = x * m[8] + y * m[9] + z * m[10] + d * m[11]; const finalD = x * m[12] + y * m[13] + z * m[14] + d * m[15]; return new _Plane(normalX, normalY, normalZ, finalD); } /** * Compute the dot product between the point and the plane normal * @param point point to calculate the dot product with * @returns the dot product (float) of the point coordinates and the plane normal. */ dotCoordinate(point) { return this.normal.x * point.x + this.normal.y * point.y + this.normal.z * point.z + this.d; } /** * Updates the current Plane from the plane defined by the three given points. * @param point1 one of the points used to construct the plane * @param point2 one of the points used to construct the plane * @param point3 one of the points used to construct the plane * @returns the updated Plane. */ copyFromPoints(point1, point2, point3) { const x1 = point2.x - point1.x; const y1 = point2.y - point1.y; const z1 = point2.z - point1.z; const x2 = point3.x - point1.x; const y2 = point3.y - point1.y; const z2 = point3.z - point1.z; const yz = y1 * z2 - z1 * y2; const xz = z1 * x2 - x1 * z2; const xy = x1 * y2 - y1 * x2; const pyth = Math.sqrt(yz * yz + xz * xz + xy * xy); let invPyth; if (pyth !== 0) { invPyth = 1 / pyth; } else { invPyth = 0; } this.normal.x = yz * invPyth; this.normal.y = xz * invPyth; this.normal.z = xy * invPyth; this.d = -(this.normal.x * point1.x + this.normal.y * point1.y + this.normal.z * point1.z); return this; } /** * Checks if the plane is facing a given direction (meaning if the plane's normal is pointing in the opposite direction of the given vector). * Note that for this function to work as expected you should make sure that: * - direction and the plane normal are normalized * - epsilon is a number just bigger than -1, something like -0.99 for eg * @param direction the direction to check if the plane is facing * @param epsilon value the dot product is compared against (returns true if dot <= epsilon) * @returns True if the plane is facing the given direction */ isFrontFacingTo(direction, epsilon) { const dot = Vector3.Dot(this.normal, direction); return dot <= epsilon; } /** * Calculates the distance to a point * @param point point to calculate distance to * @returns the signed distance (float) from the given point to the Plane. */ signedDistanceTo(point) { return Vector3.Dot(point, this.normal) + this.d; } // Statics /** * Creates a plane from an array * @param array the array to create a plane from * @returns a new Plane from the given array. */ static FromArray(array) { return new _Plane(array[0], array[1], array[2], array[3]); } /** * Creates a plane from three points * @param point1 point used to create the plane * @param point2 point used to create the plane * @param point3 point used to create the plane * @returns a new Plane defined by the three given points. */ static FromPoints(point1, point2, point3) { const result = new _Plane(0, 0, 0, 0); result.copyFromPoints(point1, point2, point3); return result; } /** * Creates a plane from an origin point and a normal * @param origin origin of the plane to be constructed * @param normal normal of the plane to be constructed * @returns a new Plane the normal vector to this plane at the given origin point. */ static FromPositionAndNormal(origin, normal) { const plane = new _Plane(0, 0, 0, 0); return this.FromPositionAndNormalToRef(origin, normal, plane); } /** * Updates the given Plane "result" from an origin point and a normal. * @param origin origin of the plane to be constructed * @param normal the normalized normals of the plane to be constructed * @param result defines the Plane where to store the result * @returns result input */ static FromPositionAndNormalToRef(origin, normal, result) { result.normal.copyFrom(normal); result.normal.normalize(); result.d = -origin.dot(result.normal); return result; } /** * Calculates the distance from a plane and a point * @param origin origin of the plane to be constructed * @param normal normal of the plane to be constructed * @param point point to calculate distance to * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point. */ static SignedDistanceToPlaneFromPositionAndNormal(origin, normal, point) { const d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z); return Vector3.Dot(point, normal) + d; } }; Plane._TmpMatrix = Matrix.Identity(); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.frustum.js var Frustum; var init_math_frustum = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.frustum.js"() { init_math_plane(); Frustum = class _Frustum { static { __name(this, "Frustum"); } /** * Gets the planes representing the frustum * @param transform matrix to be applied to the returned planes * @returns a new array of 6 Frustum planes computed by the given transformation matrix. */ static GetPlanes(transform) { const frustumPlanes = []; for (let index = 0; index < 6; index++) { frustumPlanes.push(new Plane(0, 0, 0, 0)); } _Frustum.GetPlanesToRef(transform, frustumPlanes); return frustumPlanes; } /** * Gets the near frustum plane transformed by the transform matrix * @param transform transformation matrix to be applied to the resulting frustum plane * @param frustumPlane the resulting frustum plane */ static GetNearPlaneToRef(transform, frustumPlane) { const m = transform.m; frustumPlane.normal.x = m[3] + m[2]; frustumPlane.normal.y = m[7] + m[6]; frustumPlane.normal.z = m[11] + m[10]; frustumPlane.d = m[15] + m[14]; frustumPlane.normalize(); } /** * Gets the far frustum plane transformed by the transform matrix * @param transform transformation matrix to be applied to the resulting frustum plane * @param frustumPlane the resulting frustum plane */ static GetFarPlaneToRef(transform, frustumPlane) { const m = transform.m; frustumPlane.normal.x = m[3] - m[2]; frustumPlane.normal.y = m[7] - m[6]; frustumPlane.normal.z = m[11] - m[10]; frustumPlane.d = m[15] - m[14]; frustumPlane.normalize(); } /** * Gets the left frustum plane transformed by the transform matrix * @param transform transformation matrix to be applied to the resulting frustum plane * @param frustumPlane the resulting frustum plane */ static GetLeftPlaneToRef(transform, frustumPlane) { const m = transform.m; frustumPlane.normal.x = m[3] + m[0]; frustumPlane.normal.y = m[7] + m[4]; frustumPlane.normal.z = m[11] + m[8]; frustumPlane.d = m[15] + m[12]; frustumPlane.normalize(); } /** * Gets the right frustum plane transformed by the transform matrix * @param transform transformation matrix to be applied to the resulting frustum plane * @param frustumPlane the resulting frustum plane */ static GetRightPlaneToRef(transform, frustumPlane) { const m = transform.m; frustumPlane.normal.x = m[3] - m[0]; frustumPlane.normal.y = m[7] - m[4]; frustumPlane.normal.z = m[11] - m[8]; frustumPlane.d = m[15] - m[12]; frustumPlane.normalize(); } /** * Gets the top frustum plane transformed by the transform matrix * @param transform transformation matrix to be applied to the resulting frustum plane * @param frustumPlane the resulting frustum plane */ static GetTopPlaneToRef(transform, frustumPlane) { const m = transform.m; frustumPlane.normal.x = m[3] - m[1]; frustumPlane.normal.y = m[7] - m[5]; frustumPlane.normal.z = m[11] - m[9]; frustumPlane.d = m[15] - m[13]; frustumPlane.normalize(); } /** * Gets the bottom frustum plane transformed by the transform matrix * @param transform transformation matrix to be applied to the resulting frustum plane * @param frustumPlane the resulting frustum plane */ static GetBottomPlaneToRef(transform, frustumPlane) { const m = transform.m; frustumPlane.normal.x = m[3] + m[1]; frustumPlane.normal.y = m[7] + m[5]; frustumPlane.normal.z = m[11] + m[9]; frustumPlane.d = m[15] + m[13]; frustumPlane.normalize(); } /** * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix. * @param transform transformation matrix to be applied to the resulting frustum planes * @param frustumPlanes the resulting frustum planes */ static GetPlanesToRef(transform, frustumPlanes) { _Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]); _Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]); _Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]); _Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]); _Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]); _Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]); } /** * Tests if a point is located between the frustum planes. * @param point defines the point to test * @param frustumPlanes defines the frustum planes to test * @returns true if the point is located between the frustum planes */ static IsPointInFrustum(point, frustumPlanes) { for (let i = 0; i < 6; i++) { if (frustumPlanes[i].dotCoordinate(point) < 0) { return false; } } return true; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.path.js var Orientation, BezierCurve, Angle, Arc2, Path2, Path3D, Curve3; var init_math_path = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.path.js"() { init_math_scalar_functions(); init_math_vector(); init_math_constants(); (function(Orientation2) { Orientation2[Orientation2["CW"] = 0] = "CW"; Orientation2[Orientation2["CCW"] = 1] = "CCW"; })(Orientation || (Orientation = {})); BezierCurve = class { static { __name(this, "BezierCurve"); } /** * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats * @param t defines the time * @param x1 defines the left coordinate on X axis * @param y1 defines the left coordinate on Y axis * @param x2 defines the right coordinate on X axis * @param y2 defines the right coordinate on Y axis * @returns the interpolated value */ static Interpolate(t, x1, y1, x2, y2) { if (t === 0) { return 0; } const f0 = 1 - 3 * x2 + 3 * x1; const f1 = 3 * x2 - 6 * x1; const f2 = 3 * x1; let refinedT = t; for (let i = 0; i < 5; i++) { const refinedT2 = refinedT * refinedT; const refinedT3 = refinedT2 * refinedT; const x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT; const slope = 1 / (3 * f0 * refinedT2 + 2 * f1 * refinedT + f2); refinedT -= (x - t) * slope; refinedT = Math.min(1, Math.max(0, refinedT)); } return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3); } }; Angle = class _Angle { static { __name(this, "Angle"); } /** * Creates an Angle object of "radians" radians (float). * @param radians the angle in radians */ constructor(radians) { this._radians = radians; if (this._radians < 0) { this._radians += 2 * Math.PI; } } /** * Get value in degrees * @returns the Angle value in degrees (float) */ degrees() { return this._radians * 180 / Math.PI; } /** * Get value in radians * @returns the Angle value in radians (float) */ radians() { return this._radians; } /** * Gets a new Angle object with a value of the angle (in radians) between the line connecting the two points and the x-axis * @param a defines first point as the origin * @param b defines point * @returns a new Angle */ static BetweenTwoPoints(a, b) { const delta = b.subtract(a); const theta = Math.atan2(delta.y, delta.x); return new _Angle(theta); } /** * Gets the angle between the two vectors * @param a defines first vector * @param b defines vector * @returns Returns an new Angle between 0 and PI */ static BetweenTwoVectors(a, b) { let product = a.lengthSquared() * b.lengthSquared(); if (product === 0) { return new _Angle(Math.PI / 2); } product = Math.sqrt(product); let cosVal = a.dot(b) / product; cosVal = Clamp(cosVal, -1, 1); const angle = Math.acos(cosVal); return new _Angle(angle); } /** * Gets a new Angle object from the given float in radians * @param radians defines the angle value in radians * @returns a new Angle */ static FromRadians(radians) { return new _Angle(radians); } /** * Gets a new Angle object from the given float in degrees * @param degrees defines the angle value in degrees * @returns a new Angle */ static FromDegrees(degrees) { return new _Angle(degrees * Math.PI / 180); } }; Arc2 = class { static { __name(this, "Arc2"); } /** * Creates an Arc object from the three given points : start, middle and end. * @param startPoint Defines the start point of the arc * @param midPoint Defines the middle point of the arc * @param endPoint Defines the end point of the arc */ constructor(startPoint, midPoint, endPoint) { this.startPoint = startPoint; this.midPoint = midPoint; this.endPoint = endPoint; const temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2); const startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2; const midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2; const det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y); this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det); this.radius = this.centerPoint.subtract(this.startPoint).length(); this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint); const a1 = this.startAngle.degrees(); let a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees(); let a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees(); if (a2 - a1 > 180) { a2 -= 360; } if (a2 - a1 < -180) { a2 += 360; } if (a3 - a2 > 180) { a3 -= 360; } if (a3 - a2 < -180) { a3 += 360; } this.orientation = a2 - a1 < 0 ? 0 : 1; this.angle = Angle.FromDegrees(this.orientation === 0 ? a1 - a3 : a3 - a1); } }; Path2 = class _Path2 { static { __name(this, "Path2"); } /** * Creates a Path2 object from the starting 2D coordinates x and y. * @param x the starting points x value * @param y the starting points y value */ constructor(x, y) { this._points = new Array(); this._length = 0; this.closed = false; this._points.push(new Vector2(x, y)); } /** * Adds a new segment until the given coordinates (x, y) to the current Path2. * @param x the added points x value * @param y the added points y value * @returns the updated Path2. */ addLineTo(x, y) { if (this.closed) { return this; } const newPoint = new Vector2(x, y); const previousPoint = this._points[this._points.length - 1]; this._points.push(newPoint); this._length += newPoint.subtract(previousPoint).length(); return this; } /** * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2. * @param midX middle point x value * @param midY middle point y value * @param endX end point x value * @param endY end point y value * @param numberOfSegments (default: 36) * @returns the updated Path2. */ addArcTo(midX, midY, endX, endY, numberOfSegments = 36) { if (this.closed) { return this; } const startPoint = this._points[this._points.length - 1]; const midPoint = new Vector2(midX, midY); const endPoint = new Vector2(endX, endY); const arc = new Arc2(startPoint, midPoint, endPoint); let increment = arc.angle.radians() / numberOfSegments; if (arc.orientation === 0) { increment *= -1; } let currentAngle = arc.startAngle.radians() + increment; for (let i = 0; i < numberOfSegments; i++) { const x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x; const y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y; this.addLineTo(x, y); currentAngle += increment; } return this; } /** * Adds _numberOfSegments_ segments according to the quadratic curve definition to the current Path2. * @param controlX control point x value * @param controlY control point y value * @param endX end point x value * @param endY end point y value * @param numberOfSegments (default: 36) * @returns the updated Path2. */ addQuadraticCurveTo(controlX, controlY, endX, endY, numberOfSegments = 36) { if (this.closed) { return this; } const equation = /* @__PURE__ */ __name((t, val0, val1, val2) => { const res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2; return res; }, "equation"); const startPoint = this._points[this._points.length - 1]; for (let i = 0; i <= numberOfSegments; i++) { const step = i / numberOfSegments; const x = equation(step, startPoint.x, controlX, endX); const y = equation(step, startPoint.y, controlY, endY); this.addLineTo(x, y); } return this; } /** * Adds _numberOfSegments_ segments according to the bezier curve definition to the current Path2. * @param originTangentX tangent vector at the origin point x value * @param originTangentY tangent vector at the origin point y value * @param destinationTangentX tangent vector at the destination point x value * @param destinationTangentY tangent vector at the destination point y value * @param endX end point x value * @param endY end point y value * @param numberOfSegments (default: 36) * @returns the updated Path2. */ addBezierCurveTo(originTangentX, originTangentY, destinationTangentX, destinationTangentY, endX, endY, numberOfSegments = 36) { if (this.closed) { return this; } const equation = /* @__PURE__ */ __name((t, val0, val1, val2, val3) => { const res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3; return res; }, "equation"); const startPoint = this._points[this._points.length - 1]; for (let i = 0; i <= numberOfSegments; i++) { const step = i / numberOfSegments; const x = equation(step, startPoint.x, originTangentX, destinationTangentX, endX); const y = equation(step, startPoint.y, originTangentY, destinationTangentY, endY); this.addLineTo(x, y); } return this; } /** * Defines if a given point is inside the polygon defines by the path * @param point defines the point to test * @returns true if the point is inside */ isPointInside(point) { let isInside = false; const count = this._points.length; for (let p = count - 1, q = 0; q < count; p = q++) { let edgeLow = this._points[p]; let edgeHigh = this._points[q]; let edgeDx = edgeHigh.x - edgeLow.x; let edgeDy = edgeHigh.y - edgeLow.y; if (Math.abs(edgeDy) > Number.EPSILON) { if (edgeDy < 0) { edgeLow = this._points[q]; edgeDx = -edgeDx; edgeHigh = this._points[p]; edgeDy = -edgeDy; } if (point.y < edgeLow.y || point.y > edgeHigh.y) { continue; } if (point.y === edgeLow.y && point.x === edgeLow.x) { return true; } else { const perpEdge = edgeDy * (point.x - edgeLow.x) - edgeDx * (point.y - edgeLow.y); if (perpEdge === 0) { return true; } if (perpEdge < 0) { continue; } isInside = !isInside; } } else { if (point.y !== edgeLow.y) { continue; } if (edgeHigh.x <= point.x && point.x <= edgeLow.x || edgeLow.x <= point.x && point.x <= edgeHigh.x) { return true; } } } return isInside; } /** * Closes the Path2. * @returns the Path2. */ close() { this.closed = true; return this; } /** * Gets the sum of the distance between each sequential point in the path * @returns the Path2 total length (float). */ length() { let result = this._length; if (this.closed) { const lastPoint = this._points[this._points.length - 1]; const firstPoint = this._points[0]; result += firstPoint.subtract(lastPoint).length(); } return result; } /** * Gets the area of the polygon defined by the path * @returns area value */ area() { const n = this._points.length; let value = 0; for (let p = n - 1, q = 0; q < n; p = q++) { value += this._points[p].x * this._points[q].y - this._points[q].x * this._points[p].y; } return value * 0.5; } /** * Gets the points which construct the path * @returns the Path2 internal array of points. */ getPoints() { return this._points; } /** * Retrieves the point at the distance aways from the starting point * @param normalizedLengthPosition the length along the path to retrieve the point from * @returns a new Vector2 located at a percentage of the Path2 total length on this path. */ getPointAtLengthPosition(normalizedLengthPosition) { if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) { return Vector2.Zero(); } const lengthPosition = normalizedLengthPosition * this.length(); let previousOffset = 0; for (let i = 0; i < this._points.length; i++) { const j = (i + 1) % this._points.length; const a = this._points[i]; const b = this._points[j]; const bToA = b.subtract(a); const nextOffset = bToA.length() + previousOffset; if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) { const dir = bToA.normalize(); const localOffset = lengthPosition - previousOffset; return new Vector2(a.x + dir.x * localOffset, a.y + dir.y * localOffset); } previousOffset = nextOffset; } return Vector2.Zero(); } /** * Creates a new path starting from an x and y position * @param x starting x value * @param y starting y value * @returns a new Path2 starting at the coordinates (x, y). */ static StartingAt(x, y) { return new _Path2(x, y); } }; Path3D = class _Path3D { static { __name(this, "Path3D"); } /** * new Path3D(path, normal, raw) * Creates a Path3D. A Path3D is a logical math object, so not a mesh. * please read the description in the tutorial : https://doc.babylonjs.com/features/featuresDeepDive/mesh/path3D * @param path an array of Vector3, the curve axis of the Path3D * @param firstNormal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed. * @param alignTangentsWithPath (optional, default false) : boolean, if true the tangents will be aligned with the path. */ constructor(path, firstNormal = null, raw, alignTangentsWithPath = false) { this.path = path; this._curve = new Array(); this._distances = new Array(); this._tangents = new Array(); this._normals = new Array(); this._binormals = new Array(); this._pointAtData = { id: 0, point: Vector3.Zero(), previousPointArrayIndex: 0, position: 0, subPosition: 0, interpolateReady: false, interpolationMatrix: Matrix.Identity() }; for (let p = 0; p < path.length; p++) { this._curve[p] = path[p].clone(); } this._raw = raw || false; this._alignTangentsWithPath = alignTangentsWithPath; this._compute(firstNormal, alignTangentsWithPath); } /** * Returns the Path3D array of successive Vector3 designing its curve. * @returns the Path3D array of successive Vector3 designing its curve. */ getCurve() { return this._curve; } /** * Returns the Path3D array of successive Vector3 designing its curve. * @returns the Path3D array of successive Vector3 designing its curve. */ getPoints() { return this._curve; } /** * @returns the computed length (float) of the path. */ length() { return this._distances[this._distances.length - 1]; } /** * Returns an array populated with tangent vectors on each Path3D curve point. * @returns an array populated with tangent vectors on each Path3D curve point. */ getTangents() { return this._tangents; } /** * Returns an array populated with normal vectors on each Path3D curve point. * @returns an array populated with normal vectors on each Path3D curve point. */ getNormals() { return this._normals; } /** * Returns an array populated with binormal vectors on each Path3D curve point. * @returns an array populated with binormal vectors on each Path3D curve point. */ getBinormals() { return this._binormals; } /** * Returns an array populated with distances (float) of the i-th point from the first curve point. * @returns an array populated with distances (float) of the i-th point from the first curve point. */ getDistances() { return this._distances; } /** * Returns an interpolated point along this path * @param position the position of the point along this path, from 0.0 to 1.0 * @returns a new Vector3 as the point */ getPointAt(position) { return this._updatePointAtData(position).point; } /** * Returns the tangent vector of an interpolated Path3D curve point at the specified position along this path. * @param position the position of the point along this path, from 0.0 to 1.0 * @param interpolated (optional, default false) : boolean, if true returns an interpolated tangent instead of the tangent of the previous path point. * @returns a tangent vector corresponding to the interpolated Path3D curve point, if not interpolated, the tangent is taken from the precomputed tangents array. */ getTangentAt(position, interpolated = false) { this._updatePointAtData(position, interpolated); return interpolated ? Vector3.TransformCoordinates(Vector3.Forward(), this._pointAtData.interpolationMatrix) : this._tangents[this._pointAtData.previousPointArrayIndex]; } /** * Returns the tangent vector of an interpolated Path3D curve point at the specified position along this path. * @param position the position of the point along this path, from 0.0 to 1.0 * @param interpolated (optional, default false) : boolean, if true returns an interpolated normal instead of the normal of the previous path point. * @returns a normal vector corresponding to the interpolated Path3D curve point, if not interpolated, the normal is taken from the precomputed normals array. */ getNormalAt(position, interpolated = false) { this._updatePointAtData(position, interpolated); return interpolated ? Vector3.TransformCoordinates(Vector3.Right(), this._pointAtData.interpolationMatrix) : this._normals[this._pointAtData.previousPointArrayIndex]; } /** * Returns the binormal vector of an interpolated Path3D curve point at the specified position along this path. * @param position the position of the point along this path, from 0.0 to 1.0 * @param interpolated (optional, default false) : boolean, if true returns an interpolated binormal instead of the binormal of the previous path point. * @returns a binormal vector corresponding to the interpolated Path3D curve point, if not interpolated, the binormal is taken from the precomputed binormals array. */ getBinormalAt(position, interpolated = false) { this._updatePointAtData(position, interpolated); return interpolated ? Vector3.TransformCoordinates(Vector3.UpReadOnly, this._pointAtData.interpolationMatrix) : this._binormals[this._pointAtData.previousPointArrayIndex]; } /** * Returns the distance (float) of an interpolated Path3D curve point at the specified position along this path. * @param position the position of the point along this path, from 0.0 to 1.0 * @returns the distance of the interpolated Path3D curve point at the specified position along this path. */ getDistanceAt(position) { return this.length() * position; } /** * Returns the array index of the previous point of an interpolated point along this path * @param position the position of the point to interpolate along this path, from 0.0 to 1.0 * @returns the array index */ getPreviousPointIndexAt(position) { this._updatePointAtData(position); return this._pointAtData.previousPointArrayIndex; } /** * Returns the position of an interpolated point relative to the two path points it lies between, from 0.0 (point A) to 1.0 (point B) * @param position the position of the point to interpolate along this path, from 0.0 to 1.0 * @returns the sub position */ getSubPositionAt(position) { this._updatePointAtData(position); return this._pointAtData.subPosition; } /** * Returns the position of the closest virtual point on this path to an arbitrary Vector3, from 0.0 to 1.0 * @param target the vector of which to get the closest position to * @returns the position of the closest virtual point on this path to the target vector */ getClosestPositionTo(target) { let smallestDistance = Number.MAX_VALUE; let closestPosition = 0; for (let i = 0; i < this._curve.length - 1; i++) { const point = this._curve[i + 0]; const tangent = this._curve[i + 1].subtract(point).normalize(); const subLength = this._distances[i + 1] - this._distances[i + 0]; const subPosition = Math.min(Math.max(Vector3.Dot(tangent, target.subtract(point).normalize()), 0) * Vector3.Distance(point, target) / subLength, 1); const distance = Vector3.Distance(point.add(tangent.scale(subPosition * subLength)), target); if (distance < smallestDistance) { smallestDistance = distance; closestPosition = (this._distances[i + 0] + subLength * subPosition) / this.length(); } } return closestPosition; } /** * Returns a sub path (slice) of this path * @param start the position of the fist path point, from 0.0 to 1.0, or a negative value, which will get wrapped around from the end of the path to 0.0 to 1.0 values * @param end the position of the last path point, from 0.0 to 1.0, or a negative value, which will get wrapped around from the end of the path to 0.0 to 1.0 values * @returns a sub path (slice) of this path */ slice(start = 0, end = 1) { if (start < 0) { start = 1 - start * -1 % 1; } if (end < 0) { end = 1 - end * -1 % 1; } if (start > end) { const _start = start; start = end; end = _start; } const curvePoints = this.getCurve(); const startPoint = this.getPointAt(start); let startIndex = this.getPreviousPointIndexAt(start); const endPoint = this.getPointAt(end); const endIndex = this.getPreviousPointIndexAt(end) + 1; const slicePoints = []; if (start !== 0) { startIndex++; slicePoints.push(startPoint); } slicePoints.push(...curvePoints.slice(startIndex, endIndex)); if (end !== 1 || start === 1) { slicePoints.push(endPoint); } return new _Path3D(slicePoints, this.getNormalAt(start), this._raw, this._alignTangentsWithPath); } /** * Forces the Path3D tangent, normal, binormal and distance recomputation. * @param path path which all values are copied into the curves points * @param firstNormal which should be projected onto the curve * @param alignTangentsWithPath (optional, default false) : boolean, if true the tangents will be aligned with the path * @returns the same object updated. */ update(path, firstNormal = null, alignTangentsWithPath = false) { for (let p = 0; p < path.length; p++) { this._curve[p].x = path[p].x; this._curve[p].y = path[p].y; this._curve[p].z = path[p].z; } this._compute(firstNormal, alignTangentsWithPath); return this; } // private function compute() : computes tangents, normals and binormals _compute(firstNormal, alignTangentsWithPath = false) { const l = this._curve.length; if (l < 2) { return; } this._tangents[0] = this._getFirstNonNullVector(0); if (!this._raw) { this._tangents[0].normalize(); } this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]); if (!this._raw) { this._tangents[l - 1].normalize(); } const tg0 = this._tangents[0]; const pp0 = this._normalVector(tg0, firstNormal); this._normals[0] = pp0; if (!this._raw) { this._normals[0].normalize(); } this._binormals[0] = Vector3.Cross(tg0, this._normals[0]); if (!this._raw) { this._binormals[0].normalize(); } this._distances[0] = 0; let prev; let cur; let curTang; let prevNor; let prevBinor; for (let i = 1; i < l; i++) { prev = this._getLastNonNullVector(i); if (i < l - 1) { cur = this._getFirstNonNullVector(i); this._tangents[i] = alignTangentsWithPath ? cur : prev.add(cur); this._tangents[i].normalize(); } this._distances[i] = this._distances[i - 1] + this._curve[i].subtract(this._curve[i - 1]).length(); curTang = this._tangents[i]; prevBinor = this._binormals[i - 1]; this._normals[i] = Vector3.Cross(prevBinor, curTang); if (!this._raw) { if (this._normals[i].length() === 0) { prevNor = this._normals[i - 1]; this._normals[i] = prevNor.clone(); } else { this._normals[i].normalize(); } } this._binormals[i] = Vector3.Cross(curTang, this._normals[i]); if (!this._raw) { this._binormals[i].normalize(); } } this._pointAtData.id = NaN; } // private function getFirstNonNullVector(index) // returns the first non null vector from index : curve[index + N].subtract(curve[index]) _getFirstNonNullVector(index) { let i = 1; let nNVector = this._curve[index + i].subtract(this._curve[index]); while (nNVector.length() === 0 && index + i + 1 < this._curve.length) { i++; nNVector = this._curve[index + i].subtract(this._curve[index]); } return nNVector; } // private function getLastNonNullVector(index) // returns the last non null vector from index : curve[index].subtract(curve[index - N]) _getLastNonNullVector(index) { let i = 1; let nLVector = this._curve[index].subtract(this._curve[index - i]); while (nLVector.length() === 0 && index > i + 1) { i++; nLVector = this._curve[index].subtract(this._curve[index - i]); } return nLVector; } // private function normalVector(v0, vt, va) : // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0 _normalVector(vt, va) { let normal0; let tgl = vt.length(); if (tgl === 0) { tgl = 1; } if (va === void 0 || va === null) { let point; if (!WithinEpsilon(Math.abs(vt.y) / tgl, 1, Epsilon)) { point = new Vector3(0, -1, 0); } else if (!WithinEpsilon(Math.abs(vt.x) / tgl, 1, Epsilon)) { point = new Vector3(1, 0, 0); } else if (!WithinEpsilon(Math.abs(vt.z) / tgl, 1, Epsilon)) { point = new Vector3(0, 0, 1); } else { point = Vector3.Zero(); } normal0 = Vector3.Cross(vt, point); } else { normal0 = Vector3.Cross(vt, va); Vector3.CrossToRef(normal0, vt, normal0); } normal0.normalize(); return normal0; } /** * Updates the point at data for an interpolated point along this curve * @param position the position of the point along this curve, from 0.0 to 1.0 * @param interpolateTNB * @interpolateTNB whether to compute the interpolated tangent, normal and binormal * @returns the (updated) point at data */ _updatePointAtData(position, interpolateTNB = false) { if (this._pointAtData.id === position) { if (!this._pointAtData.interpolateReady) { this._updateInterpolationMatrix(); } return this._pointAtData; } else { this._pointAtData.id = position; } const curvePoints = this.getPoints(); if (position <= 0) { return this._setPointAtData(0, 0, curvePoints[0], 0, interpolateTNB); } else if (position >= 1) { return this._setPointAtData(1, 1, curvePoints[curvePoints.length - 1], curvePoints.length - 1, interpolateTNB); } let previousPoint = curvePoints[0]; let currentPoint; let currentLength = 0; const targetLength = position * this.length(); for (let i = 1; i < curvePoints.length; i++) { currentPoint = curvePoints[i]; const distance = Vector3.Distance(previousPoint, currentPoint); currentLength += distance; if (currentLength === targetLength) { return this._setPointAtData(position, 1, currentPoint, i, interpolateTNB); } else if (currentLength > targetLength) { const toLength = currentLength - targetLength; const diff = toLength / distance; const dir = previousPoint.subtract(currentPoint); const point = currentPoint.add(dir.scaleInPlace(diff)); return this._setPointAtData(position, 1 - diff, point, i - 1, interpolateTNB); } previousPoint = currentPoint; } return this._pointAtData; } /** * Updates the point at data from the specified parameters * @param position where along the path the interpolated point is, from 0.0 to 1.0 * @param subPosition * @param point the interpolated point * @param parentIndex the index of an existing curve point that is on, or else positionally the first behind, the interpolated point * @param interpolateTNB whether to compute the interpolated tangent, normal and binormal * @returns the (updated) point at data */ _setPointAtData(position, subPosition, point, parentIndex, interpolateTNB) { this._pointAtData.point = point; this._pointAtData.position = position; this._pointAtData.subPosition = subPosition; this._pointAtData.previousPointArrayIndex = parentIndex; this._pointAtData.interpolateReady = interpolateTNB; if (interpolateTNB) { this._updateInterpolationMatrix(); } return this._pointAtData; } /** * Updates the point at interpolation matrix for the tangents, normals and binormals */ _updateInterpolationMatrix() { this._pointAtData.interpolationMatrix = Matrix.Identity(); const parentIndex = this._pointAtData.previousPointArrayIndex; if (parentIndex !== this._tangents.length - 1) { const index = parentIndex + 1; const tangentFrom = this._tangents[parentIndex].clone(); const normalFrom = this._normals[parentIndex].clone(); const binormalFrom = this._binormals[parentIndex].clone(); const tangentTo = this._tangents[index].clone(); const normalTo = this._normals[index].clone(); const binormalTo = this._binormals[index].clone(); const quatFrom = Quaternion.RotationQuaternionFromAxis(normalFrom, binormalFrom, tangentFrom); const quatTo = Quaternion.RotationQuaternionFromAxis(normalTo, binormalTo, tangentTo); const quatAt = Quaternion.Slerp(quatFrom, quatTo, this._pointAtData.subPosition); quatAt.toRotationMatrix(this._pointAtData.interpolationMatrix); } } }; Curve3 = class _Curve3 { static { __name(this, "Curve3"); } /** * Returns a Curve3 object along a Quadratic Bezier curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#quadratic-bezier-curve * @param v0 (Vector3) the origin point of the Quadratic Bezier * @param v1 (Vector3) the control point * @param v2 (Vector3) the end point of the Quadratic Bezier * @param nbPoints (integer) the wanted number of points in the curve * @returns the created Curve3 */ static CreateQuadraticBezier(v0, v1, v2, nbPoints) { nbPoints = nbPoints > 2 ? nbPoints : 3; const bez = []; const equation = /* @__PURE__ */ __name((t, val0, val1, val2) => { const res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2; return res; }, "equation"); for (let i = 0; i <= nbPoints; i++) { bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z))); } return new _Curve3(bez); } /** * Returns a Curve3 object along a Cubic Bezier curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#cubic-bezier-curve * @param v0 (Vector3) the origin point of the Cubic Bezier * @param v1 (Vector3) the first control point * @param v2 (Vector3) the second control point * @param v3 (Vector3) the end point of the Cubic Bezier * @param nbPoints (integer) the wanted number of points in the curve * @returns the created Curve3 */ static CreateCubicBezier(v0, v1, v2, v3, nbPoints) { nbPoints = nbPoints > 3 ? nbPoints : 4; const bez = []; const equation = /* @__PURE__ */ __name((t, val0, val1, val2, val3) => { const res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3; return res; }, "equation"); for (let i = 0; i <= nbPoints; i++) { bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z))); } return new _Curve3(bez); } /** * Returns a Curve3 object along a Hermite Spline curve : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#hermite-spline * @param p1 (Vector3) the origin point of the Hermite Spline * @param t1 (Vector3) the tangent vector at the origin point * @param p2 (Vector3) the end point of the Hermite Spline * @param t2 (Vector3) the tangent vector at the end point * @param nSeg (integer) the number of curve segments or nSeg + 1 points in the array * @returns the created Curve3 */ static CreateHermiteSpline(p1, t1, p2, t2, nSeg) { const hermite = []; const step = 1 / nSeg; for (let i = 0; i <= nSeg; i++) { hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step)); } return new _Curve3(hermite); } /** * Returns a Curve3 object along a CatmullRom Spline curve : * @param points (array of Vector3) the points the spline must pass through. At least, four points required * @param nbPoints (integer) the wanted number of points between each curve control points * @param closed (boolean) optional with default false, when true forms a closed loop from the points * @returns the created Curve3 */ static CreateCatmullRomSpline(points, nbPoints, closed) { const catmullRom = []; const step = 1 / nbPoints; let amount = 0; if (closed) { const pointsCount = points.length; for (let i = 0; i < pointsCount; i++) { amount = 0; for (let c = 0; c < nbPoints; c++) { catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount)); amount += step; } } catmullRom.push(catmullRom[0]); } else { const totalPoints = []; totalPoints.push(points[0].clone()); Array.prototype.push.apply(totalPoints, points); totalPoints.push(points[points.length - 1].clone()); let i = 0; for (; i < totalPoints.length - 3; i++) { amount = 0; for (let c = 0; c < nbPoints; c++) { catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount)); amount += step; } } i--; catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount)); } return new _Curve3(catmullRom); } /** * Returns a Curve3 object along an arc through three vector3 points: * The three points should not be colinear. When they are the Curve3 is empty. * @param first (Vector3) the first point the arc must pass through. * @param second (Vector3) the second point the arc must pass through. * @param third (Vector3) the third point the arc must pass through. * @param steps (number) the larger the number of steps the more detailed the arc. * @param closed (boolean) optional with default false, when true forms the chord from the first and third point * @param fullCircle Circle (boolean) optional with default false, when true forms the complete circle through the three points * @returns the created Curve3 */ static ArcThru3Points(first, second, third, steps = 32, closed = false, fullCircle = false) { const arc = []; const vec1 = second.subtract(first); const vec2 = third.subtract(second); const vec3 = first.subtract(third); const zAxis = Vector3.Cross(vec1, vec2); const len4 = zAxis.length(); if (len4 < Math.pow(10, -8)) { return new _Curve3(arc); } const len1Sq = vec1.lengthSquared(); const len2Sq = vec2.lengthSquared(); const len3Sq = vec3.lengthSquared(); const len4Sq = zAxis.lengthSquared(); const len1 = vec1.length(); const len2 = vec2.length(); const len3 = vec3.length(); const radius = 0.5 * len1 * len2 * len3 / len4; const dot1 = Vector3.Dot(vec1, vec3); const dot2 = Vector3.Dot(vec1, vec2); const dot3 = Vector3.Dot(vec2, vec3); const a = -0.5 * len2Sq * dot1 / len4Sq; const b = -0.5 * len3Sq * dot2 / len4Sq; const c = -0.5 * len1Sq * dot3 / len4Sq; const center = first.scale(a).add(second.scale(b)).add(third.scale(c)); const radiusVec = first.subtract(center); const xAxis = radiusVec.normalize(); const yAxis = Vector3.Cross(zAxis, xAxis).normalize(); if (fullCircle) { const dStep = 2 * Math.PI / steps; for (let theta = 0; theta <= 2 * Math.PI; theta += dStep) { arc.push(center.add(xAxis.scale(radius * Math.cos(theta)).add(yAxis.scale(radius * Math.sin(theta))))); } arc.push(first); } else { const dStep = 1 / steps; let theta = 0; let point = Vector3.Zero(); do { point = center.add(xAxis.scale(radius * Math.cos(theta)).add(yAxis.scale(radius * Math.sin(theta)))); arc.push(point); theta += dStep; } while (!point.equalsWithEpsilon(third, radius * dStep * 1.1)); arc.push(third); if (closed) { arc.push(first); } } return new _Curve3(arc); } /** * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space. * A Curve3 is designed from a series of successive Vector3. * Tuto : https://doc.babylonjs.com/features/featuresDeepDive/mesh/drawCurves#curve3-object * @param points points which make up the curve */ constructor(points) { this._length = 0; this._points = points; this._length = this._computeLength(points); } /** * @returns the Curve3 stored array of successive Vector3 */ getPoints() { return this._points; } /** * @returns the computed length (float) of the curve. */ length() { return this._length; } /** * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB); * This new Curve3 is built by translating and sticking the curveB at the end of the curveA. * curveA and curveB keep unchanged. * @param curve the curve to continue from this curve * @returns the newly constructed curve */ continue(curve) { const lastPoint = this._points[this._points.length - 1]; const continuedPoints = this._points.slice(); const curvePoints = curve.getPoints(); for (let i = 1; i < curvePoints.length; i++) { continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint)); } const continuedCurve = new _Curve3(continuedPoints); return continuedCurve; } _computeLength(path) { let l = 0; for (let i = 1; i < path.length; i++) { l += path[i].subtract(path[i - 1]).length(); } return l; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.size.js var Size; var init_math_size = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.size.js"() { Size = class _Size { static { __name(this, "Size"); } /** * Creates a Size object from the given width and height (floats). * @param width width of the new size * @param height height of the new size */ constructor(width, height) { this.width = width; this.height = height; } /** * Returns a string with the Size width and height * @returns a string with the Size width and height */ toString() { return `{W: ${this.width}, H: ${this.height}}`; } /** * "Size" * @returns the string "Size" */ getClassName() { return "Size"; } /** * Returns the Size hash code. * @returns a hash code for a unique width and height */ getHashCode() { let hash = this.width | 0; hash = hash * 397 ^ (this.height | 0); return hash; } /** * Updates the current size from the given one. * @param src the given size */ copyFrom(src) { this.width = src.width; this.height = src.height; } /** * Updates in place the current Size from the given floats. * @param width width of the new size * @param height height of the new size * @returns the updated Size. */ copyFromFloats(width, height) { this.width = width; this.height = height; return this; } /** * Updates in place the current Size from the given floats. * @param width width to set * @param height height to set * @returns the updated Size. */ set(width, height) { return this.copyFromFloats(width, height); } /** * Multiplies the width and height by numbers * @param w factor to multiple the width by * @param h factor to multiple the height by * @returns a new Size set with the multiplication result of the current Size and the given floats. */ multiplyByFloats(w, h) { return new _Size(this.width * w, this.height * h); } /** * Clones the size * @returns a new Size copied from the given one. */ clone() { return new _Size(this.width, this.height); } /** * True if the current Size and the given one width and height are strictly equal. * @param other the other size to compare against * @returns True if the current Size and the given one width and height are strictly equal. */ equals(other) { if (!other) { return false; } return this.width === other.width && this.height === other.height; } /** * The surface of the Size : width * height (float). */ get surface() { return this.width * this.height; } /** * Create a new size of zero * @returns a new Size set to (0.0, 0.0) */ static Zero() { return new _Size(0, 0); } /** * Sums the width and height of two sizes * @param otherSize size to add to this size * @returns a new Size set as the addition result of the current Size and the given one. */ add(otherSize) { const r = new _Size(this.width + otherSize.width, this.height + otherSize.height); return r; } /** * Subtracts the width and height of two * @param otherSize size to subtract to this size * @returns a new Size set as the subtraction result of the given one from the current Size. */ subtract(otherSize) { const r = new _Size(this.width - otherSize.width, this.height - otherSize.height); return r; } /** * Scales the width and height * @param scale the scale to multiply the width and height by * @returns a new Size set with the multiplication result of the current Size and the given floats. */ scale(scale) { return new _Size(this.width * scale, this.height * scale); } /** * Creates a new Size set at the linear interpolation "amount" between "start" and "end" * @param start starting size to lerp between * @param end end size to lerp between * @param amount amount to lerp between the start and end values * @returns a new Size set at the linear interpolation "amount" between "start" and "end" */ static Lerp(start, end, amount) { const w = start.width + (end.width - start.width) * amount; const h = start.height + (end.height - start.height) * amount; return new _Size(w, h); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.vertexFormat.js var PositionNormalVertex, PositionNormalTextureVertex; var init_math_vertexFormat = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.vertexFormat.js"() { init_math_vector(); PositionNormalVertex = class _PositionNormalVertex { static { __name(this, "PositionNormalVertex"); } /** * Creates a PositionNormalVertex * @param position the position of the vertex (defaut: 0,0,0) * @param normal the normal of the vertex (defaut: 0,1,0) */ constructor(position = Vector3.Zero(), normal = Vector3.Up()) { this.position = position; this.normal = normal; } /** * Clones the PositionNormalVertex * @returns the cloned PositionNormalVertex */ clone() { return new _PositionNormalVertex(this.position.clone(), this.normal.clone()); } }; PositionNormalTextureVertex = class _PositionNormalTextureVertex { static { __name(this, "PositionNormalTextureVertex"); } /** * Creates a PositionNormalTextureVertex * @param position the position of the vertex (defaut: 0,0,0) * @param normal the normal of the vertex (defaut: 0,1,0) * @param uv the uv of the vertex (default: 0,0) */ constructor(position = Vector3.Zero(), normal = Vector3.Up(), uv = Vector2.Zero()) { this.position = position; this.normal = normal; this.uv = uv; } /** * Clones the PositionNormalTextureVertex * @returns the cloned PositionNormalTextureVertex */ clone() { return new _PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone()); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.viewport.js var Viewport; var init_math_viewport = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.viewport.js"() { Viewport = class _Viewport { static { __name(this, "Viewport"); } /** * Creates a Viewport object located at (x, y) and sized (width, height) * @param x defines viewport left coordinate * @param y defines viewport top coordinate * @param width defines the viewport width * @param height defines the viewport height */ constructor(x, y, width, height) { this.x = x; this.y = y; this.width = width; this.height = height; } /** * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1) * @param renderWidth defines the rendering width * @param renderHeight defines the rendering height * @returns a new Viewport */ toGlobal(renderWidth, renderHeight) { return new _Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight); } /** * Stores absolute viewport value into a target viewport (from 0-> width, 0-> height instead of 0->1) * @param renderWidth defines the rendering width * @param renderHeight defines the rendering height * @param ref defines the target viewport * @returns the current viewport */ toGlobalToRef(renderWidth, renderHeight, ref) { ref.x = this.x * renderWidth; ref.y = this.y * renderHeight; ref.width = this.width * renderWidth; ref.height = this.height * renderHeight; return this; } /** * Returns a new Viewport copied from the current one * @returns a new Viewport */ clone() { return new _Viewport(this.x, this.y, this.width, this.height); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.js var init_math = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.js"() { init_math_axis(); init_math_color(); init_math_constants(); init_math_frustum(); init_math_path(); init_math_plane(); init_math_size(); init_math_vector(); init_math_vertexFormat(); init_math_viewport(); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/sphericalPolynomial.js var SH3ylmBasisConstants, SH3ylmBasisTrigonometricTerms, applySH3, SHCosKernelConvolution, SphericalHarmonics, SphericalPolynomial; var init_sphericalPolynomial = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/sphericalPolynomial.js"() { init_math_vector(); init_math(); SH3ylmBasisConstants = [ Math.sqrt(1 / (4 * Math.PI)), // l00 -Math.sqrt(3 / (4 * Math.PI)), // l1_1 Math.sqrt(3 / (4 * Math.PI)), // l10 -Math.sqrt(3 / (4 * Math.PI)), // l11 Math.sqrt(15 / (4 * Math.PI)), // l2_2 -Math.sqrt(15 / (4 * Math.PI)), // l2_1 Math.sqrt(5 / (16 * Math.PI)), // l20 -Math.sqrt(15 / (4 * Math.PI)), // l21 Math.sqrt(15 / (16 * Math.PI)) // l22 ]; SH3ylmBasisTrigonometricTerms = [ () => 1, // l00 (direction) => direction.y, // l1_1 (direction) => direction.z, // l10 (direction) => direction.x, // l11 (direction) => direction.x * direction.y, // l2_2 (direction) => direction.y * direction.z, // l2_1 (direction) => 3 * direction.z * direction.z - 1, // l20 (direction) => direction.x * direction.z, // l21 (direction) => direction.x * direction.x - direction.y * direction.y // l22 ]; applySH3 = /* @__PURE__ */ __name((lm, direction) => { return SH3ylmBasisConstants[lm] * SH3ylmBasisTrigonometricTerms[lm](direction); }, "applySH3"); SHCosKernelConvolution = [Math.PI, 2 * Math.PI / 3, 2 * Math.PI / 3, 2 * Math.PI / 3, Math.PI / 4, Math.PI / 4, Math.PI / 4, Math.PI / 4, Math.PI / 4]; SphericalHarmonics = class _SphericalHarmonics { static { __name(this, "SphericalHarmonics"); } constructor() { this.preScaled = false; this.l00 = Vector3.Zero(); this.l1_1 = Vector3.Zero(); this.l10 = Vector3.Zero(); this.l11 = Vector3.Zero(); this.l2_2 = Vector3.Zero(); this.l2_1 = Vector3.Zero(); this.l20 = Vector3.Zero(); this.l21 = Vector3.Zero(); this.l22 = Vector3.Zero(); } /** * Adds a light to the spherical harmonics * @param direction the direction of the light * @param color the color of the light * @param deltaSolidAngle the delta solid angle of the light */ addLight(direction, color, deltaSolidAngle) { TmpVectors.Vector3[0].set(color.r, color.g, color.b); const colorVector = TmpVectors.Vector3[0]; const c = TmpVectors.Vector3[1]; colorVector.scaleToRef(deltaSolidAngle, c); c.scaleToRef(applySH3(0, direction), TmpVectors.Vector3[2]); this.l00.addInPlace(TmpVectors.Vector3[2]); c.scaleToRef(applySH3(1, direction), TmpVectors.Vector3[2]); this.l1_1.addInPlace(TmpVectors.Vector3[2]); c.scaleToRef(applySH3(2, direction), TmpVectors.Vector3[2]); this.l10.addInPlace(TmpVectors.Vector3[2]); c.scaleToRef(applySH3(3, direction), TmpVectors.Vector3[2]); this.l11.addInPlace(TmpVectors.Vector3[2]); c.scaleToRef(applySH3(4, direction), TmpVectors.Vector3[2]); this.l2_2.addInPlace(TmpVectors.Vector3[2]); c.scaleToRef(applySH3(5, direction), TmpVectors.Vector3[2]); this.l2_1.addInPlace(TmpVectors.Vector3[2]); c.scaleToRef(applySH3(6, direction), TmpVectors.Vector3[2]); this.l20.addInPlace(TmpVectors.Vector3[2]); c.scaleToRef(applySH3(7, direction), TmpVectors.Vector3[2]); this.l21.addInPlace(TmpVectors.Vector3[2]); c.scaleToRef(applySH3(8, direction), TmpVectors.Vector3[2]); this.l22.addInPlace(TmpVectors.Vector3[2]); } /** * Scales the spherical harmonics by the given amount * @param scale the amount to scale */ scaleInPlace(scale) { this.l00.scaleInPlace(scale); this.l1_1.scaleInPlace(scale); this.l10.scaleInPlace(scale); this.l11.scaleInPlace(scale); this.l2_2.scaleInPlace(scale); this.l2_1.scaleInPlace(scale); this.l20.scaleInPlace(scale); this.l21.scaleInPlace(scale); this.l22.scaleInPlace(scale); } /** * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere. * * ``` * E_lm = A_l * L_lm * ``` * * In spherical harmonics this convolution amounts to scaling factors for each frequency band. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where * the scaling factors are given in equation 9. */ convertIncidentRadianceToIrradiance() { this.l00.scaleInPlace(SHCosKernelConvolution[0]); this.l1_1.scaleInPlace(SHCosKernelConvolution[1]); this.l10.scaleInPlace(SHCosKernelConvolution[2]); this.l11.scaleInPlace(SHCosKernelConvolution[3]); this.l2_2.scaleInPlace(SHCosKernelConvolution[4]); this.l2_1.scaleInPlace(SHCosKernelConvolution[5]); this.l20.scaleInPlace(SHCosKernelConvolution[6]); this.l21.scaleInPlace(SHCosKernelConvolution[7]); this.l22.scaleInPlace(SHCosKernelConvolution[8]); } /** * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation. * * ``` * L = (1/pi) * E * rho * ``` * * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually. */ convertIrradianceToLambertianRadiance() { this.scaleInPlace(1 / Math.PI); } /** * Integrates the reconstruction coefficients directly in to the SH preventing further * required operations at run time. * * This is simply done by scaling back the SH with Ylm constants parameter. * The trigonometric part being applied by the shader at run time. */ preScaleForRendering() { this.preScaled = true; this.l00.scaleInPlace(SH3ylmBasisConstants[0]); this.l1_1.scaleInPlace(SH3ylmBasisConstants[1]); this.l10.scaleInPlace(SH3ylmBasisConstants[2]); this.l11.scaleInPlace(SH3ylmBasisConstants[3]); this.l2_2.scaleInPlace(SH3ylmBasisConstants[4]); this.l2_1.scaleInPlace(SH3ylmBasisConstants[5]); this.l20.scaleInPlace(SH3ylmBasisConstants[6]); this.l21.scaleInPlace(SH3ylmBasisConstants[7]); this.l22.scaleInPlace(SH3ylmBasisConstants[8]); } /** * update the spherical harmonics coefficients from the given array * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22) * @returns the spherical harmonics (this) */ updateFromArray(data) { Vector3.FromArrayToRef(data[0], 0, this.l00); Vector3.FromArrayToRef(data[1], 0, this.l1_1); Vector3.FromArrayToRef(data[2], 0, this.l10); Vector3.FromArrayToRef(data[3], 0, this.l11); Vector3.FromArrayToRef(data[4], 0, this.l2_2); Vector3.FromArrayToRef(data[5], 0, this.l2_1); Vector3.FromArrayToRef(data[6], 0, this.l20); Vector3.FromArrayToRef(data[7], 0, this.l21); Vector3.FromArrayToRef(data[8], 0, this.l22); return this; } /** * update the spherical harmonics coefficients from the given floats array * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22) * @returns the spherical harmonics (this) */ updateFromFloatsArray(data) { Vector3.FromFloatsToRef(data[0], data[1], data[2], this.l00); Vector3.FromFloatsToRef(data[3], data[4], data[5], this.l1_1); Vector3.FromFloatsToRef(data[6], data[7], data[8], this.l10); Vector3.FromFloatsToRef(data[9], data[10], data[11], this.l11); Vector3.FromFloatsToRef(data[12], data[13], data[14], this.l2_2); Vector3.FromFloatsToRef(data[15], data[16], data[17], this.l2_1); Vector3.FromFloatsToRef(data[18], data[19], data[20], this.l20); Vector3.FromFloatsToRef(data[21], data[22], data[23], this.l21); Vector3.FromFloatsToRef(data[24], data[25], data[26], this.l22); return this; } /** * Constructs a spherical harmonics from an array. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22) * @returns the spherical harmonics */ static FromArray(data) { const sh = new _SphericalHarmonics(); return sh.updateFromArray(data); } // Keep for references. /** * Gets the spherical harmonics from polynomial * @param polynomial the spherical polynomial * @returns the spherical harmonics */ static FromPolynomial(polynomial) { const result = new _SphericalHarmonics(); result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126)); result.l1_1 = polynomial.y.scale(0.977204); result.l10 = polynomial.z.scale(0.977204); result.l11 = polynomial.x.scale(0.977204); result.l2_2 = polynomial.xy.scale(1.16538); result.l2_1 = polynomial.yz.scale(1.16538); result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834)); result.l21 = polynomial.zx.scale(1.16538); result.l22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538)); result.l1_1.scaleInPlace(-1); result.l11.scaleInPlace(-1); result.l2_1.scaleInPlace(-1); result.l21.scaleInPlace(-1); result.scaleInPlace(Math.PI); return result; } }; SphericalPolynomial = class _SphericalPolynomial { static { __name(this, "SphericalPolynomial"); } constructor() { this.x = Vector3.Zero(); this.y = Vector3.Zero(); this.z = Vector3.Zero(); this.xx = Vector3.Zero(); this.yy = Vector3.Zero(); this.zz = Vector3.Zero(); this.xy = Vector3.Zero(); this.yz = Vector3.Zero(); this.zx = Vector3.Zero(); } /** * The spherical harmonics used to create the polynomials. */ get preScaledHarmonics() { if (!this._harmonics) { this._harmonics = SphericalHarmonics.FromPolynomial(this); } if (!this._harmonics.preScaled) { this._harmonics.preScaleForRendering(); } return this._harmonics; } /** * Adds an ambient color to the spherical polynomial * @param color the color to add */ addAmbient(color) { TmpVectors.Vector3[0].copyFromFloats(color.r, color.g, color.b); const colorVector = TmpVectors.Vector3[0]; this.xx.addInPlace(colorVector); this.yy.addInPlace(colorVector); this.zz.addInPlace(colorVector); } /** * Scales the spherical polynomial by the given amount * @param scale the amount to scale */ scaleInPlace(scale) { this.x.scaleInPlace(scale); this.y.scaleInPlace(scale); this.z.scaleInPlace(scale); this.xx.scaleInPlace(scale); this.yy.scaleInPlace(scale); this.zz.scaleInPlace(scale); this.yz.scaleInPlace(scale); this.zx.scaleInPlace(scale); this.xy.scaleInPlace(scale); } /** * Updates the spherical polynomial from harmonics * @param harmonics the spherical harmonics * @returns the spherical polynomial */ updateFromHarmonics(harmonics) { this._harmonics = harmonics; this.x.copyFrom(harmonics.l11); this.x.scaleInPlace(1.02333).scaleInPlace(-1); this.y.copyFrom(harmonics.l1_1); this.y.scaleInPlace(1.02333).scaleInPlace(-1); this.z.copyFrom(harmonics.l10); this.z.scaleInPlace(1.02333); this.xx.copyFrom(harmonics.l00); TmpVectors.Vector3[0].copyFrom(harmonics.l20).scaleInPlace(0.247708); TmpVectors.Vector3[1].copyFrom(harmonics.l22).scaleInPlace(0.429043); this.xx.scaleInPlace(0.886277).subtractInPlace(TmpVectors.Vector3[0]).addInPlace(TmpVectors.Vector3[1]); this.yy.copyFrom(harmonics.l00); this.yy.scaleInPlace(0.886277).subtractInPlace(TmpVectors.Vector3[0]).subtractInPlace(TmpVectors.Vector3[1]); this.zz.copyFrom(harmonics.l00); TmpVectors.Vector3[0].copyFrom(harmonics.l20).scaleInPlace(0.495417); this.zz.scaleInPlace(0.886277).addInPlace(TmpVectors.Vector3[0]); this.yz.copyFrom(harmonics.l2_1); this.yz.scaleInPlace(0.858086).scaleInPlace(-1); this.zx.copyFrom(harmonics.l21); this.zx.scaleInPlace(0.858086).scaleInPlace(-1); this.xy.copyFrom(harmonics.l2_2); this.xy.scaleInPlace(0.858086); this.scaleInPlace(1 / Math.PI); return this; } /** * Gets the spherical polynomial from harmonics * @param harmonics the spherical harmonics * @returns the spherical polynomial */ static FromHarmonics(harmonics) { const result = new _SphericalPolynomial(); return result.updateFromHarmonics(harmonics); } /** * Constructs a spherical polynomial from an array. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy) * @returns the spherical polynomial */ static FromArray(data) { const sp = new _SphericalPolynomial(); Vector3.FromArrayToRef(data[0], 0, sp.x); Vector3.FromArrayToRef(data[1], 0, sp.y); Vector3.FromArrayToRef(data[2], 0, sp.z); Vector3.FromArrayToRef(data[3], 0, sp.xx); Vector3.FromArrayToRef(data[4], 0, sp.yy); Vector3.FromArrayToRef(data[5], 0, sp.zz); Vector3.FromArrayToRef(data[6], 0, sp.yz); Vector3.FromArrayToRef(data[7], 0, sp.zx); Vector3.FromArrayToRef(data[8], 0, sp.xy); return sp; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/HighDynamicRange/cubemapToSphericalPolynomial.js var FileFaceOrientation, CubeMapToSphericalPolynomialTools; var init_cubemapToSphericalPolynomial = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/HighDynamicRange/cubemapToSphericalPolynomial.js"() { init_math_vector(); init_math_scalar_functions(); init_sphericalPolynomial(); init_math_constants(); init_math_color(); FileFaceOrientation = class { static { __name(this, "FileFaceOrientation"); } constructor(name260, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) { this.name = name260; this.worldAxisForNormal = worldAxisForNormal; this.worldAxisForFileX = worldAxisForFileX; this.worldAxisForFileY = worldAxisForFileY; } }; CubeMapToSphericalPolynomialTools = class { static { __name(this, "CubeMapToSphericalPolynomialTools"); } /** * Converts a texture to the according Spherical Polynomial data. * This extracts the first 3 orders only as they are the only one used in the lighting. * * @param texture The texture to extract the information from. * @returns The Spherical Polynomial data. */ static ConvertCubeMapTextureToSphericalPolynomial(texture) { if (!texture.isCube) { return null; } texture.getScene()?.getEngine().flushFramebuffer(); const size = texture.getSize().width; const rightPromise = texture.readPixels(0, void 0, void 0, false); const leftPromise = texture.readPixels(1, void 0, void 0, false); let upPromise; let downPromise; if (texture.isRenderTarget) { upPromise = texture.readPixels(3, void 0, void 0, false); downPromise = texture.readPixels(2, void 0, void 0, false); } else { upPromise = texture.readPixels(2, void 0, void 0, false); downPromise = texture.readPixels(3, void 0, void 0, false); } const frontPromise = texture.readPixels(4, void 0, void 0, false); const backPromise = texture.readPixels(5, void 0, void 0, false); const gammaSpace = texture.gammaSpace; const format = 5; let type = 0; if (texture.textureType == 1 || texture.textureType == 2) { type = 1; } return new Promise((resolve) => { Promise.all([leftPromise, rightPromise, upPromise, downPromise, frontPromise, backPromise]).then(([left, right, up, down, front, back]) => { const cubeInfo = { size, right, left, up, down, front, back, format, type, gammaSpace }; resolve(this.ConvertCubeMapToSphericalPolynomial(cubeInfo)); }); }); } /** * Compute the area on the unit sphere of the rectangle defined by (x,y) and the origin * See https://www.rorydriscoll.com/2012/01/15/cubemap-texel-solid-angle/ * @param x * @param y * @returns the area */ static _AreaElement(x, y) { return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1)); } /** * Converts a cubemap to the according Spherical Polynomial data. * This extracts the first 3 orders only as they are the only one used in the lighting. * * @param cubeInfo The Cube map to extract the information from. * @returns The Spherical Polynomial data. */ static ConvertCubeMapToSphericalPolynomial(cubeInfo) { const sphericalHarmonics = new SphericalHarmonics(); let totalSolidAngle = 0; const du = 2 / cubeInfo.size; const dv = du; const halfTexel = 0.5 * du; const minUV = halfTexel - 1; for (let faceIndex = 0; faceIndex < 6; faceIndex++) { const fileFace = this._FileFaces[faceIndex]; const dataArray = cubeInfo[fileFace.name]; let v = minUV; const stride = cubeInfo.format === 5 ? 4 : 3; for (let y = 0; y < cubeInfo.size; y++) { let u = minUV; for (let x = 0; x < cubeInfo.size; x++) { const worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal); worldDirection.normalize(); const deltaSolidAngle = this._AreaElement(u - halfTexel, v - halfTexel) - this._AreaElement(u - halfTexel, v + halfTexel) - this._AreaElement(u + halfTexel, v - halfTexel) + this._AreaElement(u + halfTexel, v + halfTexel); let r = dataArray[y * cubeInfo.size * stride + x * stride + 0]; let g = dataArray[y * cubeInfo.size * stride + x * stride + 1]; let b = dataArray[y * cubeInfo.size * stride + x * stride + 2]; if (isNaN(r)) { r = 0; } if (isNaN(g)) { g = 0; } if (isNaN(b)) { b = 0; } if (cubeInfo.type === 0) { r /= 255; g /= 255; b /= 255; } if (cubeInfo.gammaSpace) { r = Math.pow(Clamp(r), ToLinearSpace); g = Math.pow(Clamp(g), ToLinearSpace); b = Math.pow(Clamp(b), ToLinearSpace); } const max = this.MAX_HDRI_VALUE; if (this.PRESERVE_CLAMPED_COLORS) { const currentMax = Math.max(r, g, b); if (currentMax > max) { const factor = max / currentMax; r *= factor; g *= factor; b *= factor; } } else { r = Clamp(r, 0, max); g = Clamp(g, 0, max); b = Clamp(b, 0, max); } const color = new Color3(r, g, b); sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle); totalSolidAngle += deltaSolidAngle; u += du; } v += dv; } } const sphereSolidAngle = 4 * Math.PI; const facesProcessed = 6; const expectedSolidAngle = sphereSolidAngle * facesProcessed / 6; const correctionFactor = expectedSolidAngle / totalSolidAngle; sphericalHarmonics.scaleInPlace(correctionFactor); sphericalHarmonics.convertIncidentRadianceToIrradiance(); sphericalHarmonics.convertIrradianceToLambertianRadiance(); return SphericalPolynomial.FromHarmonics(sphericalHarmonics); } }; CubeMapToSphericalPolynomialTools._FileFaces = [ new FileFaceOrientation("right", new Vector3(1, 0, 0), new Vector3(0, 0, -1), new Vector3(0, -1, 0)), // +X east new FileFaceOrientation("left", new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, -1, 0)), // -X west new FileFaceOrientation("up", new Vector3(0, 1, 0), new Vector3(1, 0, 0), new Vector3(0, 0, 1)), // +Y north new FileFaceOrientation("down", new Vector3(0, -1, 0), new Vector3(1, 0, 0), new Vector3(0, 0, -1)), // -Y south new FileFaceOrientation("front", new Vector3(0, 0, 1), new Vector3(1, 0, 0), new Vector3(0, -1, 0)), // +Z top new FileFaceOrientation("back", new Vector3(0, 0, -1), new Vector3(-1, 0, 0), new Vector3(0, -1, 0)) // -Z bottom ]; CubeMapToSphericalPolynomialTools.MAX_HDRI_VALUE = 4096; CubeMapToSphericalPolynomialTools.PRESERVE_CLAMPED_COLORS = false; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/lodCube.fragment.js var lodCube_fragment_exports = {}; __export(lodCube_fragment_exports, { lodCubePixelShader: () => lodCubePixelShader }); var name, shader, lodCubePixelShader; var init_lodCube_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/lodCube.fragment.js"() { init_shaderStore(); name = "lodCubePixelShader"; shader = `precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform int gamma;void main(void) {vec2 uv=vUV*2.0-1.0; #ifdef POSITIVEX gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod); #endif #ifdef NEGATIVEX gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod); #endif #ifdef POSITIVEY gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod); #endif #ifdef NEGATIVEY gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod); #endif #ifdef POSITIVEZ gl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod); #endif #ifdef NEGATIVEZ gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod); #endif if (gamma==0) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}} `; if (!ShaderStore.ShadersStore[name]) { ShaderStore.ShadersStore[name] = shader; } lodCubePixelShader = { name, shader }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/lod.fragment.js var lod_fragment_exports = {}; __export(lod_fragment_exports, { lodPixelShader: () => lodPixelShader }); var name2, shader2, lodPixelShader; var init_lod_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/lod.fragment.js"() { init_shaderStore(); name2 = "lodPixelShader"; shader2 = `precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform sampler2D textureSampler;uniform float lod;uniform vec2 texSize;uniform int gamma;void main(void) {ivec2 textureDimensions=textureSize(textureSampler,0);gl_FragColor=texelFetch(textureSampler,ivec2(vUV*vec2(textureDimensions)),int(lod));if (gamma==0) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}} `; if (!ShaderStore.ShadersStore[name2]) { ShaderStore.ShadersStore[name2] = shader2; } lodPixelShader = { name: name2, shader: shader2 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/lodCube.fragment.js var lodCube_fragment_exports2 = {}; __export(lodCube_fragment_exports2, { lodCubePixelShaderWGSL: () => lodCubePixelShaderWGSL }); var name3, shader3, lodCubePixelShaderWGSL; var init_lodCube_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/lodCube.fragment.js"() { init_shaderStore(); name3 = "lodCubePixelShader"; shader3 = `const GammaEncodePowerApprox=1.0/2.2;varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_cube;uniform lod: f32;uniform gamma: i32;@fragment fn main(input: FragmentInputs)->FragmentOutputs {let uv=fragmentInputs.vUV*2.0-1.0; #ifdef POSITIVEX fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(1.001,uv.y,uv.x),uniforms.lod); #endif #ifdef NEGATIVEX fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(-1.001,uv.y,uv.x),uniforms.lod); #endif #ifdef POSITIVEY fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv.y,1.001,uv.x),uniforms.lod); #endif #ifdef NEGATIVEY fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv.y,-1.001,uv.x),uniforms.lod); #endif #ifdef POSITIVEZ fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv,1.001),uniforms.lod); #endif #ifdef NEGATIVEZ fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,vec3f(uv,-1.001),uniforms.lod); #endif if (uniforms.gamma==0) {fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb,vec3f(GammaEncodePowerApprox)),fragmentOutputs.color.a);}} `; if (!ShaderStore.ShadersStoreWGSL[name3]) { ShaderStore.ShadersStoreWGSL[name3] = shader3; } lodCubePixelShaderWGSL = { name: name3, shader: shader3 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/lod.fragment.js var lod_fragment_exports2 = {}; __export(lod_fragment_exports2, { lodPixelShaderWGSL: () => lodPixelShaderWGSL }); var name4, shader4, lodPixelShaderWGSL; var init_lod_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/lod.fragment.js"() { init_shaderStore(); name4 = "lodPixelShader"; shader4 = `const GammaEncodePowerApprox=1.0/2.2;varying vUV: vec2f;var textureSampler: texture_2d;uniform lod: f32;uniform gamma: i32;@fragment fn main(input: FragmentInputs)->FragmentOutputs {let textureSize=textureDimensions(textureSampler);fragmentOutputs.color=textureLoad(textureSampler,vec2u(fragmentInputs.vUV*vec2f(textureSize)),u32(uniforms.lod));if (uniforms.gamma==0) {fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb,vec3f(GammaEncodePowerApprox)),fragmentOutputs.color.a);}} `; if (!ShaderStore.ShadersStoreWGSL[name4]) { ShaderStore.ShadersStoreWGSL[name4] = shader4; } lodPixelShaderWGSL = { name: name4, shader: shader4 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/tslib.es6.js function __extends(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } __name(__, "__"); d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } 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); }); } __name(adopt, "adopt"); return new (P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } __name(fulfilled, "fulfilled"); function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } __name(rejected, "rejected"); function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } __name(step, "step"); step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: /* @__PURE__ */ __name(function() { if (t[0] & 1) throw t[1]; return t[1]; }, "sent"), 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]); }; } __name(verb, "verb"); 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 }; } __name(step, "step"); } function __exportStar(m, o) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, 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: /* @__PURE__ */ __name(function() { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; }, "next") }; 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 }; } 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 __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } 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); }); }; } __name(verb, "verb"); function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } __name(resume, "resume"); function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } __name(step, "step"); function fulfill(value) { resume("next", value); } __name(fulfill, "fulfill"); function reject(value) { resume("throw", value); } __name(reject, "reject"); function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } __name(settle, "settle"); } 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; } __name(verb, "verb"); } 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); }); }; } __name(verb, "verb"); function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v2) { resolve({ value: v2, done: d }); }, reject); } __name(settle, "settle"); } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.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, state, kind, f) { if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); } function __classPrivateFieldSet(receiver, state, value, kind, f) { if (kind === "m") throw new TypeError("Private method is not writable"); if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; } function __classPrivateFieldIn(state, receiver) { if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); return typeof state === "function" ? receiver === state : state.has(receiver); } var extendStatics, __assign, __createBinding, __setModuleDefault; var init_tslib_es6 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/tslib.es6.js"() { extendStatics = /* @__PURE__ */ __name(function(d, b) { extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { d2.__proto__ = b2; } || function(d2, b2) { for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; }; return extendStatics(d, b); }, "extendStatics"); __name(__extends, "__extends"); __assign = /* @__PURE__ */ __name(function() { __assign = Object.assign || /* @__PURE__ */ __name(function __assign2(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; }, "__assign"); return __assign.apply(this, arguments); }, "__assign"); __name(__rest, "__rest"); __name(__decorate, "__decorate"); __name(__param, "__param"); __name(__metadata, "__metadata"); __name(__awaiter, "__awaiter"); __name(__generator, "__generator"); __createBinding = Object.create ? function(o, m, k, k2) { if (k2 === void 0) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: /* @__PURE__ */ __name(function() { return m[k]; }, "get") }; } Object.defineProperty(o, k2, desc); } : function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; }; __name(__exportStar, "__exportStar"); __name(__values, "__values"); __name(__read, "__read"); __name(__spread, "__spread"); __name(__spreadArrays, "__spreadArrays"); __name(__spreadArray, "__spreadArray"); __name(__await, "__await"); __name(__asyncGenerator, "__asyncGenerator"); __name(__asyncDelegator, "__asyncDelegator"); __name(__asyncValues, "__asyncValues"); __name(__makeTemplateObject, "__makeTemplateObject"); ; __setModuleDefault = Object.create ? function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); } : function(o, v) { o["default"] = v; }; __name(__importStar, "__importStar"); __name(__importDefault, "__importDefault"); __name(__classPrivateFieldGet, "__classPrivateFieldGet"); __name(__classPrivateFieldSet, "__classPrivateFieldSet"); __name(__classPrivateFieldIn, "__classPrivateFieldIn"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/decorators.functions.js function GetDirectStore(target) { const classKey = target.getClassName(); if (!DecoratorInitialStore[classKey]) { DecoratorInitialStore[classKey] = {}; } return DecoratorInitialStore[classKey]; } function GetMergedStore(target) { const classKey = target.getClassName(); if (MergedStore[classKey]) { return MergedStore[classKey]; } MergedStore[classKey] = {}; const store = MergedStore[classKey]; let currentTarget = target; let currentKey = classKey; while (currentKey) { const initialStore = DecoratorInitialStore[currentKey]; for (const property in initialStore) { store[property] = initialStore[property]; } let parent; let done = false; do { parent = Object.getPrototypeOf(currentTarget); if (!parent.getClassName) { done = true; break; } if (parent.getClassName() !== currentKey) { break; } currentTarget = parent; } while (parent); if (done) { break; } currentKey = parent.getClassName(); currentTarget = parent; } return store; } var MergedStore, DecoratorInitialStore; var init_decorators_functions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/decorators.functions.js"() { MergedStore = {}; DecoratorInitialStore = {}; __name(GetDirectStore, "GetDirectStore"); __name(GetMergedStore, "GetMergedStore"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/decorators.js function generateSerializableMember(type, sourceName) { return (target, propertyKey) => { const classStore = GetDirectStore(target); if (!classStore[propertyKey]) { classStore[propertyKey] = { type, sourceName }; } }; } function generateExpandMember(setCallback, targetKey = null) { return (target, propertyKey) => { const key = targetKey || "_" + propertyKey; Object.defineProperty(target, propertyKey, { get: /* @__PURE__ */ __name(function() { return this[key]; }, "get"), set: /* @__PURE__ */ __name(function(value) { if (typeof this[key]?.equals === "function") { if (this[key].equals(value)) { return; } } if (this[key] === value) { return; } this[key] = value; target[setCallback].apply(this); }, "set"), enumerable: true, configurable: true }); }; } function expandToProperty(callback, targetKey = null) { return generateExpandMember(callback, targetKey); } function serialize(sourceName) { return generateSerializableMember(0, sourceName); } function serializeAsTexture(sourceName) { return generateSerializableMember(1, sourceName); } function serializeAsColor3(sourceName) { return generateSerializableMember(2, sourceName); } function serializeAsFresnelParameters(sourceName) { return generateSerializableMember(3, sourceName); } function serializeAsVector2(sourceName) { return generateSerializableMember(4, sourceName); } function serializeAsVector3(sourceName) { return generateSerializableMember(5, sourceName); } function serializeAsMeshReference(sourceName) { return generateSerializableMember(6, sourceName); } function serializeAsColorCurves(sourceName) { return generateSerializableMember(7, sourceName); } function serializeAsColor4(sourceName) { return generateSerializableMember(8, sourceName); } function serializeAsImageProcessingConfiguration(sourceName) { return generateSerializableMember(9, sourceName); } function serializeAsQuaternion(sourceName) { return generateSerializableMember(10, sourceName); } function serializeAsMatrix(sourceName) { return generateSerializableMember(12, sourceName); } function serializeAsCameraReference(sourceName) { return generateSerializableMember(11, sourceName); } function nativeOverride(target, propertyKey, descriptor, predicate) { const jsFunc = descriptor.value; descriptor.value = (...params) => { let func = jsFunc; if (typeof _native !== "undefined" && _native[propertyKey]) { const nativeFunc = _native[propertyKey]; if (predicate) { func = /* @__PURE__ */ __name((...params2) => predicate(...params2) ? nativeFunc(...params2) : jsFunc(...params2), "func"); } else { func = nativeFunc; } } target[propertyKey] = func; return func(...params); }; } function addAccessorsForMaterialProperty(setCallback, targetKey = null) { return (target, propertyKey) => { const key = propertyKey; const newKey = targetKey || ""; Object.defineProperty(target, newKey, { get: /* @__PURE__ */ __name(function() { return this[key].value; }, "get"), set: /* @__PURE__ */ __name(function(value) { if (typeof this[key]?.value?.equals === "function") { if (this[key].value.equals(value)) { return; } } if (this[key].value === value) { return; } this[key].value = value; target[setCallback].apply(this); }, "set"), enumerable: true, configurable: true }); }; } var init_decorators = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/decorators.js"() { init_decorators_functions(); __name(generateSerializableMember, "generateSerializableMember"); __name(generateExpandMember, "generateExpandMember"); __name(expandToProperty, "expandToProperty"); __name(serialize, "serialize"); __name(serializeAsTexture, "serializeAsTexture"); __name(serializeAsColor3, "serializeAsColor3"); __name(serializeAsFresnelParameters, "serializeAsFresnelParameters"); __name(serializeAsVector2, "serializeAsVector2"); __name(serializeAsVector3, "serializeAsVector3"); __name(serializeAsMeshReference, "serializeAsMeshReference"); __name(serializeAsColorCurves, "serializeAsColorCurves"); __name(serializeAsColor4, "serializeAsColor4"); __name(serializeAsImageProcessingConfiguration, "serializeAsImageProcessingConfiguration"); __name(serializeAsQuaternion, "serializeAsQuaternion"); __name(serializeAsMatrix, "serializeAsMatrix"); __name(serializeAsCameraReference, "serializeAsCameraReference"); __name(nativeOverride, "nativeOverride"); nativeOverride.filter = function(predicate) { return (target, propertyKey, descriptor) => nativeOverride(target, propertyKey, descriptor, predicate); }; __name(addAccessorsForMaterialProperty, "addAccessorsForMaterialProperty"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/guid.js function RandomGUID() { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0, v = c === "x" ? r : r & 3 | 8; return v.toString(16); }); } var GUID; var init_guid = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/guid.js"() { __name(RandomGUID, "RandomGUID"); GUID = { /** * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 * Be aware Math.random() could cause collisions, but: * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide" * @returns a pseudo random id */ // eslint-disable-next-line @typescript-eslint/naming-convention RandomId: RandomGUID }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/thinTexture.js var ThinTexture; var init_thinTexture = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/thinTexture.js"() { init_math_size(); ThinTexture = class _ThinTexture { static { __name(this, "ThinTexture"); } /** * | Value | Type | Description | * | ----- | ------------------ | ----------- | * | 0 | CLAMP_ADDRESSMODE | | * | 1 | WRAP_ADDRESSMODE | | * | 2 | MIRROR_ADDRESSMODE | | */ get wrapU() { return this._wrapU; } set wrapU(value) { this._wrapU = value; } /** * | Value | Type | Description | * | ----- | ------------------ | ----------- | * | 0 | CLAMP_ADDRESSMODE | | * | 1 | WRAP_ADDRESSMODE | | * | 2 | MIRROR_ADDRESSMODE | | */ get wrapV() { return this._wrapV; } set wrapV(value) { this._wrapV = value; } /** * How a texture is mapped. * Unused in thin texture mode. */ get coordinatesMode() { return 0; } /** * Define if the texture is a cube texture or if false a 2d texture. */ get isCube() { if (!this._texture) { return false; } return this._texture.isCube; } // eslint-disable-next-line @typescript-eslint/naming-convention set isCube(value) { if (!this._texture) { return; } this._texture.isCube = value; } /** * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture. */ get is3D() { if (!this._texture) { return false; } return this._texture.is3D; } // eslint-disable-next-line @typescript-eslint/naming-convention set is3D(value) { if (!this._texture) { return; } this._texture.is3D = value; } /** * Define if the texture is a 2d array texture (webgl 2) or if false a 2d texture. */ get is2DArray() { if (!this._texture) { return false; } return this._texture.is2DArray; } // eslint-disable-next-line @typescript-eslint/naming-convention set is2DArray(value) { if (!this._texture) { return; } this._texture.is2DArray = value; } /** * Get the class name of the texture. * @returns "ThinTexture" */ getClassName() { return "ThinTexture"; } static _IsRenderTargetWrapper(texture) { return texture?.shareDepth !== void 0; } /** * Instantiates a new ThinTexture. * Base class of all the textures in babylon. * This can be used as an internal texture wrapper in AbstractEngine to benefit from the cache * @param internalTexture Define the internalTexture to wrap. You can also pass a RenderTargetWrapper, in which case the texture will be the render target's texture */ constructor(internalTexture) { this._wrapU = 1; this._wrapV = 1; this.wrapR = 1; this.anisotropicFilteringLevel = 4; this.delayLoadState = 0; this._texture = null; this._engine = null; this._cachedSize = Size.Zero(); this._cachedBaseSize = Size.Zero(); this._initialSamplingMode = 2; this._texture = _ThinTexture._IsRenderTargetWrapper(internalTexture) ? internalTexture.texture : internalTexture; if (this._texture) { this._engine = this._texture.getEngine(); this.wrapU = this._texture._cachedWrapU ?? this.wrapU; this.wrapV = this._texture._cachedWrapV ?? this.wrapV; this.wrapR = this._texture._cachedWrapR ?? this.wrapR; } } /** * Get if the texture is ready to be used (downloaded, converted, mip mapped...). * @returns true if fully ready */ isReady() { if (this.delayLoadState === 4) { this.delayLoad(); return false; } if (this._texture) { return this._texture.isReady; } return false; } /** * Triggers the load sequence in delayed load mode. */ delayLoad() { } /** * Get the underlying lower level texture from Babylon. * @returns the internal texture */ getInternalTexture() { return this._texture; } /** * Get the size of the texture. * @returns the texture size. */ getSize() { if (this._texture) { if (this._texture.width) { this._cachedSize.width = this._texture.width; this._cachedSize.height = this._texture.height; return this._cachedSize; } if (this._texture._size) { this._cachedSize.width = this._texture._size; this._cachedSize.height = this._texture._size; return this._cachedSize; } } return this._cachedSize; } /** * Get the base size of the texture. * It can be different from the size if the texture has been resized for POT for instance * @returns the base size */ getBaseSize() { if (!this.isReady() || !this._texture) { this._cachedBaseSize.width = 0; this._cachedBaseSize.height = 0; return this._cachedBaseSize; } if (this._texture._size) { this._cachedBaseSize.width = this._texture._size; this._cachedBaseSize.height = this._texture._size; return this._cachedBaseSize; } this._cachedBaseSize.width = this._texture.baseWidth; this._cachedBaseSize.height = this._texture.baseHeight; return this._cachedBaseSize; } /** * Get the current sampling mode associated with the texture. */ get samplingMode() { if (!this._texture) { return this._initialSamplingMode; } return this._texture.samplingMode; } /** * Update the sampling mode of the texture. * Default is Trilinear mode. * * | Value | Type | Description | * | ----- | ------------------ | ----------- | * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear | * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest | * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear | * | 4 | NEAREST_NEAREST_MIPNEAREST | | * | 5 | NEAREST_LINEAR_MIPNEAREST | | * | 6 | NEAREST_LINEAR_MIPLINEAR | | * | 7 | NEAREST_LINEAR | | * | 8 | NEAREST_NEAREST | | * | 9 | LINEAR_NEAREST_MIPNEAREST | | * | 10 | LINEAR_NEAREST_MIPLINEAR | | * | 11 | LINEAR_LINEAR | | * | 12 | LINEAR_NEAREST | | * * > _mag_: magnification filter (close to the viewer) * > _min_: minification filter (far from the viewer) * > _mip_: filter used between mip map levels *@param samplingMode Define the new sampling mode of the texture *@param generateMipMaps Define if the texture should generate mip maps or not. Default is false. */ updateSamplingMode(samplingMode, generateMipMaps = false) { if (this._texture && this._engine) { this._engine.updateTextureSamplingMode(samplingMode, this._texture, this._texture.generateMipMaps && generateMipMaps); } } /** * Release and destroy the underlying lower level texture aka internalTexture. */ releaseInternalTexture() { if (this._texture) { this._texture.dispose(); this._texture = null; } } /** * Dispose the texture and release its associated resources. */ dispose() { if (this._texture) { this.releaseInternalTexture(); this._engine = null; } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/andOrNotEvaluator.js var AndOrNotEvaluator; var init_andOrNotEvaluator = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/andOrNotEvaluator.js"() { AndOrNotEvaluator = class _AndOrNotEvaluator { static { __name(this, "AndOrNotEvaluator"); } /** * Evaluate a query * @param query defines the query to evaluate * @param evaluateCallback defines the callback used to filter result * @returns true if the query matches */ static Eval(query, evaluateCallback) { if (!query.match(/\([^()]*\)/g)) { query = _AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback); } else { query = query.replace(/\([^()]*\)/g, (r) => { r = r.slice(1, r.length - 1); return _AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback); }); } if (query === "true") { return true; } if (query === "false") { return false; } return _AndOrNotEvaluator.Eval(query, evaluateCallback); } static _HandleParenthesisContent(parenthesisContent, evaluateCallback) { evaluateCallback = evaluateCallback || ((r) => { return r === "true" ? true : false; }); let result; const or = parenthesisContent.split("||"); for (const i in or) { if (Object.prototype.hasOwnProperty.call(or, i)) { let ori = _AndOrNotEvaluator._SimplifyNegation(or[i].trim()); const and = ori.split("&&"); if (and.length > 1) { for (let j = 0; j < and.length; ++j) { const andj = _AndOrNotEvaluator._SimplifyNegation(and[j].trim()); if (andj !== "true" && andj !== "false") { if (andj[0] === "!") { result = !evaluateCallback(andj.substring(1)); } else { result = evaluateCallback(andj); } } else { result = andj === "true" ? true : false; } if (!result) { ori = "false"; break; } } } if (result || ori === "true") { result = true; break; } if (ori !== "true" && ori !== "false") { if (ori[0] === "!") { result = !evaluateCallback(ori.substring(1)); } else { result = evaluateCallback(ori); } } else { result = ori === "true" ? true : false; } } } return result ? "true" : "false"; } static _SimplifyNegation(booleanString) { booleanString = booleanString.replace(/^[\s!]+/, (r) => { r = r.replace(/[\s]/g, () => ""); return r.length % 2 ? "!" : ""; }); booleanString = booleanString.trim(); if (booleanString === "!true") { booleanString = "false"; } else if (booleanString === "!false") { booleanString = "true"; } return booleanString; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tags.js var Tags; var init_tags = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tags.js"() { init_andOrNotEvaluator(); Tags = class _Tags { static { __name(this, "Tags"); } /** * Adds support for tags on the given object * @param obj defines the object to use */ static EnableFor(obj) { obj._tags = obj._tags || {}; obj.hasTags = () => { return _Tags.HasTags(obj); }; obj.addTags = (tagsString) => { return _Tags.AddTagsTo(obj, tagsString); }; obj.removeTags = (tagsString) => { return _Tags.RemoveTagsFrom(obj, tagsString); }; obj.matchesTagsQuery = (tagsQuery) => { return _Tags.MatchesQuery(obj, tagsQuery); }; } /** * Removes tags support * @param obj defines the object to use */ static DisableFor(obj) { delete obj._tags; delete obj.hasTags; delete obj.addTags; delete obj.removeTags; delete obj.matchesTagsQuery; } /** * Gets a boolean indicating if the given object has tags * @param obj defines the object to use * @returns a boolean */ static HasTags(obj) { if (!obj._tags) { return false; } const tags = obj._tags; for (const i in tags) { if (Object.prototype.hasOwnProperty.call(tags, i)) { return true; } } return false; } /** * Gets the tags available on a given object * @param obj defines the object to use * @param asString defines if the tags must be returned as a string instead of an array of strings * @returns the tags */ static GetTags(obj, asString = true) { if (!obj._tags) { return null; } if (asString) { const tagsArray = []; for (const tag in obj._tags) { if (Object.prototype.hasOwnProperty.call(obj._tags, tag) && obj._tags[tag] === true) { tagsArray.push(tag); } } return tagsArray.join(" "); } else { return obj._tags; } } /** * Adds tags to an object * @param obj defines the object to use * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces */ static AddTagsTo(obj, tagsString) { if (!tagsString) { return; } if (typeof tagsString !== "string") { return; } const tags = tagsString.split(" "); for (const tag of tags) { _Tags._AddTagTo(obj, tag); } } /** * @internal */ static _AddTagTo(obj, tag) { tag = tag.trim(); if (tag === "" || tag === "true" || tag === "false") { return; } if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) { return; } _Tags.EnableFor(obj); obj._tags[tag] = true; } /** * Removes specific tags from a specific object * @param obj defines the object to use * @param tagsString defines the tags to remove */ static RemoveTagsFrom(obj, tagsString) { if (!_Tags.HasTags(obj)) { return; } const tags = tagsString.split(" "); for (const t in tags) { _Tags._RemoveTagFrom(obj, tags[t]); } } /** * @internal */ static _RemoveTagFrom(obj, tag) { delete obj._tags[tag]; } /** * Defines if tags hosted on an object match a given query * @param obj defines the object to use * @param tagsQuery defines the tag query * @returns a boolean */ static MatchesQuery(obj, tagsQuery) { if (tagsQuery === void 0) { return true; } if (tagsQuery === "") { return _Tags.HasTags(obj); } return AndOrNotEvaluator.Eval(tagsQuery, (r) => _Tags.HasTags(obj) && obj._tags[r]); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/decorators.serialization.js var CopySource, SerializationHelper; var init_decorators_serialization = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/decorators.serialization.js"() { init_devTools(); init_tags(); init_math_color(); init_math_vector(); init_decorators_functions(); CopySource = /* @__PURE__ */ __name(function(creationFunction, source, instanciate, options = {}) { const destination = creationFunction(); if (Tags && Tags.HasTags(source)) { Tags.AddTagsTo(destination, Tags.GetTags(source, true)); } const classStore = GetMergedStore(destination); const textureMap = {}; for (const property in classStore) { const propertyDescriptor = classStore[property]; const sourceProperty = source[property]; const propertyType = propertyDescriptor.type; if (sourceProperty !== void 0 && sourceProperty !== null && (property !== "uniqueId" || SerializationHelper.AllowLoadingUniqueId)) { switch (propertyType) { case 0: // Value case 6: // Mesh reference case 9: // Image processing configuration reference case 11: destination[property] = sourceProperty; break; case 1: if (options.cloneTexturesOnlyOnce && textureMap[sourceProperty.uniqueId]) { destination[property] = textureMap[sourceProperty.uniqueId]; } else { destination[property] = instanciate || sourceProperty.isRenderTarget ? sourceProperty : sourceProperty.clone(); textureMap[sourceProperty.uniqueId] = destination[property]; } break; case 2: // Color3 case 3: // FresnelParameters case 4: // Vector2 case 5: // Vector3 case 7: // Color Curves case 8: // Color 4 case 10: // Quaternion case 12: destination[property] = instanciate ? sourceProperty : sourceProperty.clone(); break; } } } return destination; }, "CopySource"); SerializationHelper = class _SerializationHelper { static { __name(this, "SerializationHelper"); } /** * Appends the serialized animations from the source animations * @param source Source containing the animations * @param destination Target to store the animations */ static AppendSerializedAnimations(source, destination) { if (source.animations) { destination.animations = []; for (let animationIndex = 0; animationIndex < source.animations.length; animationIndex++) { const animation = source.animations[animationIndex]; destination.animations.push(animation.serialize()); } } } /** * Static function used to serialized a specific entity * @param entity defines the entity to serialize * @param serializationObject defines the optional target object where serialization data will be stored * @returns a JSON compatible object representing the serialization of the entity */ static Serialize(entity, serializationObject) { if (!serializationObject) { serializationObject = {}; } if (Tags) { serializationObject.tags = Tags.GetTags(entity); } const serializedProperties = GetMergedStore(entity); for (const property in serializedProperties) { const propertyDescriptor = serializedProperties[property]; const targetPropertyName = propertyDescriptor.sourceName || property; const propertyType = propertyDescriptor.type; const sourceProperty = entity[property]; if (sourceProperty !== void 0 && sourceProperty !== null && (property !== "uniqueId" || _SerializationHelper.AllowLoadingUniqueId)) { switch (propertyType) { case 0: if (Array.isArray(sourceProperty)) { serializationObject[targetPropertyName] = sourceProperty.slice(); } else { serializationObject[targetPropertyName] = sourceProperty; } break; case 1: serializationObject[targetPropertyName] = sourceProperty.serialize(); break; case 2: serializationObject[targetPropertyName] = sourceProperty.asArray(); break; case 3: serializationObject[targetPropertyName] = sourceProperty.serialize(); break; case 4: serializationObject[targetPropertyName] = sourceProperty.asArray(); break; case 5: serializationObject[targetPropertyName] = sourceProperty.asArray(); break; case 6: serializationObject[targetPropertyName] = sourceProperty.id; break; case 7: serializationObject[targetPropertyName] = sourceProperty.serialize(); break; case 8: serializationObject[targetPropertyName] = sourceProperty.asArray(); break; case 9: serializationObject[targetPropertyName] = sourceProperty.serialize(); break; case 10: serializationObject[targetPropertyName] = sourceProperty.asArray(); break; case 11: serializationObject[targetPropertyName] = sourceProperty.id; break; case 12: serializationObject[targetPropertyName] = sourceProperty.asArray(); break; } } } return serializationObject; } /** * Given a source json and a destination object in a scene, this function will parse the source and will try to apply its content to the destination object * @param source the source json data * @param destination the destination object * @param scene the scene where the object is * @param rootUrl root url to use to load assets */ static ParseProperties(source, destination, scene, rootUrl) { if (!rootUrl) { rootUrl = ""; } const classStore = GetMergedStore(destination); for (const property in classStore) { const propertyDescriptor = classStore[property]; const sourceProperty = source[propertyDescriptor.sourceName || property]; const propertyType = propertyDescriptor.type; if (sourceProperty !== void 0 && sourceProperty !== null && (property !== "uniqueId" || _SerializationHelper.AllowLoadingUniqueId)) { const dest = destination; switch (propertyType) { case 0: dest[property] = sourceProperty; break; case 1: if (scene) { dest[property] = _SerializationHelper._TextureParser(sourceProperty, scene, rootUrl); } break; case 2: dest[property] = Color3.FromArray(sourceProperty); break; case 3: dest[property] = _SerializationHelper._FresnelParametersParser(sourceProperty); break; case 4: dest[property] = Vector2.FromArray(sourceProperty); break; case 5: dest[property] = Vector3.FromArray(sourceProperty); break; case 6: if (scene) { dest[property] = scene.getLastMeshById(sourceProperty); } break; case 7: dest[property] = _SerializationHelper._ColorCurvesParser(sourceProperty); break; case 8: dest[property] = Color4.FromArray(sourceProperty); break; case 9: dest[property] = _SerializationHelper._ImageProcessingConfigurationParser(sourceProperty); break; case 10: dest[property] = Quaternion.FromArray(sourceProperty); break; case 11: if (scene) { dest[property] = scene.getCameraById(sourceProperty); } break; case 12: dest[property] = Matrix.FromArray(sourceProperty); break; } } } } /** * Creates a new entity from a serialization data object * @param creationFunction defines a function used to instanciated the new entity * @param source defines the source serialization data * @param scene defines the hosting scene * @param rootUrl defines the root url for resources * @returns a new entity */ static Parse(creationFunction, source, scene, rootUrl = null) { const destination = creationFunction(); if (Tags) { Tags.AddTagsTo(destination, source.tags); } _SerializationHelper.ParseProperties(source, destination, scene, rootUrl); return destination; } /** * Clones an object * @param creationFunction defines the function used to instanciate the new object * @param source defines the source object * @param options defines the options to use * @returns the cloned object */ static Clone(creationFunction, source, options = {}) { return CopySource(creationFunction, source, false, options); } /** * Instanciates a new object based on a source one (some data will be shared between both object) * @param creationFunction defines the function used to instanciate the new object * @param source defines the source object * @returns the new object */ static Instanciate(creationFunction, source) { return CopySource(creationFunction, source, true); } }; SerializationHelper.AllowLoadingUniqueId = false; SerializationHelper._ImageProcessingConfigurationParser = (sourceProperty) => { throw _WarnImport("ImageProcessingConfiguration"); }; SerializationHelper._FresnelParametersParser = (sourceProperty) => { throw _WarnImport("FresnelParameters"); }; SerializationHelper._ColorCurvesParser = (sourceProperty) => { throw _WarnImport("ColorCurves"); }; SerializationHelper._TextureParser = (sourceProperty, scene, rootUrl) => { throw _WarnImport("Texture"); }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/baseTexture.js var BaseTexture; var init_baseTexture = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/baseTexture.js"() { init_tslib_es6(); init_decorators(); init_observable(); init_math_vector(); init_engineStore(); init_guid(); init_fileTools(); init_thinTexture(); init_decorators_serialization(); BaseTexture = class _BaseTexture extends ThinTexture { static { __name(this, "BaseTexture"); } /** * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance). */ set hasAlpha(value) { if (this._hasAlpha === value) { return; } this._hasAlpha = value; if (this._scene) { this._scene.markAllMaterialsAsDirty(1, (mat) => { return mat.hasTexture(this); }); } } get hasAlpha() { return this._hasAlpha; } /** * 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. */ set getAlphaFromRGB(value) { if (this._getAlphaFromRGB === value) { return; } this._getAlphaFromRGB = value; if (this._scene) { this._scene.markAllMaterialsAsDirty(1, (mat) => { return mat.hasTexture(this); }); } } get getAlphaFromRGB() { return this._getAlphaFromRGB; } /** * Define the UV channel to use starting from 0 and defaulting to 0. * This is part of the texture as textures usually maps to one uv set. */ set coordinatesIndex(value) { if (this._coordinatesIndex === value) { return; } this._coordinatesIndex = value; if (this._scene) { this._scene.markAllMaterialsAsDirty(1, (mat) => { return mat.hasTexture(this); }); } } get coordinatesIndex() { return this._coordinatesIndex; } /** * How a texture is mapped. * * | Value | Type | Description | * | ----- | ----------------------------------- | ----------- | * | 0 | EXPLICIT_MODE | | * | 1 | SPHERICAL_MODE | | * | 2 | PLANAR_MODE | | * | 3 | CUBIC_MODE | | * | 4 | PROJECTION_MODE | | * | 5 | SKYBOX_MODE | | * | 6 | INVCUBIC_MODE | | * | 7 | EQUIRECTANGULAR_MODE | | * | 8 | FIXED_EQUIRECTANGULAR_MODE | | * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | | */ set coordinatesMode(value) { if (this._coordinatesMode === value) { return; } this._coordinatesMode = value; if (this._scene) { this._scene.markAllMaterialsAsDirty(1, (mat) => { return mat.hasTexture(this); }); } } get coordinatesMode() { return this._coordinatesMode; } /** * | Value | Type | Description | * | ----- | ------------------ | ----------- | * | 0 | CLAMP_ADDRESSMODE | | * | 1 | WRAP_ADDRESSMODE | | * | 2 | MIRROR_ADDRESSMODE | | */ get wrapU() { return this._wrapU; } set wrapU(value) { this._wrapU = value; } /** * | Value | Type | Description | * | ----- | ------------------ | ----------- | * | 0 | CLAMP_ADDRESSMODE | | * | 1 | WRAP_ADDRESSMODE | | * | 2 | MIRROR_ADDRESSMODE | | */ get wrapV() { return this._wrapV; } set wrapV(value) { this._wrapV = value; } /** * Define if the texture is a cube texture or if false a 2d texture. */ get isCube() { if (!this._texture) { return this._isCube; } return this._texture.isCube; } // eslint-disable-next-line @typescript-eslint/naming-convention set isCube(value) { if (!this._texture) { this._isCube = value; } else { this._texture.isCube = value; } } /** * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture. */ get is3D() { if (!this._texture) { return false; } return this._texture.is3D; } // eslint-disable-next-line @typescript-eslint/naming-convention set is3D(value) { if (!this._texture) { return; } this._texture.is3D = value; } /** * Define if the texture is a 2d array texture (webgl 2) or if false a 2d texture. */ get is2DArray() { if (!this._texture) { return false; } return this._texture.is2DArray; } // eslint-disable-next-line @typescript-eslint/naming-convention set is2DArray(value) { if (!this._texture) { return; } this._texture.is2DArray = value; } /** * Define if the texture contains data in gamma space (most of the png/jpg aside bump). * HDR texture are usually stored in linear space. * This only impacts the PBR and Background materials */ get gammaSpace() { if (!this._texture) { return this._gammaSpace; } else { if (this._texture._gammaSpace === null) { this._texture._gammaSpace = this._gammaSpace; } } return this._texture._gammaSpace && !this._texture._useSRGBBuffer; } set gammaSpace(gamma) { if (!this._texture) { if (this._gammaSpace === gamma) { return; } this._gammaSpace = gamma; } else { if (this._texture._gammaSpace === gamma) { return; } this._texture._gammaSpace = gamma; } this.getScene()?.markAllMaterialsAsDirty(1, (mat) => { return mat.hasTexture(this); }); } /** * Gets or sets whether or not the texture contains RGBD data. */ get isRGBD() { return this._texture != null && this._texture._isRGBD; } set isRGBD(value) { if (value === this.isRGBD) { return; } if (this._texture) { this._texture._isRGBD = value; } this.getScene()?.markAllMaterialsAsDirty(1, (mat) => { return mat.hasTexture(this); }); } /** * Are mip maps generated for this texture or not. */ get noMipmap() { return false; } /** * With prefiltered texture, defined the offset used during the prefiltering steps. */ get lodGenerationOffset() { if (this._texture) { return this._texture._lodGenerationOffset; } return 0; } set lodGenerationOffset(value) { if (this._texture) { this._texture._lodGenerationOffset = value; } } /** * With prefiltered texture, defined the scale used during the prefiltering steps. */ get lodGenerationScale() { if (this._texture) { return this._texture._lodGenerationScale; } return 0; } set lodGenerationScale(value) { if (this._texture) { this._texture._lodGenerationScale = value; } } /** * With prefiltered texture, defined if the specular generation is based on a linear ramp. * By default we are using a log2 of the linear roughness helping to keep a better resolution for * average roughness values. */ get linearSpecularLOD() { if (this._texture) { return this._texture._linearSpecularLOD; } return false; } set linearSpecularLOD(value) { if (this._texture) { this._texture._linearSpecularLOD = value; } } /** * In case a better definition than spherical harmonics is required for the diffuse part of the environment. * You can set the irradiance texture to rely on a texture instead of the spherical approach. * This texture need to have the same characteristics than its parent (Cube vs 2d, coordinates mode, Gamma/Linear, RGBD). */ get irradianceTexture() { if (this._texture) { return this._texture._irradianceTexture; } return null; } set irradianceTexture(value) { if (this._texture) { this._texture._irradianceTexture = value; } } /** * Define the unique id of the texture in the scene. */ get uid() { if (!this._uid) { this._uid = RandomGUID(); } return this._uid; } /** * Return a string representation of the texture. * @returns the texture as a string */ toString() { return this.name; } /** * Get the class name of the texture. * @returns "BaseTexture" */ getClassName() { return "BaseTexture"; } /** * Callback triggered when the texture has been disposed. * Kept for back compatibility, you can use the onDisposeObservable instead. */ set onDispose(callback) { if (this._onDisposeObserver) { this.onDisposeObservable.remove(this._onDisposeObserver); } this._onDisposeObserver = this.onDisposeObservable.add(callback); } /** * Define if the texture is preventing a material to render or not. * If not and the texture is not ready, the engine will use a default black texture instead. */ get isBlocking() { return true; } /** * Was there any loading error? */ get loadingError() { return this._loadingError; } /** * If a loading error occurred this object will be populated with information about the error. */ get errorObject() { return this._errorObject; } /** * Instantiates a new BaseTexture. * Base class of all the textures in babylon. * It groups all the common properties the materials, post process, lights... might need * in order to make a correct use of the texture. * @param sceneOrEngine Define the scene or engine the texture belongs to * @param internalTexture Define the internal texture associated with the texture */ constructor(sceneOrEngine, internalTexture = null) { super(null); this.metadata = null; this.reservedDataStore = null; this._hasAlpha = false; this._getAlphaFromRGB = false; this.level = 1; this._coordinatesIndex = 0; this.optimizeUVAllocation = true; this._coordinatesMode = 0; this.wrapR = 1; this.anisotropicFilteringLevel = _BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL; this._isCube = false; this._gammaSpace = true; this.invertZ = false; this.lodLevelInAlpha = false; this._dominantDirection = null; this.isRenderTarget = false; this._prefiltered = false; this._forceSerialize = false; this.animations = []; this.onDisposeObservable = new Observable(); this._onDisposeObserver = null; this._scene = null; this._uid = null; this._parentContainer = null; this._loadingError = false; if (sceneOrEngine) { if (_BaseTexture._IsScene(sceneOrEngine)) { this._scene = sceneOrEngine; } else { this._engine = sceneOrEngine; } } else { this._scene = EngineStore.LastCreatedScene; } if (this._scene) { this.uniqueId = this._scene.getUniqueId(); this._scene.addTexture(this); this._engine = this._scene.getEngine(); } this._texture = internalTexture; this._uid = null; } /** * Get the scene the texture belongs to. * @returns the scene or null if undefined */ getScene() { return this._scene; } /** @internal */ _getEngine() { return this._engine; } /** * Get the texture transform matrix used to offset tile the texture for instance. * @returns the transformation matrix */ getTextureMatrix() { return Matrix.IdentityReadOnly; } /** * Get the texture reflection matrix used to rotate/transform the reflection. * @returns the reflection matrix */ getReflectionTextureMatrix() { return Matrix.IdentityReadOnly; } /** * Gets a suitable rotate/transform matrix when the texture is used for refraction. * There's a separate function from getReflectionTextureMatrix because refraction requires a special configuration of the matrix in right-handed mode. * @returns The refraction matrix */ getRefractionTextureMatrix() { return this.getReflectionTextureMatrix(); } /** * Get if the texture is ready to be consumed (either it is ready or it is not blocking) * @returns true if ready, not blocking or if there was an error loading the texture */ isReadyOrNotBlocking() { return !this.isBlocking || this.isReady() || this.loadingError; } /** * Scales the texture if is `canRescale()` * @param ratio the resize factor we want to use to rescale */ // eslint-disable-next-line @typescript-eslint/no-unused-vars scale(ratio) { } /** * Get if the texture can rescale. */ get canRescale() { return false; } /** * @internal */ _getFromCache(url, noMipmap, sampling, invertY, useSRGBBuffer, isCube) { const engine = this._getEngine(); if (!engine) { return null; } const correctedUseSRGBBuffer = engine._getUseSRGBBuffer(!!useSRGBBuffer, noMipmap); const texturesCache = engine.getLoadedTexturesCache(); for (let index = 0; index < texturesCache.length; index++) { const texturesCacheEntry = texturesCache[index]; if (useSRGBBuffer === void 0 || correctedUseSRGBBuffer === texturesCacheEntry._useSRGBBuffer) { if (invertY === void 0 || invertY === texturesCacheEntry.invertY) { if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) { if (!sampling || sampling === texturesCacheEntry.samplingMode) { if (isCube === void 0 || isCube === texturesCacheEntry.isCube) { texturesCacheEntry.incrementReferences(); return texturesCacheEntry; } } } } } } return null; } /** @internal */ _rebuild(_fromContextLost = false) { } /** * Clones the texture. * @returns the cloned texture */ clone() { return null; } /** * Get the texture underlying type (INT, FLOAT...) */ get textureType() { if (!this._texture) { return 0; } return this._texture.type !== void 0 ? this._texture.type : 0; } /** * Get the texture underlying format (RGB, RGBA...) */ get textureFormat() { if (!this._texture) { return 5; } return this._texture.format !== void 0 ? this._texture.format : 5; } /** * Indicates that textures need to be re-calculated for all materials */ _markAllSubMeshesAsTexturesDirty() { const scene = this.getScene(); if (!scene) { return; } scene.markAllMaterialsAsDirty(1); } /** * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer. * This will returns an RGBA array buffer containing either in values (0-255) or * float values (0-1) depending of the underlying buffer type. * @param faceIndex defines the face of the texture to read (in case of cube texture) * @param level defines the LOD level of the texture to read (in case of Mip Maps) * @param buffer defines a user defined buffer to fill with data (can be null) * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels * @param noDataConversion false to convert the data to Uint8Array (if texture type is UNSIGNED_BYTE) or to Float32Array (if texture type is anything but UNSIGNED_BYTE). If true, the type of the generated buffer (if buffer==null) will depend on the type of the texture * @param x defines the region x coordinates to start reading from (default to 0) * @param y defines the region y coordinates to start reading from (default to 0) * @param width defines the region width to read from (default to the texture size at level) * @param height defines the region width to read from (default to the texture size at level) * @returns The Array buffer promise containing the pixels data. */ readPixels(faceIndex = 0, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0, width = Number.MAX_VALUE, height = Number.MAX_VALUE) { if (!this._texture) { return null; } const engine = this._getEngine(); if (!engine) { return null; } const size = this.getSize(); let maxWidth = size.width; let maxHeight = size.height; if (level !== 0) { maxWidth = maxWidth / Math.pow(2, level); maxHeight = maxHeight / Math.pow(2, level); maxWidth = Math.round(maxWidth); maxHeight = Math.round(maxHeight); } width = Math.min(maxWidth, width); height = Math.min(maxHeight, height); try { if (this._texture.isCube) { return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion, x, y); } return engine._readTexturePixels(this._texture, width, height, -1, level, buffer, flushRenderer, noDataConversion, x, y); } catch (e) { return null; } } /** * @internal */ _readPixelsSync(faceIndex = 0, level = 0, buffer = null, flushRenderer = true, noDataConversion = false) { if (!this._texture) { return null; } const size = this.getSize(); let width = size.width; let height = size.height; const engine = this._getEngine(); if (!engine) { return null; } if (level != 0) { width = width / Math.pow(2, level); height = height / Math.pow(2, level); width = Math.round(width); height = Math.round(height); } try { if (this._texture.isCube) { return engine._readTexturePixelsSync(this._texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion); } return engine._readTexturePixelsSync(this._texture, width, height, -1, level, buffer, flushRenderer, noDataConversion); } catch (e) { return null; } } /** @internal */ get _lodTextureHigh() { if (this._texture) { return this._texture._lodTextureHigh; } return null; } /** @internal */ get _lodTextureMid() { if (this._texture) { return this._texture._lodTextureMid; } return null; } /** @internal */ get _lodTextureLow() { if (this._texture) { return this._texture._lodTextureLow; } return null; } /** * Dispose the texture and release its associated resources. */ dispose() { if (this._scene) { if (this._scene.stopAnimation) { this._scene.stopAnimation(this); } this._scene.removePendingData(this); const index = this._scene.textures.indexOf(this); if (index >= 0) { this._scene.textures.splice(index, 1); } this._scene.onTextureRemovedObservable.notifyObservers(this); this._scene = null; if (this._parentContainer) { const index2 = this._parentContainer.textures.indexOf(this); if (index2 > -1) { this._parentContainer.textures.splice(index2, 1); } this._parentContainer = null; } } this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); this.metadata = null; super.dispose(); } /** * Serialize the texture into a JSON representation that can be parsed later on. * @param allowEmptyName True to force serialization even if name is empty. Default: false * @returns the JSON representation of the texture */ serialize(allowEmptyName = false) { if (!this.name && !allowEmptyName) { return null; } const serializationObject = SerializationHelper.Serialize(this); SerializationHelper.AppendSerializedAnimations(this, serializationObject); return serializationObject; } /** * Helper function to be called back once a list of texture contains only ready textures. * @param textures Define the list of textures to wait for * @param callback Define the callback triggered once the entire list will be ready */ static WhenAllReady(textures, callback) { let numRemaining = textures.length; if (numRemaining === 0) { callback(); return; } for (let i = 0; i < textures.length; i++) { const texture = textures[i]; if (texture.isReady()) { if (--numRemaining === 0) { callback(); } } else { const onLoadObservable = texture.onLoadObservable; if (onLoadObservable) { onLoadObservable.addOnce(() => { if (--numRemaining === 0) { callback(); } }); } else { if (--numRemaining === 0) { callback(); } } } } } static _IsScene(sceneOrEngine) { return sceneOrEngine.getClassName() === "Scene"; } }; BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4; __decorate([ serialize() ], BaseTexture.prototype, "uniqueId", void 0); __decorate([ serialize() ], BaseTexture.prototype, "name", void 0); __decorate([ serialize() ], BaseTexture.prototype, "displayName", void 0); __decorate([ serialize() ], BaseTexture.prototype, "metadata", void 0); __decorate([ serialize("hasAlpha") ], BaseTexture.prototype, "_hasAlpha", void 0); __decorate([ serialize("getAlphaFromRGB") ], BaseTexture.prototype, "_getAlphaFromRGB", void 0); __decorate([ serialize() ], BaseTexture.prototype, "level", void 0); __decorate([ serialize("coordinatesIndex") ], BaseTexture.prototype, "_coordinatesIndex", void 0); __decorate([ serialize() ], BaseTexture.prototype, "optimizeUVAllocation", void 0); __decorate([ serialize("coordinatesMode") ], BaseTexture.prototype, "_coordinatesMode", void 0); __decorate([ serialize() ], BaseTexture.prototype, "wrapU", null); __decorate([ serialize() ], BaseTexture.prototype, "wrapV", null); __decorate([ serialize() ], BaseTexture.prototype, "wrapR", void 0); __decorate([ serialize() ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0); __decorate([ serialize() ], BaseTexture.prototype, "isCube", null); __decorate([ serialize() ], BaseTexture.prototype, "is3D", null); __decorate([ serialize() ], BaseTexture.prototype, "is2DArray", null); __decorate([ serialize() ], BaseTexture.prototype, "gammaSpace", null); __decorate([ serialize() ], BaseTexture.prototype, "invertZ", void 0); __decorate([ serialize() ], BaseTexture.prototype, "lodLevelInAlpha", void 0); __decorate([ serialize() ], BaseTexture.prototype, "lodGenerationOffset", null); __decorate([ serialize() ], BaseTexture.prototype, "lodGenerationScale", null); __decorate([ serialize() ], BaseTexture.prototype, "linearSpecularLOD", null); __decorate([ serializeAsTexture() ], BaseTexture.prototype, "irradianceTexture", null); __decorate([ serialize() ], BaseTexture.prototype, "isRenderTarget", void 0); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/instantiationTools.js var InstantiationTools; var init_instantiationTools = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/instantiationTools.js"() { init_logger(); init_typeStore(); InstantiationTools = class { static { __name(this, "InstantiationTools"); } /** * Tries to instantiate a new object from a given class name * @param className defines the class name to instantiate * @returns the new object or null if the system was not able to do the instantiation */ static Instantiate(className2) { if (this.RegisteredExternalClasses && this.RegisteredExternalClasses[className2]) { return this.RegisteredExternalClasses[className2]; } const internalClass = GetClass(className2); if (internalClass) { return internalClass; } Logger.Warn(className2 + " not found, you may have missed an import."); const arr = className2.split("."); let fn = window || this; for (let i = 0, len = arr.length; i < len; i++) { fn = fn[arr[i]]; } if (typeof fn !== "function") { return null; } return fn; } }; InstantiationTools.RegisteredExternalClasses = {}; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/copyTools.js function GenerateBase64StringFromPixelData(pixels, size, invertY = false) { const width = size.width; const height = size.height; if (pixels instanceof Float32Array) { let len = pixels.byteLength / pixels.BYTES_PER_ELEMENT; const npixels = new Uint8Array(len); while (--len >= 0) { let val = pixels[len]; if (val < 0) { val = 0; } else if (val > 1) { val = 1; } npixels[len] = val * 255; } pixels = npixels; } const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; const ctx = canvas.getContext("2d"); if (!ctx) { return null; } const imageData = ctx.createImageData(width, height); const castData = imageData.data; castData.set(pixels); ctx.putImageData(imageData, 0, 0); if (invertY) { const canvas2 = document.createElement("canvas"); canvas2.width = width; canvas2.height = height; const ctx2 = canvas2.getContext("2d"); if (!ctx2) { return null; } ctx2.translate(0, height); ctx2.scale(1, -1); ctx2.drawImage(canvas, 0, 0); return canvas2.toDataURL("image/png"); } return canvas.toDataURL("image/png"); } function GenerateBase64StringFromTexture(texture, faceIndex = 0, level = 0) { const internalTexture = texture.getInternalTexture(); if (!internalTexture) { return null; } const pixels = texture._readPixelsSync(faceIndex, level); if (!pixels) { return null; } return GenerateBase64StringFromPixelData(pixels, texture.getSize(), internalTexture.invertY); } async function GenerateBase64StringFromTextureAsync(texture, faceIndex = 0, level = 0) { const internalTexture = texture.getInternalTexture(); if (!internalTexture) { return null; } const pixels = await texture.readPixels(faceIndex, level); if (!pixels) { return null; } return GenerateBase64StringFromPixelData(pixels, texture.getSize(), internalTexture.invertY); } var CopyTools; var init_copyTools = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/copyTools.js"() { __name(GenerateBase64StringFromPixelData, "GenerateBase64StringFromPixelData"); __name(GenerateBase64StringFromTexture, "GenerateBase64StringFromTexture"); __name(GenerateBase64StringFromTextureAsync, "GenerateBase64StringFromTextureAsync"); CopyTools = { /** * Transform some pixel data to a base64 string * @param pixels defines the pixel data to transform to base64 * @param size defines the width and height of the (texture) data * @param invertY true if the data must be inverted for the Y coordinate during the conversion * @returns The base64 encoded string or null */ GenerateBase64StringFromPixelData, /** * Reads the pixels stored in the webgl texture and returns them as a base64 string * @param texture defines the texture to read pixels from * @param faceIndex defines the face of the texture to read (in case of cube texture) * @param level defines the LOD level of the texture to read (in case of Mip Maps) * @returns The base64 encoded string or null */ GenerateBase64StringFromTexture, /** * Reads the pixels stored in the webgl texture and returns them as a base64 string * @param texture defines the texture to read pixels from * @param faceIndex defines the face of the texture to read (in case of cube texture) * @param level defines the LOD level of the texture to read (in case of Mip Maps) * @returns The base64 encoded string or null wrapped in a promise */ GenerateBase64StringFromTextureAsync }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Compat/compatibilityOptions.js function setOpenGLOrientationForUV(value) { useOpenGLOrientationForUV = value; } var useOpenGLOrientationForUV, CompatibilityOptions; var init_compatibilityOptions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Compat/compatibilityOptions.js"() { useOpenGLOrientationForUV = false; __name(setOpenGLOrientationForUV, "setOpenGLOrientationForUV"); CompatibilityOptions = { /* eslint-disable @typescript-eslint/naming-convention */ get UseOpenGLOrientationForUV() { return useOpenGLOrientationForUV; }, set UseOpenGLOrientationForUV(value) { useOpenGLOrientationForUV = value; } /* eslint-enable @typescript-eslint/naming-convention */ }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/texture.js var Texture; var init_texture = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/texture.js"() { init_tslib_es6(); init_decorators(); init_observable(); init_math_vector(); init_baseTexture(); init_typeStore(); init_devTools(); init_timingTools(); init_instantiationTools(); init_math_plane(); init_stringTools(); init_copyTools(); init_compatibilityOptions(); init_decorators_serialization(); Texture = class _Texture extends BaseTexture { static { __name(this, "Texture"); } /** * @internal */ static _CreateVideoTexture(name260, src, scene, generateMipMaps = false, invertY = false, samplingMode = _Texture.TRILINEAR_SAMPLINGMODE, settings = {}, onError, format = 5) { throw _WarnImport("VideoTexture"); } /** * Are mip maps generated for this texture or not. */ get noMipmap() { return this._noMipmap; } /** Returns the texture mime type if it was defined by a loader (undefined else) */ get mimeType() { return this._mimeType; } /** * Is the texture preventing material to render while loading. * If false, a default texture will be used instead of the loading one during the preparation step. */ set isBlocking(value) { this._isBlocking = value; } get isBlocking() { return this._isBlocking; } /** * Gets a boolean indicating if the texture needs to be inverted on the y axis during loading */ get invertY() { return this._invertY; } /** * Instantiates a new texture. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input. * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction#texture * @param url defines the url of the picture to load as a texture * @param sceneOrEngine defines the scene or engine the texture will belong to * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture * @param invertY defines if the texture needs to be inverted on the y axis during loading * @param samplingMode defines the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...) * @param onLoad defines a callback triggered when the texture has been loaded * @param onError defines a callback triggered when an error occurred during the loading session * @param buffer defines the buffer to load the texture from in case the texture is loaded from a buffer representation * @param deleteBuffer defines if the buffer we are loading the texture from should be deleted after load * @param format defines the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...) * @param mimeType defines an optional mime type information * @param loaderOptions options to be passed to the loader * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) * @param forcedExtension defines the extension to use to pick the right loader */ constructor(url, sceneOrEngine, noMipmapOrOptions, invertY, samplingMode = _Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, buffer = null, deleteBuffer = false, format, mimeType, loaderOptions, creationFlags, forcedExtension) { super(sceneOrEngine); this.url = null; this.uOffset = 0; this.vOffset = 0; this.uScale = 1; this.vScale = 1; this.uAng = 0; this.vAng = 0; this.wAng = 0; this.uRotationCenter = 0.5; this.vRotationCenter = 0.5; this.wRotationCenter = 0.5; this.homogeneousRotationInUVTransform = false; this.inspectableCustomProperties = null; this._noMipmap = false; this._invertY = false; this._rowGenerationMatrix = null; this._cachedTextureMatrix = null; this._projectionModeMatrix = null; this._t0 = null; this._t1 = null; this._t2 = null; this._cachedUOffset = -1; this._cachedVOffset = -1; this._cachedUScale = 0; this._cachedVScale = 0; this._cachedUAng = -1; this._cachedVAng = -1; this._cachedWAng = -1; this._cachedReflectionProjectionMatrixId = -1; this._cachedURotationCenter = -1; this._cachedVRotationCenter = -1; this._cachedWRotationCenter = -1; this._cachedHomogeneousRotationInUVTransform = false; this._cachedIdentity3x2 = true; this._cachedReflectionTextureMatrix = null; this._cachedReflectionUOffset = -1; this._cachedReflectionVOffset = -1; this._cachedReflectionUScale = 0; this._cachedReflectionVScale = 0; this._cachedReflectionCoordinatesMode = -1; this._buffer = null; this._deleteBuffer = false; this._format = null; this._delayedOnLoad = null; this._delayedOnError = null; this.onLoadObservable = new Observable(); this._isBlocking = true; this.name = url || ""; this.url = url; let noMipmap; let useSRGBBuffer = false; let internalTexture = null; let gammaSpace = true; if (typeof noMipmapOrOptions === "object" && noMipmapOrOptions !== null) { noMipmap = noMipmapOrOptions.noMipmap ?? false; invertY = noMipmapOrOptions.invertY ?? !useOpenGLOrientationForUV; samplingMode = noMipmapOrOptions.samplingMode ?? _Texture.TRILINEAR_SAMPLINGMODE; onLoad = noMipmapOrOptions.onLoad ?? null; onError = noMipmapOrOptions.onError ?? null; buffer = noMipmapOrOptions.buffer ?? null; deleteBuffer = noMipmapOrOptions.deleteBuffer ?? false; format = noMipmapOrOptions.format; mimeType = noMipmapOrOptions.mimeType; loaderOptions = noMipmapOrOptions.loaderOptions; creationFlags = noMipmapOrOptions.creationFlags; useSRGBBuffer = noMipmapOrOptions.useSRGBBuffer ?? false; internalTexture = noMipmapOrOptions.internalTexture ?? null; gammaSpace = noMipmapOrOptions.gammaSpace ?? gammaSpace; forcedExtension = noMipmapOrOptions.forcedExtension ?? forcedExtension; } else { noMipmap = !!noMipmapOrOptions; } this._gammaSpace = gammaSpace; this._noMipmap = noMipmap; this._invertY = invertY === void 0 ? !useOpenGLOrientationForUV : invertY; this._initialSamplingMode = samplingMode; this._buffer = buffer; this._deleteBuffer = deleteBuffer; this._mimeType = mimeType; this._loaderOptions = loaderOptions; this._creationFlags = creationFlags; this._useSRGBBuffer = useSRGBBuffer; this._forcedExtension = forcedExtension; if (format !== void 0) { this._format = format; } const scene = this.getScene(); const engine = this._getEngine(); if (!engine) { return; } engine.onBeforeTextureInitObservable.notifyObservers(this); const load = /* @__PURE__ */ __name(() => { if (this._texture) { if (this._texture._invertVScale) { this.vScale *= -1; this.vOffset += 1; } if (this._texture._cachedWrapU !== null) { this.wrapU = this._texture._cachedWrapU; this._texture._cachedWrapU = null; } if (this._texture._cachedWrapV !== null) { this.wrapV = this._texture._cachedWrapV; this._texture._cachedWrapV = null; } if (this._texture._cachedWrapR !== null) { this.wrapR = this._texture._cachedWrapR; this._texture._cachedWrapR = null; } } if (this.onLoadObservable.hasObservers()) { this.onLoadObservable.notifyObservers(this); } if (onLoad) { onLoad(); } if (!this.isBlocking && scene) { scene.resetCachedMaterial(); } }, "load"); const errorHandler = /* @__PURE__ */ __name((message, exception) => { this._loadingError = true; this._errorObject = { message, exception }; if (onError) { onError(message, exception); } _Texture.OnTextureLoadErrorObservable.notifyObservers(this); }, "errorHandler"); if (!this.url && !internalTexture) { this._delayedOnLoad = load; this._delayedOnError = errorHandler; return; } this._texture = internalTexture ?? this._getFromCache(this.url, noMipmap, samplingMode, this._invertY, useSRGBBuffer, this.isCube); if (!this._texture) { if (!scene || !scene.useDelayedTextureLoading) { try { this._texture = engine.createTexture(this.url, noMipmap, this._invertY, scene, samplingMode, load, errorHandler, this._buffer, void 0, this._format, this._forcedExtension, mimeType, loaderOptions, creationFlags, useSRGBBuffer); } catch (e) { errorHandler("error loading", e); throw e; } if (deleteBuffer) { this._buffer = null; } } else { this.delayLoadState = 4; this._delayedOnLoad = load; this._delayedOnError = errorHandler; } } else { if (this._texture.isReady) { TimingTools.SetImmediate(() => load()); } else { const loadObserver = this._texture.onLoadedObservable.add(load); this._texture.onErrorObservable.add((e) => { errorHandler(e.message, e.exception); this._texture?.onLoadedObservable.remove(loadObserver); }); } } } /** * Update the url (and optional buffer) of this texture if url was null during construction. * @param url the url of the texture * @param buffer the buffer of the texture (defaults to null) * @param onLoad callback called when the texture is loaded (defaults to null) * @param forcedExtension defines the extension to use to pick the right loader */ updateURL(url, buffer = null, onLoad, forcedExtension) { if (this.url) { this.releaseInternalTexture(); this.getScene().markAllMaterialsAsDirty(1, (mat) => { return mat.hasTexture(this); }); } if (!this.name || this.name.startsWith("data:")) { this.name = url; } this.url = url; this._buffer = buffer; this._forcedExtension = forcedExtension; this.delayLoadState = 4; const existingOnLoad = this._delayedOnLoad; const load = /* @__PURE__ */ __name(() => { if (existingOnLoad) { existingOnLoad(); } else if (this.onLoadObservable.hasObservers()) { this.onLoadObservable.notifyObservers(this); } if (onLoad) { onLoad(); } }, "load"); this._delayedOnLoad = load; this.delayLoad(); } /** * Finish the loading sequence of a texture flagged as delayed load. * @internal */ delayLoad() { if (this.delayLoadState !== 4) { return; } const scene = this.getScene(); if (!scene) { return; } let url = this.url; if (!url && (this.name.indexOf("://") > 0 || this.name.startsWith("data:"))) { url = this.name; } this.delayLoadState = 1; this._texture = this._getFromCache(url, this._noMipmap, this.samplingMode, this._invertY, this._useSRGBBuffer, this.isCube); if (!this._texture) { this._texture = scene.getEngine().createTexture(url, this._noMipmap, this._invertY, scene, this.samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format, this._forcedExtension, this._mimeType, this._loaderOptions, this._creationFlags, this._useSRGBBuffer); if (this._deleteBuffer) { this._buffer = null; } } else { if (this._delayedOnLoad) { if (this._texture.isReady) { TimingTools.SetImmediate(this._delayedOnLoad); } else { this._texture.onLoadedObservable.add(this._delayedOnLoad); } } } this._delayedOnLoad = null; this._delayedOnError = null; } _prepareRowForTextureGeneration(x, y, z, t) { x *= this._cachedUScale; y *= this._cachedVScale; x -= this.uRotationCenter * this._cachedUScale; y -= this.vRotationCenter * this._cachedVScale; z -= this.wRotationCenter; Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t); t.x += this.uRotationCenter * this._cachedUScale + this._cachedUOffset; t.y += this.vRotationCenter * this._cachedVScale + this._cachedVOffset; t.z += this.wRotationCenter; } /** * Get the current texture matrix which includes the requested offsetting, tiling and rotation components. * @param uBase The horizontal base offset multiplier (1 by default) * @returns the transform matrix of the texture. */ getTextureMatrix(uBase = 1) { if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale * uBase === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng && this.uRotationCenter === this._cachedURotationCenter && this.vRotationCenter === this._cachedVRotationCenter && this.wRotationCenter === this._cachedWRotationCenter && this.homogeneousRotationInUVTransform === this._cachedHomogeneousRotationInUVTransform) { return this._cachedTextureMatrix; } this._cachedUOffset = this.uOffset; this._cachedVOffset = this.vOffset; this._cachedUScale = this.uScale * uBase; this._cachedVScale = this.vScale; this._cachedUAng = this.uAng; this._cachedVAng = this.vAng; this._cachedWAng = this.wAng; this._cachedURotationCenter = this.uRotationCenter; this._cachedVRotationCenter = this.vRotationCenter; this._cachedWRotationCenter = this.wRotationCenter; this._cachedHomogeneousRotationInUVTransform = this.homogeneousRotationInUVTransform; if (!this._cachedTextureMatrix || !this._rowGenerationMatrix) { this._cachedTextureMatrix = Matrix.Zero(); this._rowGenerationMatrix = new Matrix(); this._t0 = Vector3.Zero(); this._t1 = Vector3.Zero(); this._t2 = Vector3.Zero(); } Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix); if (this.homogeneousRotationInUVTransform) { Matrix.TranslationToRef(-this._cachedURotationCenter, -this._cachedVRotationCenter, -this._cachedWRotationCenter, TmpVectors.Matrix[0]); Matrix.TranslationToRef(this._cachedURotationCenter, this._cachedVRotationCenter, this._cachedWRotationCenter, TmpVectors.Matrix[1]); Matrix.ScalingToRef(this._cachedUScale, this._cachedVScale, 0, TmpVectors.Matrix[2]); Matrix.TranslationToRef(this._cachedUOffset, this._cachedVOffset, 0, TmpVectors.Matrix[3]); TmpVectors.Matrix[0].multiplyToRef(this._rowGenerationMatrix, this._cachedTextureMatrix); this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[1], this._cachedTextureMatrix); this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[2], this._cachedTextureMatrix); this._cachedTextureMatrix.multiplyToRef(TmpVectors.Matrix[3], this._cachedTextureMatrix); this._cachedTextureMatrix.setRowFromFloats(2, this._cachedTextureMatrix.m[12], this._cachedTextureMatrix.m[13], this._cachedTextureMatrix.m[14], 1); } else { this._prepareRowForTextureGeneration(0, 0, 0, this._t0); this._prepareRowForTextureGeneration(1, 0, 0, this._t1); this._prepareRowForTextureGeneration(0, 1, 0, this._t2); this._t1.subtractInPlace(this._t0); this._t2.subtractInPlace(this._t0); Matrix.FromValuesToRef(this._t1.x, this._t1.y, this._t1.z, 0, this._t2.x, this._t2.y, this._t2.z, 0, this._t0.x, this._t0.y, this._t0.z, 0, 0, 0, 0, 1, this._cachedTextureMatrix); } const scene = this.getScene(); if (!scene) { return this._cachedTextureMatrix; } const previousIdentity3x2 = this._cachedIdentity3x2; this._cachedIdentity3x2 = this._cachedTextureMatrix.isIdentityAs3x2(); if (this.optimizeUVAllocation && previousIdentity3x2 !== this._cachedIdentity3x2) { scene.markAllMaterialsAsDirty(1, (mat) => { return mat.hasTexture(this); }); } return this._cachedTextureMatrix; } /** * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance. * @returns The reflection texture transform */ getReflectionTextureMatrix() { const scene = this.getScene(); if (!scene) { return this._cachedReflectionTextureMatrix; } if (this.uOffset === this._cachedReflectionUOffset && this.vOffset === this._cachedReflectionVOffset && this.uScale === this._cachedReflectionUScale && this.vScale === this._cachedReflectionVScale && this.coordinatesMode === this._cachedReflectionCoordinatesMode) { if (this.coordinatesMode === _Texture.PROJECTION_MODE) { if (this._cachedReflectionProjectionMatrixId === scene.getProjectionMatrix().updateFlag) { return this._cachedReflectionTextureMatrix; } } else { return this._cachedReflectionTextureMatrix; } } if (!this._cachedReflectionTextureMatrix) { this._cachedReflectionTextureMatrix = Matrix.Zero(); } if (!this._projectionModeMatrix) { this._projectionModeMatrix = Matrix.Zero(); } const flagMaterialsAsTextureDirty = this._cachedReflectionCoordinatesMode !== this.coordinatesMode; this._cachedReflectionUOffset = this.uOffset; this._cachedReflectionVOffset = this.vOffset; this._cachedReflectionUScale = this.uScale; this._cachedReflectionVScale = this.vScale; this._cachedReflectionCoordinatesMode = this.coordinatesMode; switch (this.coordinatesMode) { case _Texture.PLANAR_MODE: { Matrix.IdentityToRef(this._cachedReflectionTextureMatrix); this._cachedReflectionTextureMatrix[0] = this.uScale; this._cachedReflectionTextureMatrix[5] = this.vScale; this._cachedReflectionTextureMatrix[12] = this.uOffset; this._cachedReflectionTextureMatrix[13] = this.vOffset; break; } case _Texture.PROJECTION_MODE: { Matrix.FromValuesToRef(0.5, 0, 0, 0, 0, -0.5, 0, 0, 0, 0, 0, 0, 0.5, 0.5, 1, 1, this._projectionModeMatrix); const projectionMatrix = scene.getProjectionMatrix(); this._cachedReflectionProjectionMatrixId = projectionMatrix.updateFlag; projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedReflectionTextureMatrix); break; } default: Matrix.IdentityToRef(this._cachedReflectionTextureMatrix); break; } if (flagMaterialsAsTextureDirty) { scene.markAllMaterialsAsDirty(1, (mat) => { return mat.hasTexture(this); }); } return this._cachedReflectionTextureMatrix; } /** * Clones the texture. * @returns the cloned texture */ clone() { const options = { noMipmap: this._noMipmap, invertY: this._invertY, samplingMode: this.samplingMode, onLoad: void 0, onError: void 0, buffer: this._texture ? this._texture._buffer : void 0, deleteBuffer: this._deleteBuffer, format: this.textureFormat, mimeType: this.mimeType, loaderOptions: this._loaderOptions, creationFlags: this._creationFlags, useSRGBBuffer: this._useSRGBBuffer }; return SerializationHelper.Clone(() => { return new _Texture(this._texture ? this._texture.url : null, this.getScene(), options); }, this); } /** * Serialize the texture to a JSON representation we can easily use in the respective Parse function. * @returns The JSON representation of the texture */ serialize() { const savedName = this.name; if (!_Texture.SerializeBuffers) { if (this.name.startsWith("data:")) { this.name = ""; } } if (this.name.startsWith("data:") && this.url === this.name) { this.url = ""; } const serializationObject = super.serialize(_Texture._SerializeInternalTextureUniqueId); if (!serializationObject) { return null; } if (_Texture.SerializeBuffers || _Texture.ForceSerializeBuffers) { if (typeof this._buffer === "string" && this._buffer.startsWith("data:")) { serializationObject.base64String = this._buffer; serializationObject.name = serializationObject.name.replace("data:", ""); } else if (this.url && this.url.startsWith("data:") && this._buffer instanceof Uint8Array) { const mimeType = this.mimeType || "image/png"; serializationObject.base64String = `data:${mimeType};base64,${EncodeArrayBufferToBase64(this._buffer)}`; } else if (_Texture.ForceSerializeBuffers || this.url && this.url.startsWith("blob:") || this._forceSerialize) { serializationObject.base64String = !this._engine || this._engine._features.supportSyncTextureRead ? GenerateBase64StringFromTexture(this) : GenerateBase64StringFromTextureAsync(this); } } serializationObject.invertY = this._invertY; serializationObject.samplingMode = this.samplingMode; serializationObject._creationFlags = this._creationFlags; serializationObject._useSRGBBuffer = this._useSRGBBuffer; if (_Texture._SerializeInternalTextureUniqueId) { serializationObject.internalTextureUniqueId = this._texture?.uniqueId; } serializationObject.internalTextureLabel = this._texture?.label; serializationObject.noMipmap = this._noMipmap; this.name = savedName; return serializationObject; } /** * Get the current class name of the texture useful for serialization or dynamic coding. * @returns "Texture" */ getClassName() { return "Texture"; } /** * Dispose the texture and release its associated resources. */ dispose() { super.dispose(); this.onLoadObservable.clear(); this._delayedOnLoad = null; this._delayedOnError = null; this._buffer = null; } /** * Parse the JSON representation of a texture in order to recreate the texture in the given scene. * @param parsedTexture Define the JSON representation of the texture * @param scene Define the scene the parsed texture should be instantiated in * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies * @returns The parsed texture if successful */ static Parse(parsedTexture, scene, rootUrl) { if (parsedTexture.customType) { const customTexture = InstantiationTools.Instantiate(parsedTexture.customType); const parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl); if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) { if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) { parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode); } } return parsedCustomTexture; } if (parsedTexture.isCube && !parsedTexture.isRenderTarget) { return _Texture._CubeTextureParser(parsedTexture, scene, rootUrl); } const hasInternalTextureUniqueId = parsedTexture.internalTextureUniqueId !== void 0; if (!parsedTexture.name && !parsedTexture.isRenderTarget && !hasInternalTextureUniqueId) { return null; } let internalTexture; if (hasInternalTextureUniqueId) { const cache = scene.getEngine().getLoadedTexturesCache(); for (const texture2 of cache) { if (texture2.uniqueId === parsedTexture.internalTextureUniqueId) { internalTexture = texture2; break; } } } const onLoaded = /* @__PURE__ */ __name((texture2) => { if (texture2 && texture2._texture) { texture2._texture._cachedWrapU = null; texture2._texture._cachedWrapV = null; texture2._texture._cachedWrapR = null; } if (parsedTexture.samplingMode) { const sampling = parsedTexture.samplingMode; if (texture2 && texture2.samplingMode !== sampling) { texture2.updateSamplingMode(sampling); } } if (texture2 && parsedTexture.animations) { for (let animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) { const parsedAnimation = parsedTexture.animations[animationIndex]; const internalClass = GetClass("BABYLON.Animation"); if (internalClass) { texture2.animations.push(internalClass.Parse(parsedAnimation)); } } } if (texture2 && texture2._texture) { if (hasInternalTextureUniqueId && !internalTexture) { texture2._texture._setUniqueId(parsedTexture.internalTextureUniqueId); } texture2._texture.label = parsedTexture.internalTextureLabel; } }, "onLoaded"); const texture = SerializationHelper.Parse(() => { let generateMipMaps = true; if (parsedTexture.noMipmap) { generateMipMaps = false; } if (parsedTexture.mirrorPlane) { const mirrorTexture = _Texture._CreateMirror(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps); mirrorTexture._waitingRenderList = parsedTexture.renderList; mirrorTexture.mirrorPlane = Plane.FromArray(parsedTexture.mirrorPlane); onLoaded(mirrorTexture); return mirrorTexture; } else if (parsedTexture.isRenderTarget && !parsedTexture.base64String) { let renderTargetTexture = null; if (parsedTexture.isCube) { if (scene.reflectionProbes) { for (let index = 0; index < scene.reflectionProbes.length; index++) { const probe = scene.reflectionProbes[index]; if (probe.name === parsedTexture.name) { return probe.cubeTexture; } } } } else { renderTargetTexture = _Texture._CreateRenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps, parsedTexture._creationFlags ?? 0); renderTargetTexture._waitingRenderList = parsedTexture.renderList; } onLoaded(renderTargetTexture); return renderTargetTexture; } else if (parsedTexture.isVideo) { const texture2 = _Texture._CreateVideoTexture(rootUrl + (parsedTexture.url || parsedTexture.name), rootUrl + (parsedTexture.src || parsedTexture.url), scene, generateMipMaps, parsedTexture.invertY, parsedTexture.samplingMode, parsedTexture.settings || {}); onLoaded(texture2); return texture2; } else { let texture2; if (parsedTexture.base64String && !internalTexture) { texture2 = _Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.base64String, scene, !generateMipMaps, parsedTexture.invertY, parsedTexture.samplingMode, () => { onLoaded(texture2); }, parsedTexture._creationFlags ?? 0, parsedTexture._useSRGBBuffer ?? false); texture2.name = parsedTexture.name; } else { let url; if (parsedTexture.name && (parsedTexture.name.indexOf("://") > 0 || parsedTexture.name.startsWith("data:"))) { url = parsedTexture.name; } else { url = rootUrl + parsedTexture.name; } if (parsedTexture.url && (parsedTexture.url.startsWith("data:") || _Texture.UseSerializedUrlIfAny)) { url = parsedTexture.url; } const options = { noMipmap: !generateMipMaps, invertY: parsedTexture.invertY, samplingMode: parsedTexture.samplingMode, onLoad: /* @__PURE__ */ __name(() => { onLoaded(texture2); }, "onLoad"), internalTexture }; texture2 = new _Texture(url, scene, options); } return texture2; } }, parsedTexture, scene); return texture; } /** * Creates a texture from its base 64 representation. * @param data Define the base64 payload without the data: prefix * @param name Define the name of the texture in the scene useful fo caching purpose for instance * @param scene Define the scene the texture should belong to * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture * @param invertY define if the texture needs to be inverted on the y axis during loading * @param samplingMode define the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...) * @param onLoad define a callback triggered when the texture has been loaded * @param onError define a callback triggered when an error occurred during the loading session * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...) * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) * @param forcedExtension defines the extension to use to pick the right loader * @returns the created texture */ static CreateFromBase64String(data, name260, scene, noMipmapOrOptions, invertY, samplingMode = _Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags, forcedExtension) { return new _Texture("data:" + name260, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, data, false, format, void 0, void 0, creationFlags, forcedExtension); } /** * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in) * @param name Define the name of the texture in the scene useful fo caching purpose for instance * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation * @param scene Define the scene the texture should belong to * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load * @param noMipmapOrOptions defines if the texture will require mip maps or not or set of all options to create the texture * @param invertY define if the texture needs to be inverted on the y axis during loading * @param samplingMode define the sampling mode we want for the texture while fetching from it (Texture.NEAREST_SAMPLINGMODE...) * @param onLoad define a callback triggered when the texture has been loaded * @param onError define a callback triggered when an error occurred during the loading session * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...) * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) * @param forcedExtension defines the extension to use to pick the right loader * @returns the created texture */ static LoadFromDataString(name260, buffer, scene, deleteBuffer = false, noMipmapOrOptions, invertY = true, samplingMode = _Texture.TRILINEAR_SAMPLINGMODE, onLoad = null, onError = null, format = 5, creationFlags, forcedExtension) { if (name260.substring(0, 5) !== "data:") { name260 = "data:" + name260; } return new _Texture(name260, scene, noMipmapOrOptions, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format, void 0, void 0, creationFlags, forcedExtension); } }; Texture.SerializeBuffers = true; Texture.ForceSerializeBuffers = false; Texture.OnTextureLoadErrorObservable = new Observable(); Texture._SerializeInternalTextureUniqueId = false; Texture._CubeTextureParser = (jsonTexture, scene, rootUrl) => { throw _WarnImport("CubeTexture"); }; Texture._CreateMirror = (name260, renderTargetSize, scene, generateMipMaps) => { throw _WarnImport("MirrorTexture"); }; Texture._CreateRenderTargetTexture = (name260, renderTargetSize, scene, generateMipMaps, creationFlags) => { throw _WarnImport("RenderTargetTexture"); }; Texture.NEAREST_SAMPLINGMODE = 1; Texture.NEAREST_NEAREST_MIPLINEAR = 8; Texture.BILINEAR_SAMPLINGMODE = 2; Texture.LINEAR_LINEAR_MIPNEAREST = 11; Texture.TRILINEAR_SAMPLINGMODE = 3; Texture.LINEAR_LINEAR_MIPLINEAR = 3; Texture.NEAREST_NEAREST_MIPNEAREST = 4; Texture.NEAREST_LINEAR_MIPNEAREST = 5; Texture.NEAREST_LINEAR_MIPLINEAR = 6; Texture.NEAREST_LINEAR = 7; Texture.NEAREST_NEAREST = 1; Texture.LINEAR_NEAREST_MIPNEAREST = 9; Texture.LINEAR_NEAREST_MIPLINEAR = 10; Texture.LINEAR_LINEAR = 2; Texture.LINEAR_NEAREST = 12; Texture.EXPLICIT_MODE = 0; Texture.SPHERICAL_MODE = 1; Texture.PLANAR_MODE = 2; Texture.CUBIC_MODE = 3; Texture.PROJECTION_MODE = 4; Texture.SKYBOX_MODE = 5; Texture.INVCUBIC_MODE = 6; Texture.EQUIRECTANGULAR_MODE = 7; Texture.FIXED_EQUIRECTANGULAR_MODE = 8; Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9; Texture.CLAMP_ADDRESSMODE = 0; Texture.WRAP_ADDRESSMODE = 1; Texture.MIRROR_ADDRESSMODE = 2; Texture.UseSerializedUrlIfAny = false; __decorate([ serialize() ], Texture.prototype, "url", void 0); __decorate([ serialize() ], Texture.prototype, "uOffset", void 0); __decorate([ serialize() ], Texture.prototype, "vOffset", void 0); __decorate([ serialize() ], Texture.prototype, "uScale", void 0); __decorate([ serialize() ], Texture.prototype, "vScale", void 0); __decorate([ serialize() ], Texture.prototype, "uAng", void 0); __decorate([ serialize() ], Texture.prototype, "vAng", void 0); __decorate([ serialize() ], Texture.prototype, "wAng", void 0); __decorate([ serialize() ], Texture.prototype, "uRotationCenter", void 0); __decorate([ serialize() ], Texture.prototype, "vRotationCenter", void 0); __decorate([ serialize() ], Texture.prototype, "wRotationCenter", void 0); __decorate([ serialize() ], Texture.prototype, "homogeneousRotationInUVTransform", void 0); __decorate([ serialize() ], Texture.prototype, "isBlocking", null); RegisterClass("BABYLON.Texture", Texture); SerializationHelper._TextureParser = Texture.Parse; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/drawWrapper.functions.js function IsWrapper(effect) { return effect.getPipelineContext === void 0; } var init_drawWrapper_functions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/drawWrapper.functions.js"() { __name(IsWrapper, "IsWrapper"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLShaderProcessors.js var WebGLShaderProcessor; var init_webGLShaderProcessors = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLShaderProcessors.js"() { WebGLShaderProcessor = class { static { __name(this, "WebGLShaderProcessor"); } constructor() { this.shaderLanguage = 0; } postProcessor(code, defines, isFragment, processingContext, parameters) { if (parameters.drawBuffersExtensionDisabled) { const regex = /#extension.+GL_EXT_draw_buffers.+(enable|require)/g; code = code.replace(regex, ""); } return code; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGL2ShaderProcessors.js var VaryingRegex, WebGL2ShaderProcessor; var init_webGL2ShaderProcessors = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGL2ShaderProcessors.js"() { VaryingRegex = /(flat\s)?\s*varying\s*.*/; WebGL2ShaderProcessor = class { static { __name(this, "WebGL2ShaderProcessor"); } constructor() { this.shaderLanguage = 0; } attributeProcessor(attribute) { return attribute.replace("attribute", "in"); } varyingCheck(varying, _isFragment) { return VaryingRegex.test(varying); } varyingProcessor(varying, isFragment) { return varying.replace("varying", isFragment ? "in" : "out"); } postProcessor(code, defines, isFragment) { const hasDrawBuffersExtension = code.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1; const 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, ""); code = code.replace(/texture2D\s*\(/g, "texture("); if (isFragment) { const hasOutput = code.search(/layout *\(location *= *0\) *out/g) !== -1; const hasDualSourceBlending = defines.indexOf("#define DUAL_SOURCE_BLENDING") !== -1; const outputDeclaration = hasDualSourceBlending ? "layout(location = 0, index = 0) out vec4 glFragColor;\nlayout(location = 0, index = 1) out vec4 glFragColor2;\n" : "layout(location = 0) out vec4 glFragColor;\n"; if (hasDualSourceBlending) { code = "#extension GL_EXT_blend_func_extended : require\n" + code; } 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 || hasOutput ? "" : outputDeclaration) + "void main("); } else { if (defines.indexOf("#define VERTEXOUTPUT_INVARIANT") >= 0) { code = "invariant gl_Position;\n" + code; } const hasMultiviewExtension = defines.indexOf("#define MULTIVIEW") !== -1; if (hasMultiviewExtension) { return "#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n" + code; } } return code; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Buffers/dataBuffer.js var DataBuffer; var init_dataBuffer = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Buffers/dataBuffer.js"() { DataBuffer = class _DataBuffer { static { __name(this, "DataBuffer"); } /** * Gets the underlying buffer */ get underlyingResource() { return null; } /** * Constructs the buffer */ constructor() { this.references = 0; this.capacity = 0; this.is32Bits = false; this.uniqueId = _DataBuffer._Counter++; } }; DataBuffer._Counter = 0; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/WebGL/webGLDataBuffer.js var WebGLDataBuffer; var init_webGLDataBuffer = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/WebGL/webGLDataBuffer.js"() { init_dataBuffer(); WebGLDataBuffer = class extends DataBuffer { static { __name(this, "WebGLDataBuffer"); } constructor(resource) { super(); this._buffer = resource; } get underlyingResource() { return this._buffer; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tools.functions.js function IsExponentOfTwo(value) { let count = 1; do { count *= 2; } while (count < value); return count === value; } function Mix(a, b, alpha) { return a * (1 - alpha) + b * alpha; } function NearestPOT(x) { const c = CeilingPOT(x); const f = FloorPOT(x); return c - x > x - f ? f : c; } function CeilingPOT(x) { x--; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; x++; return x; } function FloorPOT(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); } function GetExponentOfTwo(value, max, mode = 2) { let pot; switch (mode) { case 1: pot = FloorPOT(value); break; case 2: pot = NearestPOT(value); break; case 3: default: pot = CeilingPOT(value); break; } return Math.min(pot, max); } var init_tools_functions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tools.functions.js"() { __name(IsExponentOfTwo, "IsExponentOfTwo"); __name(Mix, "Mix"); __name(NearestPOT, "NearestPOT"); __name(CeilingPOT, "CeilingPOT"); __name(FloorPOT, "FloorPOT"); __name(GetExponentOfTwo, "GetExponentOfTwo"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLHardwareTexture.js var WebGLHardwareTexture; var init_webGLHardwareTexture = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLHardwareTexture.js"() { WebGLHardwareTexture = class { static { __name(this, "WebGLHardwareTexture"); } get underlyingResource() { return this._webGLTexture; } constructor(existingTexture = null, context) { this._MSAARenderBuffers = null; this._context = context; if (!existingTexture) { existingTexture = context.createTexture(); if (!existingTexture) { throw new Error("Unable to create webGL texture"); } } this.set(existingTexture); } setUsage() { } set(hardwareTexture) { this._webGLTexture = hardwareTexture; } reset() { this._webGLTexture = null; this._MSAARenderBuffers = null; } addMSAARenderBuffer(buffer) { if (!this._MSAARenderBuffers) { this._MSAARenderBuffers = []; } this._MSAARenderBuffers.push(buffer); } releaseMSAARenderBuffers() { if (this._MSAARenderBuffers) { for (const buffer of this._MSAARenderBuffers) { this._context.deleteRenderbuffer(buffer); } this._MSAARenderBuffers = null; } } getMSAARenderBuffer(index = 0) { return this._MSAARenderBuffers?.[index] ?? null; } release() { this.releaseMSAARenderBuffers(); if (this._webGLTexture) { this._context.deleteTexture(this._webGLTexture); } this.reset(); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/textureHelper.functions.js function IsDepthTexture(format) { return format === 13 || format === 14 || format === 15 || format === 16 || format === 17 || format === 18 || format === 19; } function GetTypeForDepthTexture(format) { switch (format) { case 13: case 17: case 18: case 14: case 16: return 1; case 15: return 5; case 19: return 0; } return 0; } function HasStencilAspect(format) { return format === 13 || format === 17 || format === 18 || format === 19; } var init_textureHelper_functions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/textureHelper.functions.js"() { __name(IsDepthTexture, "IsDepthTexture"); __name(GetTypeForDepthTexture, "GetTypeForDepthTexture"); __name(HasStencilAspect, "HasStencilAspect"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/thinEngine.js var thinEngine_exports = {}; __export(thinEngine_exports, { ThinEngine: () => ThinEngine }); var BufferPointer, ThinEngine; var init_thinEngine = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/thinEngine.js"() { init_thinEngine_functions(); init_drawWrapper_functions(); init_logger(); init_domManagement(); init_webGLShaderProcessors(); init_webGL2ShaderProcessors(); init_webGLDataBuffer(); init_tools_functions(); init_abstractEngine(); init_webGLHardwareTexture(); init_internalTexture(); init_effect(); init_abstractEngine_functions(); init_effect_functions(); init_textureHelper_functions(); init_alphaCullingState(); BufferPointer = class { static { __name(this, "BufferPointer"); } }; ThinEngine = class _ThinEngine extends AbstractEngine { static { __name(this, "ThinEngine"); } /** * Gets or sets the name of the engine */ get name() { return this._name; } set name(value) { this._name = value; } /** * Returns the version of the engine */ get version() { return this._webGLVersion; } /** * Gets or sets the relative url used to load shaders if using the engine in non-minified mode */ static get ShadersRepository() { return Effect.ShadersRepository; } static set ShadersRepository(value) { Effect.ShadersRepository = value; } /** * Gets a boolean indicating that the engine supports uniform buffers * @see https://doc.babylonjs.com/setup/support/webGL2#uniform-buffer-objets */ get supportsUniformBuffers() { return this.webGLVersion > 1 && !this.disableUniformBuffers; } /** * 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 needPOTTextures() { return this._webGLVersion < 2 || this.forcePOTTextures; } get _supportsHardwareTextureRescaling() { return false; } /** * 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 framebufferDimensionsObject(dimensions) { this._framebufferDimensionsObject = dimensions; } /** * Creates a new snapshot at the next frame using the current snapshotRenderingMode */ snapshotRenderingReset() { this.snapshotRendering = false; } /** * 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 already used the WebGL context * @param antialias defines whether anti-aliasing should be enabled (default value is "undefined", meaning that the browser may or may not enable it) * @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) */ constructor(canvasOrContext, antialias, options, adaptToDeviceRatio) { options = options || {}; super(antialias ?? options.antialias, options, adaptToDeviceRatio); this._name = "WebGL"; this.forcePOTTextures = false; this.validateShaderPrograms = false; this.disableUniformBuffers = false; this._webGLVersion = 1; this._vertexAttribArraysEnabled = []; this._uintIndicesCurrentlySet = false; this._currentBoundBuffer = new Array(); this._currentFramebuffer = null; 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._maxMSAASamplesOverride = null; this._unpackFlipYCached = null; this.enableUnpackFlipYCached = true; this._boundUniforms = {}; if (!canvasOrContext) { return; } let canvas = null; if (canvasOrContext.getContext) { canvas = canvasOrContext; if (options.preserveDrawingBuffer === void 0) { options.preserveDrawingBuffer = false; } if (options.xrCompatible === void 0) { options.xrCompatible = false; } if (navigator && navigator.userAgent) { this._setupMobileChecks(); const ua = navigator.userAgent; for (const exception of _ThinEngine.ExceptionList) { const key = exception.key; const targets = exception.targets; const check = new RegExp(key); if (check.test(ua)) { if (exception.capture && exception.captureConstraint) { const capture = exception.capture; const constraint = exception.captureConstraint; const regex = new RegExp(capture); const matches = regex.exec(ua); if (matches && matches.length > 0) { const capturedValue = parseInt(matches[matches.length - 1]); if (capturedValue >= constraint) { continue; } } } for (const target of targets) { switch (target) { case "uniformBuffer": this.disableUniformBuffers = true; break; case "vao": this.disableVertexArrayObjects = true; break; case "antialias": options.antialias = false; break; case "maxMSAASamples": this._maxMSAASamplesOverride = 1; break; } } } } } if (!this._doNotHandleContextLost) { this._onContextLost = (evt) => { evt.preventDefault(); this._contextWasLost = true; deleteStateObject(this._gl); Logger.Warn("WebGL context lost."); this.onContextLostObservable.notifyObservers(this); }; this._onContextRestored = () => { this._restoreEngineAfterContextLost(() => this._initGLContext()); }; canvas.addEventListener("webglcontextrestored", this._onContextRestored, false); options.powerPreference = options.powerPreference || "high-performance"; } else { this._onContextLost = () => { deleteStateObject(this._gl); }; } canvas.addEventListener("webglcontextlost", this._onContextLost, false); if (this._badDesktopOS) { options.xrCompatible = false; } if (!options.disableWebGL2Support) { try { this._gl = canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options); if (this._gl) { this._webGLVersion = 2; this._shaderPlatformName = "WEBGL2"; if (!this._gl.deleteQuery) { this._webGLVersion = 1; this._shaderPlatformName = "WEBGL1"; } } } catch (e) { } } 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; canvas = this._gl.canvas; if (this._gl.renderbufferStorageMultisample) { this._webGLVersion = 2; this._shaderPlatformName = "WEBGL2"; } else { this._shaderPlatformName = "WEBGL1"; } const attributes = this._gl.getContextAttributes(); if (attributes) { options.stencil = attributes.stencil; } } this._sharedInit(canvas); this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE); if (options.useHighPrecisionFloats !== void 0) { this._highPrecisionShadersAllowed = options.useHighPrecisionFloats; } this.resize(); this._initGLContext(); this._initFeatures(); for (let i = 0; i < this._caps.maxVertexAttribs; i++) { this._currentBufferPointers[i] = new BufferPointer(); } this._shaderProcessor = this.webGLVersion > 1 ? new WebGL2ShaderProcessor() : new WebGLShaderProcessor(); const versionToLog = `Babylon.js v${_ThinEngine.Version}`; Logger.Log(versionToLog + ` - ${this.description}`); if (this._renderingCanvas && this._renderingCanvas.setAttribute) { this._renderingCanvas.setAttribute("data-engine", versionToLog); } const stateObject = getStateObject(this._gl); stateObject.validateShaderPrograms = this.validateShaderPrograms; stateObject.parallelShaderCompile = this._caps.parallelShaderCompile; } _clearEmptyResources() { this._dummyFramebuffer = null; super._clearEmptyResources(); } /** * @internal */ _getShaderProcessingContext(shaderLanguage) { return null; } /** * Gets a boolean indicating if all created effects are ready * @returns true if all effects are ready */ areAllEffectsReady() { for (const key in this._compiledEffects) { const effect = this._compiledEffects[key]; if (!effect.isReady()) { return false; } } return true; } _initGLContext() { 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), shaderFloatPrecision: 0, parallelShaderCompile: this._gl.getExtension("KHR_parallel_shader_compile") || void 0, 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"), bptc: this._gl.getExtension("EXT_texture_compression_bptc") || this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"), s3tc: this._gl.getExtension("WEBGL_compressed_texture_s3tc") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"), // eslint-disable-next-line @typescript-eslint/naming-convention s3tc_srgb: this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb") || this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"), 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"), // also a requirement of OpenGL ES 3 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"), supportOcclusionQuery: this._webGLVersion > 1, canUseTimestampForTimerQuery: false, drawBuffersExtension: false, maxMSAASamples: 1, colorBufferFloat: !!(this._webGLVersion > 1 && this._gl.getExtension("EXT_color_buffer_float")), blendFloat: this._gl.getExtension("EXT_float_blend") !== null, supportFloatTexturesResolve: false, rg11b10ufColorRenderable: false, colorBufferHalfFloat: !!(this._webGLVersion > 1 && this._gl.getExtension("EXT_color_buffer_half_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, texelFetch: this._webGLVersion !== 1, blendMinMax: false, multiview: this._gl.getExtension("OVR_multiview2"), oculusMultiview: this._gl.getExtension("OCULUS_multiview"), depthTextureExtension: false, canUseGLInstanceID: this._webGLVersion > 1, canUseGLVertexID: this._webGLVersion > 1, supportComputeShaders: false, supportSRGBBuffers: false, supportTransformFeedbacks: this._webGLVersion > 1, textureMaxLevel: this._webGLVersion > 1, texture2DArrayMaxLayerCount: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS) : 128, disableMorphTargetTexture: false, textureNorm16: this._gl.getExtension("EXT_texture_norm16") ? true : false, blendParametersPerTarget: false, dualSourceBlending: false }; this._caps.supportFloatTexturesResolve = this._caps.colorBufferFloat; this._caps.rg11b10ufColorRenderable = this._caps.colorBufferFloat; this._glVersion = this._gl.getParameter(this._gl.VERSION); const 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 = this._gl.getParameter(this._gl.VENDOR) || "Unknown vendor"; } if (!this._glRenderer) { this._glRenderer = this._gl.getParameter(this._gl.RENDERER) || "Unknown renderer"; } if (this._gl.HALF_FLOAT_OES !== 36193) { this._gl.HALF_FLOAT_OES = 36193; } if (this._gl.RGBA16F !== 34842) { this._gl.RGBA16F = 34842; } if (this._gl.RGBA32F !== 34836) { this._gl.RGBA32F = 34836; } if (this._gl.DEPTH24_STENCIL8 !== 35056) { this._gl.DEPTH24_STENCIL8 = 35056; } 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) > 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; if (this._caps.textureNorm16) { this._gl.R16_EXT = 33322; this._gl.RG16_EXT = 33324; this._gl.RGB16_EXT = 32852; this._gl.RGBA16_EXT = 32859; this._gl.R16_SNORM_EXT = 36760; this._gl.RG16_SNORM_EXT = 36761; this._gl.RGB16_SNORM_EXT = 36762; this._gl.RGBA16_SNORM_EXT = 36763; } const oesDrawBuffersIndexed = this._gl.getExtension("OES_draw_buffers_indexed"); this._caps.blendParametersPerTarget = oesDrawBuffersIndexed ? true : false; this._alphaState = new AlphaState(this._caps.blendParametersPerTarget); if (oesDrawBuffersIndexed) { this._gl.blendEquationSeparateIndexed = oesDrawBuffersIndexed.blendEquationSeparateiOES.bind(oesDrawBuffersIndexed); this._gl.blendEquationIndexed = oesDrawBuffersIndexed.blendEquationiOES.bind(oesDrawBuffersIndexed); this._gl.blendFuncSeparateIndexed = oesDrawBuffersIndexed.blendFuncSeparateiOES.bind(oesDrawBuffersIndexed); this._gl.blendFuncIndexed = oesDrawBuffersIndexed.blendFunciOES.bind(oesDrawBuffersIndexed); this._gl.colorMaskIndexed = oesDrawBuffersIndexed.colorMaskiOES.bind(oesDrawBuffersIndexed); this._gl.disableIndexed = oesDrawBuffersIndexed.disableiOES.bind(oesDrawBuffersIndexed); this._gl.enableIndexed = oesDrawBuffersIndexed.enableiOES.bind(oesDrawBuffersIndexed); } this._caps.dualSourceBlending = this._gl.getExtension("WEBGL_blend_func_extended") ? true : false; if (this._caps.astc) { this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; } if (this._caps.bptc) { this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT = this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT; } if (this._caps.s3tc_srgb) { this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT; this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; } if (this._caps.etc2) { this._gl.COMPRESSED_SRGB8_ETC2 = this._caps.etc2.COMPRESSED_SRGB8_ETC2; this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; } if (this._webGLVersion > 1) { if (this._gl.HALF_FLOAT_OES !== 5131) { this._gl.HALF_FLOAT_OES = 5131; } } this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer(); if (this._webGLVersion > 1) { this._caps.drawBuffersExtension = true; this._caps.maxMSAASamples = this._maxMSAASamplesOverride !== null ? this._maxMSAASamplesOverride : this._gl.getParameter(this._gl.MAX_SAMPLES); this._caps.maxDrawBuffers = this._gl.getParameter(this._gl.MAX_DRAW_BUFFERS); } else { const drawBuffersExtension = this._gl.getExtension("WEBGL_draw_buffers"); if (drawBuffersExtension !== null) { this._caps.drawBuffersExtension = true; this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension); this._caps.maxDrawBuffers = this._gl.getParameter(drawBuffersExtension.MAX_DRAW_BUFFERS_WEBGL); this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER; for (let i = 0; i < 16; i++) { this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"]; } } } if (this._webGLVersion > 1) { this._caps.depthTextureExtension = true; } else { const 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; } } if (this.disableVertexArrayObjects) { this._caps.vertexArrayObject = false; } else if (this._webGLVersion > 1) { this._caps.vertexArrayObject = true; } else { const 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); } } if (this._webGLVersion > 1) { this._caps.instancedArrays = true; } else { const 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) { const vertexhighp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT); const fragmenthighp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT); if (vertexhighp && fragmenthighp) { this._caps.highPrecisionShaderSupported = vertexhighp.precision !== 0 && fragmenthighp.precision !== 0; this._caps.shaderFloatPrecision = Math.min(vertexhighp.precision, fragmenthighp.precision); } if (!this._shouldUseHighPrecisionShader) { const vertexmedp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.MEDIUM_FLOAT); const fragmentmedp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.MEDIUM_FLOAT); if (vertexmedp && fragmentmedp) { this._caps.shaderFloatPrecision = Math.min(vertexmedp.precision, fragmentmedp.precision); } } if (this._caps.shaderFloatPrecision < 10) { this._caps.shaderFloatPrecision = 10; } } if (this._webGLVersion > 1) { this._caps.blendMinMax = true; } else { const 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; } } if (!this._caps.supportSRGBBuffers) { if (this._webGLVersion > 1) { this._caps.supportSRGBBuffers = true; this._glSRGBExtensionValues = { SRGB: WebGL2RenderingContext.SRGB, SRGB8: WebGL2RenderingContext.SRGB8, SRGB8_ALPHA8: WebGL2RenderingContext.SRGB8_ALPHA8 }; } else { const sRGBExtension = this._gl.getExtension("EXT_sRGB"); if (sRGBExtension != null) { this._caps.supportSRGBBuffers = true; this._glSRGBExtensionValues = { SRGB: sRGBExtension.SRGB_EXT, SRGB8: sRGBExtension.SRGB_ALPHA_EXT, SRGB8_ALPHA8: sRGBExtension.SRGB_ALPHA_EXT }; } } if (this._creationOptions) { const forceSRGBBufferSupportState = this._creationOptions.forceSRGBBufferSupportState; if (forceSRGBBufferSupportState !== void 0) { this._caps.supportSRGBBuffers = this._caps.supportSRGBBuffers && forceSRGBBufferSupportState; } } } this._depthCullingState.depthTest = true; this._depthCullingState.depthFunc = this._gl.LEQUAL; this._depthCullingState.depthMask = true; this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits; for (let slot = 0; slot < this._maxSimultaneousTextures; slot++) { this._nextFreeTextureSlots.push(slot); } if (this._glRenderer === "Mali-G72") { this._caps.disableMorphTargetTexture = true; } } _initFeatures() { this._features = { forceBitmapOverHTMLImageElement: typeof HTMLImageElement === "undefined", supportRenderAndCopyToLodForFloatTextures: this._webGLVersion !== 1, supportDepthStencilTexture: this._webGLVersion !== 1, supportShadowSamplers: this._webGLVersion !== 1, uniformBufferHardCheckMatrix: false, allowTexturePrefiltering: this._webGLVersion !== 1, trackUbosInFrame: false, checkUbosContentBeforeUpload: false, supportCSM: this._webGLVersion !== 1, basisNeedsPOT: this._webGLVersion === 1, support3DTextures: this._webGLVersion !== 1, needTypeSuffixInShaderConstants: this._webGLVersion !== 1, supportMSAA: this._webGLVersion !== 1, supportSSAO2: this._webGLVersion !== 1, supportIBLShadows: this._webGLVersion !== 1, supportExtendedTextureFormats: this._webGLVersion !== 1, supportSwitchCaseInShader: this._webGLVersion !== 1, supportSyncTextureRead: true, needsInvertingBitmap: true, useUBOBindingCache: true, needShaderCodeInlining: false, needToAlwaysBindUniformBuffers: false, supportRenderPasses: false, supportSpriteInstancing: true, forceVertexBufferStrideAndOffsetMultiple4Bytes: false, _checkNonFloatVertexBuffersDontRecreatePipelineContext: false, _collectUbosUpdatedInFrame: false }; } /** * Gets version of the current webGL context * Keep it for back compat - use version instead */ get webGLVersion() { return this._webGLVersion; } /** * Gets a string identifying the name of the class * @returns "Engine" string */ getClassName() { return "ThinEngine"; } /** @internal */ _prepareWorkingCanvas() { if (this._workingCanvas) { return; } this._workingCanvas = this.createCanvas(1, 1); const context = this._workingCanvas.getContext("2d"); if (context) { this._workingContext = context; } } /** * Gets an object containing information about the current engine context * @returns an object containing the vendor, the renderer and the version of the current engine context */ getInfo() { return this.getGlInfo(); } /** * Gets an object containing information about the current webGL context * @returns an object containing the vendor, the renderer and the version of the current webGL context */ getGlInfo() { return { vendor: this._glVendor, renderer: this._glRenderer, version: this._glVersion }; } /**Gets driver info if available */ extractDriverInfo() { const glInfo = this.getGlInfo(); if (glInfo && glInfo.renderer) { return glInfo.renderer; } return ""; } /** * 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 */ getRenderWidth(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 */ getRenderHeight(useScreen = false) { if (!useScreen && this._currentRenderTarget) { return this._currentRenderTarget.height; } return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferHeight : this._gl.drawingBufferHeight; } /** * 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 * @param stencilClearValue defines the value to use to clear the stencil buffer (default is 0) */ clear(color, backBuffer, depth, stencil = false, stencilClearValue = 0) { const useStencilGlobalOnly = this.stencilStateComposer.useStencilGlobalOnly; this.stencilStateComposer.useStencilGlobalOnly = true; this.applyStates(); this.stencilStateComposer.useStencilGlobalOnly = useStencilGlobalOnly; let mode = 0; if (backBuffer && color) { let setBackBufferColor = true; if (this._currentRenderTarget) { const textureFormat = this._currentRenderTarget.texture?.format; if (textureFormat === 8 || textureFormat === 9 || textureFormat === 10 || textureFormat === 11) { const textureType = this._currentRenderTarget.texture?.type; if (textureType === 7 || textureType === 5) { _ThinEngine._TempClearColorUint32[0] = color.r * 255; _ThinEngine._TempClearColorUint32[1] = color.g * 255; _ThinEngine._TempClearColorUint32[2] = color.b * 255; _ThinEngine._TempClearColorUint32[3] = color.a * 255; this._gl.clearBufferuiv(this._gl.COLOR, 0, _ThinEngine._TempClearColorUint32); setBackBufferColor = false; } else { _ThinEngine._TempClearColorInt32[0] = color.r * 255; _ThinEngine._TempClearColorInt32[1] = color.g * 255; _ThinEngine._TempClearColorInt32[2] = color.b * 255; _ThinEngine._TempClearColorInt32[3] = color.a * 255; this._gl.clearBufferiv(this._gl.COLOR, 0, _ThinEngine._TempClearColorInt32); setBackBufferColor = false; } } } if (setBackBufferColor) { this._gl.clearColor(color.r, color.g, color.b, color.a !== void 0 ? color.a : 1); mode |= this._gl.COLOR_BUFFER_BIT; } } if (depth) { if (this.useReverseDepthBuffer) { this._depthCullingState.depthFunc = this._gl.GEQUAL; this._gl.clearDepth(0); } else { this._gl.clearDepth(1); } mode |= this._gl.DEPTH_BUFFER_BIT; } if (stencil) { this._gl.clearStencil(stencilClearValue); mode |= this._gl.STENCIL_BUFFER_BIT; } this._gl.clear(mode); } /** * @internal */ _viewport(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); } } /** * End the current frame */ endFrame() { super.endFrame(); if (this._badOS) { this.flushFramebuffer(); } } /** * Gets the performance monitor attached to this engine * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation */ get performanceMonitor() { throw new Error("Not Supported by ThinEngine"); } /** * Binds the frame buffer to the specified texture. * @param rtWrapper The render target wrapper to render to * @param faceIndex The face of the texture to render to in case of cube texture and if the render target wrapper is not a multi render target * @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 the frame buffer if the render target wrapper is not a multi render target */ bindFramebuffer(rtWrapper, faceIndex = 0, requiredWidth, requiredHeight, forceFullscreenViewport, lodLevel = 0, layer = 0) { const webglRtWrapper = rtWrapper; if (this._currentRenderTarget) { this._resolveAndGenerateMipMapsFramebuffer(this._currentRenderTarget); } this._currentRenderTarget = rtWrapper; this._bindUnboundFramebuffer(webglRtWrapper._framebuffer); const gl = this._gl; if (!rtWrapper.isMulti) { if (rtWrapper.is2DArray || rtWrapper.is3D) { gl.framebufferTextureLayer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, rtWrapper.texture._hardwareTexture?.underlyingResource, lodLevel, layer); webglRtWrapper._currentLOD = lodLevel; } else if (rtWrapper.isCube) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, rtWrapper.texture._hardwareTexture?.underlyingResource, lodLevel); } else if (webglRtWrapper._currentLOD !== lodLevel) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, rtWrapper.texture._hardwareTexture?.underlyingResource, lodLevel); webglRtWrapper._currentLOD = lodLevel; } } const depthStencilTexture = rtWrapper._depthStencilTexture; if (depthStencilTexture) { if (rtWrapper.is3D) { if (rtWrapper.texture.width !== depthStencilTexture.width || rtWrapper.texture.height !== depthStencilTexture.height || rtWrapper.texture.depth !== depthStencilTexture.depth) { Logger.Warn("Depth/Stencil attachment for 3D target must have same dimensions as color attachment"); } } const attachment = rtWrapper._depthStencilTextureWithStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; if (rtWrapper.is2DArray || rtWrapper.is3D) { gl.framebufferTextureLayer(gl.FRAMEBUFFER, attachment, depthStencilTexture._hardwareTexture?.underlyingResource, lodLevel, layer); } else if (rtWrapper.isCube) { gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._hardwareTexture?.underlyingResource, lodLevel); } else { gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, depthStencilTexture._hardwareTexture?.underlyingResource, lodLevel); } } if (webglRtWrapper._MSAAFramebuffer) { this._bindUnboundFramebuffer(webglRtWrapper._MSAAFramebuffer); } if (this._cachedViewport && !forceFullscreenViewport) { this.setViewport(this._cachedViewport, requiredWidth, requiredHeight); } else { if (!requiredWidth) { requiredWidth = rtWrapper.width; if (lodLevel) { requiredWidth = requiredWidth / Math.pow(2, lodLevel); } } if (!requiredHeight) { requiredHeight = rtWrapper.height; if (lodLevel) { requiredHeight = requiredHeight / Math.pow(2, lodLevel); } } this._viewport(0, 0, requiredWidth, requiredHeight); } this.wipeCaches(); } setStateCullFaceType(cullBackFaces, force) { const cullFace = this.cullBackFaces ?? cullBackFaces ?? true ? this._gl.BACK : this._gl.FRONT; if (this._depthCullingState.cullFace !== cullFace || force) { this._depthCullingState.cullFace = cullFace; } } /** * Set various states to the webGL context * @param culling defines culling state: true to enable culling, false to disable it * @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 if false, CW if true) * @param cullBackFaces true to cull back faces, false to cull front faces (if culling is enabled) * @param stencil stencil states to set * @param zOffsetUnits defines the value to apply to zOffsetUnits (0 by default) */ setState(culling, zOffset = 0, force, reverseSide = false, cullBackFaces, stencil, zOffsetUnits = 0) { if (this._depthCullingState.cull !== culling || force) { this._depthCullingState.cull = culling; } this.setStateCullFaceType(cullBackFaces, force); this.setZOffset(zOffset); this.setZOffsetUnits(zOffsetUnits); const frontFace = reverseSide ? this._gl.CW : this._gl.CCW; if (this._depthCullingState.frontFace !== frontFace || force) { this._depthCullingState.frontFace = frontFace; } this._stencilStateComposer.stencilMaterial = stencil; } _resolveAndGenerateMipMapsFramebuffer(texture, disableGenerateMipMaps = false) { const webglRtWrapper = texture; if (!webglRtWrapper.disableAutomaticMSAAResolve) { if (texture.isMulti) { this.resolveMultiFramebuffer(texture); } else { this.resolveFramebuffer(texture); } } if (!disableGenerateMipMaps) { if (texture.isMulti) { this.generateMipMapsMultiFramebuffer(texture); } else { this.generateMipMapsFramebuffer(texture); } } } /** * @internal */ _bindUnboundFramebuffer(framebuffer) { if (this._currentFramebuffer !== framebuffer) { this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer); this._currentFramebuffer = framebuffer; } } /** @internal */ _currentFrameBufferIsDefaultFrameBuffer() { return this._currentFramebuffer === null; } /** * Generates the mipmaps for a texture * @param texture texture to generate the mipmaps for */ generateMipmaps(texture) { const target = this._getTextureTarget(texture); this._bindTextureDirectly(target, texture, true); this._gl.generateMipmap(target); this._bindTextureDirectly(target, null); } /** * Unbind the current render target texture from the webGL context * @param texture defines the render target wrapper 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 */ unBindFramebuffer(texture, disableGenerateMipMaps, onBeforeUnbind) { const webglRtWrapper = texture; this._currentRenderTarget = null; this._resolveAndGenerateMipMapsFramebuffer(texture, disableGenerateMipMaps); if (onBeforeUnbind) { if (webglRtWrapper._MSAAFramebuffer) { this._bindUnboundFramebuffer(webglRtWrapper._framebuffer); } onBeforeUnbind(); } this._bindUnboundFramebuffer(null); } /** * Generates mipmaps for the texture of the (single) render target * @param texture The render target containing the texture to generate the mipmaps for */ generateMipMapsFramebuffer(texture) { if (!texture.isMulti && texture.texture?.generateMipMaps && !texture.isCube) { this.generateMipmaps(texture.texture); } } /** * Resolves the MSAA texture of the (single) render target into its non-MSAA version. * Note that if "texture" is not a MSAA render target, no resolve is performed. * @param texture The render target texture containing the MSAA textures to resolve */ resolveFramebuffer(texture) { const rtWrapper = texture; const gl = this._gl; if (!rtWrapper._MSAAFramebuffer || rtWrapper.isMulti) { return; } let bufferBits = rtWrapper.resolveMSAAColors ? gl.COLOR_BUFFER_BIT : 0; bufferBits |= rtWrapper._generateDepthBuffer && rtWrapper.resolveMSAADepth ? gl.DEPTH_BUFFER_BIT : 0; bufferBits |= rtWrapper._generateStencilBuffer && rtWrapper.resolveMSAAStencil ? gl.STENCIL_BUFFER_BIT : 0; gl.bindFramebuffer(gl.READ_FRAMEBUFFER, rtWrapper._MSAAFramebuffer); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, rtWrapper._framebuffer); gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, bufferBits, gl.NEAREST); } /** * Force a webGL flush (ie. a flush of all waiting webGL commands) */ flushFramebuffer() { this._gl.flush(); } /** * Unbind the current render target and bind the default framebuffer */ restoreDefaultFramebuffer() { if (this._currentRenderTarget) { this.unBindFramebuffer(this._currentRenderTarget); } else { this._bindUnboundFramebuffer(null); } if (this._cachedViewport) { this.setViewport(this._cachedViewport); } this.wipeCaches(); } // VBOs /** @internal */ _resetVertexBufferBinding() { this.bindArrayBuffer(null); this._cachedVertexBuffers = null; } /** * Creates a vertex buffer * @param data the data or size for the vertex buffer * @param _updatable whether the buffer should be created as updatable * @param _label defines the label of the buffer (for debug purpose) * @returns the new WebGL static buffer */ createVertexBuffer(data, _updatable, _label) { return this._createVertexBuffer(data, this._gl.STATIC_DRAW); } _createVertexBuffer(data, usage) { const vbo = this._gl.createBuffer(); if (!vbo) { throw new Error("Unable to create vertex buffer"); } const dataBuffer = new WebGLDataBuffer(vbo); this.bindArrayBuffer(dataBuffer); if (typeof data !== "number") { if (data instanceof Array) { this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), usage); dataBuffer.capacity = data.length * 4; } else { this._gl.bufferData(this._gl.ARRAY_BUFFER, data, usage); dataBuffer.capacity = data.byteLength; } } else { this._gl.bufferData(this._gl.ARRAY_BUFFER, new Uint8Array(data), usage); dataBuffer.capacity = data; } this._resetVertexBufferBinding(); dataBuffer.references = 1; return dataBuffer; } /** * Creates a dynamic vertex buffer * @param data the data for the dynamic vertex buffer * @param _label defines the label of the buffer (for debug purpose) * @returns the new WebGL dynamic buffer */ createDynamicVertexBuffer(data, _label) { return this._createVertexBuffer(data, this._gl.DYNAMIC_DRAW); } _resetIndexBufferBinding() { 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 * @param _label defines the label of the buffer (for debug purpose) * @returns a new webGL buffer */ createIndexBuffer(indices, updatable, _label) { const vbo = this._gl.createBuffer(); const dataBuffer = new WebGLDataBuffer(vbo); if (!vbo) { throw new Error("Unable to create index buffer"); } this.bindIndexBuffer(dataBuffer); const 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; } _normalizeIndexData(indices) { const bytesPerElement = indices.BYTES_PER_ELEMENT; if (bytesPerElement === 2) { return indices; } if (this._caps.uintIndices) { if (indices instanceof Uint32Array) { return indices; } else { for (let index = 0; index < indices.length; index++) { if (indices[index] >= 65535) { return new Uint32Array(indices); } } return new Uint16Array(indices); } } return new Uint16Array(indices); } /** * Bind a webGL buffer to the webGL context * @param buffer defines the buffer to bind */ bindArrayBuffer(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 */ bindUniformBlock(pipelineContext, blockName, index) { const program = pipelineContext.program; const uniformLocation = this._gl.getUniformBlockIndex(program, blockName); this._gl.uniformBlockBinding(program, uniformLocation, index); } // eslint-disable-next-line @typescript-eslint/naming-convention bindIndexBuffer(buffer) { if (!this._vaoRecordInProgress) { this._unbindVertexArrayObject(); } this._bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER); } _bindBuffer(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 */ updateArrayBuffer(data) { this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data); } _vertexAttribPointer(buffer, indx, size, type, normalized, stride, offset) { const pointer = this._currentBufferPointers[indx]; if (!pointer) { return; } let 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); if (type === this._gl.UNSIGNED_INT || type === this._gl.INT) { this._gl.vertexAttribIPointer(indx, size, type, stride, offset); } else { this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset); } } } /** * @internal */ _bindIndexBufferWithCache(indexBuffer) { if (indexBuffer == null) { return; } if (this._cachedIndexBuffer !== indexBuffer) { this._cachedIndexBuffer = indexBuffer; this.bindIndexBuffer(indexBuffer); this._uintIndicesCurrentlySet = indexBuffer.is32Bits; } } _bindVertexBuffersAttributes(vertexBuffers, effect, overrideVertexBuffers) { const attributes = effect.getAttributesNames(); if (!this._vaoRecordInProgress) { this._unbindVertexArrayObject(); } this.unbindAllAttributes(); for (let index = 0; index < attributes.length; index++) { const order = effect.getAttributeLocation(index); if (order >= 0) { const ai = attributes[index]; let vertexBuffer = null; if (overrideVertexBuffers) { vertexBuffer = overrideVertexBuffers[ai]; } if (!vertexBuffer) { vertexBuffer = vertexBuffers[ai]; } if (!vertexBuffer) { continue; } this._gl.enableVertexAttribArray(order); if (!this._vaoRecordInProgress) { this._vertexAttribArraysEnabled[order] = true; } const 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/setup/support/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 * @param overrideVertexBuffers defines optional list of avertex buffers that overrides the entries in vertexBuffers * @returns the new vertex array object */ recordVertexArrayObject(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) { const vao = this._gl.createVertexArray(); if (!vao) { throw new Error("Unable to create VAO"); } this._vaoRecordInProgress = true; this._gl.bindVertexArray(vao); this._mustWipeVertexAttributes = true; this._bindVertexBuffersAttributes(vertexBuffers, effect, overrideVertexBuffers); this.bindIndexBuffer(indexBuffer); this._vaoRecordInProgress = false; this._gl.bindVertexArray(null); return vao; } /** * Bind a specific vertex array object * @see https://doc.babylonjs.com/setup/support/webGL2#vertex-array-objects * @param vertexArrayObject defines the vertex array object to bind * @param indexBuffer defines the index buffer to bind */ bindVertexArrayObject(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 */ bindBuffersDirectly(vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) { if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) { this._cachedVertexBuffers = vertexBuffer; this._cachedEffectForVertexBuffers = effect; const attributesCount = effect.getAttributesCount(); this._unbindVertexArrayObject(); this.unbindAllAttributes(); let offset = 0; for (let index = 0; index < attributesCount; index++) { if (index < vertexDeclaration.length) { const 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); } _unbindVertexArrayObject() { 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 * @param overrideVertexBuffers defines optional list of avertex buffers that overrides the entries in vertexBuffers */ bindBuffers(vertexBuffers, indexBuffer, effect, overrideVertexBuffers) { if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) { this._cachedVertexBuffers = vertexBuffers; this._cachedEffectForVertexBuffers = effect; this._bindVertexBuffersAttributes(vertexBuffers, effect, overrideVertexBuffers); } this._bindIndexBufferWithCache(indexBuffer); } /** * Unbind all instance attributes */ unbindInstanceAttributes() { let boundBuffer; for (let i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) { const instancesBuffer = this._currentInstanceBuffers[i]; if (boundBuffer != instancesBuffer && instancesBuffer.references) { boundBuffer = instancesBuffer; this.bindArrayBuffer(instancesBuffer); } const 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 */ releaseVertexArrayObject(vao) { this._gl.deleteVertexArray(vao); } /** * @internal */ _releaseBuffer(buffer) { buffer.references--; if (buffer.references === 0) { this._deleteBuffer(buffer); return true; } return false; } _deleteBuffer(buffer) { this._gl.deleteBuffer(buffer.underlyingResource); } /** * Update the content of a webGL buffer used with instantiation 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 */ updateAndBindInstancesBuffer(instancesBuffer, data, offsetLocations) { this.bindArrayBuffer(instancesBuffer); if (data) { this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data); } if (offsetLocations[0].index !== void 0) { this.bindInstancesBuffer(instancesBuffer, offsetLocations, true); } else { for (let index = 0; index < 4; index++) { const 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 */ bindInstancesBuffer(instancesBuffer, attributesInfo, computeStride = true) { this.bindArrayBuffer(instancesBuffer); let stride = 0; if (computeStride) { for (let i = 0; i < attributesInfo.length; i++) { const ai = attributesInfo[i]; stride += ai.attributeSize * 4; } } for (let i = 0; i < attributesInfo.length; i++) { const ai = attributesInfo[i]; if (ai.index === void 0) { 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 === void 0 ? 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 */ disableInstanceAttributeByName(name260) { if (!this._currentEffect) { return; } const attributeLocation = this._currentEffect.getAttributeLocationByName(name260); this.disableInstanceAttribute(attributeLocation); } /** * Disable the instance attribute corresponding to the location in parameter * @param attributeLocation defines the attribute location of the attribute to disable */ disableInstanceAttribute(attributeLocation) { let shouldClean = false; let 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 */ disableAttributeByIndex(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 instantiation is enabled) */ draw(useTriangles, indexStart, indexCount, instancesCount) { this.drawElementsType(useTriangles ? 0 : 1, 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 instantiation is enabled) */ drawPointClouds(verticesStart, verticesCount, instancesCount) { this.drawArraysType(2, 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 instantiation is enabled) */ drawUnIndexed(useTriangles, verticesStart, verticesCount, instancesCount) { this.drawArraysType(useTriangles ? 0 : 1, 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 instantiation is enabled) */ drawElementsType(fillMode, indexStart, indexCount, instancesCount) { this.applyStates(); this._reportDrawCall(); const drawMode = this._drawMode(fillMode); const indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT; const 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 instantiation is enabled) */ drawArraysType(fillMode, verticesStart, verticesCount, instancesCount) { this.applyStates(); this._reportDrawCall(); const drawMode = this._drawMode(fillMode); if (instancesCount) { this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount); } else { this._gl.drawArrays(drawMode, verticesStart, verticesCount); } } _drawMode(fillMode) { switch (fillMode) { // Triangle views case 0: return this._gl.TRIANGLES; case 2: return this._gl.POINTS; case 1: return this._gl.LINES; // Draw modes case 3: return this._gl.POINTS; case 4: return this._gl.LINES; case 5: return this._gl.LINE_LOOP; case 6: return this._gl.LINE_STRIP; case 7: return this._gl.TRIANGLE_STRIP; case 8: return this._gl.TRIANGLE_FAN; default: return this._gl.TRIANGLES; } } // Shaders /** * @internal */ _releaseEffect(effect) { if (this._compiledEffects[effect._key]) { delete this._compiledEffects[effect._key]; } const pipelineContext = effect.getPipelineContext(); if (pipelineContext) { this._deletePipelineContext(pipelineContext); } } /** * @internal */ _deletePipelineContext(pipelineContext) { const webGLPipelineContext = pipelineContext; if (webGLPipelineContext && webGLPipelineContext.program) { webGLPipelineContext.program.__SPECTOR_rebuildProgram = null; resetCachedPipeline(webGLPipelineContext); if (this._gl) { if (this._currentProgram === webGLPipelineContext.program) { this._setProgram(null); } this._gl.deleteProgram(webGLPipelineContext.program); } } } /** * @internal */ _getGlobalDefines(defines) { return _GetGlobalDefines(defines, this.isNDCHalfZRange, this.useReverseDepthBuffer, this.useExactSrgbConversions); } /** * 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 compilation 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) * @param shaderLanguage the language the shader is written in (default: GLSL) * @param extraInitializationsAsync additional async code to run before preparing the effect * @returns the new Effect */ createEffect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters, shaderLanguage = 0, extraInitializationsAsync) { const vertex = typeof baseName === "string" ? baseName : baseName.vertexToken || baseName.vertexSource || baseName.vertexElement || baseName.vertex; const fragment = typeof baseName === "string" ? baseName : baseName.fragmentToken || baseName.fragmentSource || baseName.fragmentElement || baseName.fragment; const globalDefines = this._getGlobalDefines(); const isOptions = attributesNamesOrOptions.attributes !== void 0; let fullDefines = defines ?? attributesNamesOrOptions.defines ?? ""; if (globalDefines) { fullDefines += globalDefines; } const name260 = vertex + "+" + fragment + "@" + fullDefines; if (this._compiledEffects[name260]) { const compiledEffect = this._compiledEffects[name260]; if (onCompiled && compiledEffect.isReady()) { onCompiled(compiledEffect); } compiledEffect._refCount++; return compiledEffect; } if (this._gl) { getStateObject(this._gl); } const effect = new Effect(baseName, attributesNamesOrOptions, isOptions ? this : uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters, name260, attributesNamesOrOptions.shaderLanguage ?? shaderLanguage, attributesNamesOrOptions.extraInitializationsAsync ?? extraInitializationsAsync); this._compiledEffects[name260] = effect; return effect; } /** * @internal */ _getShaderSource(shader260) { return this._gl.getShaderSource(shader260); } /** * 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 */ createRawShaderProgram(pipelineContext, vertexCode, fragmentCode, context, transformFeedbackVaryings = null) { const stateObject = getStateObject(this._gl); stateObject._contextWasLost = this._contextWasLost; stateObject.validateShaderPrograms = this.validateShaderPrograms; return createRawShaderProgram(pipelineContext, vertexCode, fragmentCode, context || this._gl, 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 */ createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings = null) { const stateObject = getStateObject(this._gl); stateObject._contextWasLost = this._contextWasLost; stateObject.validateShaderPrograms = this.validateShaderPrograms; return createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context || this._gl, transformFeedbackVaryings); } /** * Inline functions in shader code that are marked to be inlined * @param code code to inline * @returns inlined code */ inlineShaderCode(code) { return code; } /** * Creates a new pipeline context * @param shaderProcessingContext defines the shader processing context used during the processing if available * @returns the new pipeline */ createPipelineContext(shaderProcessingContext) { if (this._gl) { const stateObject = getStateObject(this._gl); stateObject.parallelShaderCompile = this._caps.parallelShaderCompile; } const context = createPipelineContext(this._gl, shaderProcessingContext); context.engine = this; return context; } /** * Creates a new material context * @returns the new context */ createMaterialContext() { return void 0; } /** * Creates a new draw context * @returns the new context */ createDrawContext() { return void 0; } _finalizePipelineContext(pipelineContext) { return _finalizePipelineContext(pipelineContext, this._gl, this.validateShaderPrograms); } /** * @internal */ // named async but not actually an async function // eslint-disable-next-line no-restricted-syntax _preparePipelineContextAsync(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rawVertexSourceCode, rawFragmentSourceCode, rebuildRebind, defines, transformFeedbackVaryings, key, onReady) { const stateObject = getStateObject(this._gl); stateObject._contextWasLost = this._contextWasLost; stateObject.validateShaderPrograms = this.validateShaderPrograms; stateObject._createShaderProgramInjection = this._createShaderProgram.bind(this); stateObject.createRawShaderProgramInjection = this.createRawShaderProgram.bind(this); stateObject.createShaderProgramInjection = this.createShaderProgram.bind(this); stateObject.loadFileInjection = this._loadFile.bind(this); return _preparePipelineContext(pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rawVertexSourceCode, rawFragmentSourceCode, rebuildRebind, defines, transformFeedbackVaryings, key, onReady); } _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings = null) { return _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings); } /** * @internal */ _isRenderingStateCompiled(pipelineContext) { if (this._isDisposed) { return false; } return _isRenderingStateCompiled(pipelineContext, this._gl, this.validateShaderPrograms); } /** * @internal */ _executeWhenRenderingStateIsCompiled(pipelineContext, action) { _executeWhenRenderingStateIsCompiled(pipelineContext, 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 */ getUniforms(pipelineContext, uniformsNames) { const results = new Array(); const webGLPipelineContext = pipelineContext; for (let index = 0; index < uniformsNames.length; index++) { results.push(this._gl.getUniformLocation(webGLPipelineContext.program, uniformsNames[index])); } return results; } /** * Gets the list 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 */ getAttributes(pipelineContext, attributesNames) { const results = []; const webGLPipelineContext = pipelineContext; for (let 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, making it the current one (ie. the one used for rendering) * @param effect defines the effect to activate */ enableEffect(effect) { effect = effect !== null && IsWrapper(effect) ? effect.effect : effect; if (!effect || effect === this._currentEffect) { return; } this._stencilStateComposer.stencilMaterial = void 0; 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 * @returns true if the value was set */ setInt(uniform, value) { if (!uniform) { return false; } this._gl.uniform1i(uniform, value); return true; } /** * Set the value of an uniform to a int2 * @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 * @returns true if the value was set */ setInt2(uniform, x, y) { if (!uniform) { return false; } this._gl.uniform2i(uniform, x, y); return true; } /** * Set the value of an uniform to a int3 * @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 * @returns true if the value was set */ setInt3(uniform, x, y, z) { if (!uniform) { return false; } this._gl.uniform3i(uniform, x, y, z); return true; } /** * Set the value of an uniform to a int4 * @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 * @returns true if the value was set */ setInt4(uniform, x, y, z, w) { if (!uniform) { return false; } this._gl.uniform4i(uniform, x, y, z, w); return true; } /** * 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 * @returns true if the value was set */ setIntArray(uniform, array) { if (!uniform) { return false; } this._gl.uniform1iv(uniform, array); return true; } /** * 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 * @returns true if the value was set */ setIntArray2(uniform, array) { if (!uniform || array.length % 2 !== 0) { return false; } this._gl.uniform2iv(uniform, array); return true; } /** * 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 * @returns true if the value was set */ setIntArray3(uniform, array) { if (!uniform || array.length % 3 !== 0) { return false; } this._gl.uniform3iv(uniform, array); return true; } /** * 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 * @returns true if the value was set */ setIntArray4(uniform, array) { if (!uniform || array.length % 4 !== 0) { return false; } this._gl.uniform4iv(uniform, array); return true; } /** * Set the value of an uniform to a number (unsigned int) * @param uniform defines the webGL uniform location where to store the value * @param value defines the unsigned int number to store * @returns true if the value was set */ setUInt(uniform, value) { if (!uniform) { return false; } this._gl.uniform1ui(uniform, value); return true; } /** * Set the value of an uniform to a unsigned int2 * @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 * @returns true if the value was set */ setUInt2(uniform, x, y) { if (!uniform) { return false; } this._gl.uniform2ui(uniform, x, y); return true; } /** * Set the value of an uniform to a unsigned int3 * @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 * @returns true if the value was set */ setUInt3(uniform, x, y, z) { if (!uniform) { return false; } this._gl.uniform3ui(uniform, x, y, z); return true; } /** * Set the value of an uniform to a unsigned int4 * @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 * @returns true if the value was set */ setUInt4(uniform, x, y, z, w) { if (!uniform) { return false; } this._gl.uniform4ui(uniform, x, y, z, w); return true; } /** * Set the value of an uniform to an array of unsigned int32 * @param uniform defines the webGL uniform location where to store the value * @param array defines the array of unsigned int32 to store * @returns true if the value was set */ setUIntArray(uniform, array) { if (!uniform) { return false; } this._gl.uniform1uiv(uniform, array); return true; } /** * Set the value of an uniform to an array of unsigned int32 (stored as vec2) * @param uniform defines the webGL uniform location where to store the value * @param array defines the array of unsigned int32 to store * @returns true if the value was set */ setUIntArray2(uniform, array) { if (!uniform || array.length % 2 !== 0) { return false; } this._gl.uniform2uiv(uniform, array); return true; } /** * Set the value of an uniform to an array of unsigned int32 (stored as vec3) * @param uniform defines the webGL uniform location where to store the value * @param array defines the array of unsigned int32 to store * @returns true if the value was set */ setUIntArray3(uniform, array) { if (!uniform || array.length % 3 !== 0) { return false; } this._gl.uniform3uiv(uniform, array); return true; } /** * Set the value of an uniform to an array of unsigned int32 (stored as vec4) * @param uniform defines the webGL uniform location where to store the value * @param array defines the array of unsigned int32 to store * @returns true if the value was set */ setUIntArray4(uniform, array) { if (!uniform || array.length % 4 !== 0) { return false; } this._gl.uniform4uiv(uniform, array); return true; } /** * 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 * @returns true if the value was set */ setArray(uniform, array) { if (!uniform) { return false; } if (array.length < 1) { return false; } this._gl.uniform1fv(uniform, array); return true; } /** * 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 * @returns true if the value was set */ setArray2(uniform, array) { if (!uniform || array.length % 2 !== 0) { return false; } this._gl.uniform2fv(uniform, array); return true; } /** * 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 * @returns true if the value was set */ setArray3(uniform, array) { if (!uniform || array.length % 3 !== 0) { return false; } this._gl.uniform3fv(uniform, array); return true; } /** * 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 * @returns true if the value was set */ setArray4(uniform, array) { if (!uniform || array.length % 4 !== 0) { return false; } this._gl.uniform4fv(uniform, array); return true; } /** * 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 * @returns true if the value was set */ setMatrices(uniform, matrices) { if (!uniform) { return false; } this._gl.uniformMatrix4fv(uniform, false, matrices); return true; } /** * 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 * @returns true if the value was set */ setMatrix3x3(uniform, matrix) { if (!uniform) { return false; } this._gl.uniformMatrix3fv(uniform, false, matrix); return true; } /** * 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 * @returns true if the value was set */ setMatrix2x2(uniform, matrix) { if (!uniform) { return false; } this._gl.uniformMatrix2fv(uniform, false, matrix); return true; } /** * 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 * @returns true if the value was transferred */ setFloat(uniform, value) { if (!uniform) { return false; } this._gl.uniform1f(uniform, value); return true; } /** * 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 * @returns true if the value was set */ setFloat2(uniform, x, y) { if (!uniform) { return false; } this._gl.uniform2f(uniform, x, y); return true; } /** * 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 * @returns true if the value was set */ setFloat3(uniform, x, y, z) { if (!uniform) { return false; } this._gl.uniform3f(uniform, x, y, z); return true; } /** * 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 * @returns true if the value was set */ setFloat4(uniform, x, y, z, w) { if (!uniform) { return false; } this._gl.uniform4f(uniform, x, y, z, w); return true; } // States /** * Apply all cached states (depth, culling, stencil and alpha) */ applyStates() { this._depthCullingState.apply(this._gl); this._stencilStateComposer.apply(this._gl); this._alphaState.apply(this._gl, this._currentRenderTarget && this._currentRenderTarget.textures ? this._currentRenderTarget.textures.length : 1); if (this._colorWriteChanged) { this._colorWriteChanged = false; const enable = this._colorWrite; this._gl.colorMask(enable, enable, enable, enable); } } // Textures /** * 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) */ wipeCaches(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; this._unbindVertexArrayObject(); if (bruteForce) { this._currentProgram = null; this.resetTextureCache(); this._stencilStateComposer.reset(); this._depthCullingState.reset(); this._depthCullingState.depthFunc = this._gl.LEQUAL; this._alphaState.reset(); this._resetAlphaMode(); 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); } /** * @internal */ _getSamplingParameters(samplingMode, generateMipMaps) { const gl = this._gl; let magFilter = gl.NEAREST; let minFilter = gl.NEAREST; let hasMipMaps = false; switch (samplingMode) { case 11: magFilter = gl.LINEAR; if (generateMipMaps) { minFilter = gl.LINEAR_MIPMAP_NEAREST; } else { minFilter = gl.LINEAR; } break; case 3: magFilter = gl.LINEAR; hasMipMaps = true; if (generateMipMaps) { minFilter = gl.LINEAR_MIPMAP_LINEAR; } else { minFilter = gl.LINEAR; } break; case 8: hasMipMaps = true; magFilter = gl.NEAREST; if (generateMipMaps) { minFilter = gl.NEAREST_MIPMAP_LINEAR; } else { minFilter = gl.NEAREST; } break; case 4: magFilter = gl.NEAREST; if (generateMipMaps) { minFilter = gl.NEAREST_MIPMAP_NEAREST; } else { minFilter = gl.NEAREST; } break; case 5: magFilter = gl.NEAREST; if (generateMipMaps) { minFilter = gl.LINEAR_MIPMAP_NEAREST; } else { minFilter = gl.LINEAR; } break; case 6: hasMipMaps = true; magFilter = gl.NEAREST; if (generateMipMaps) { minFilter = gl.LINEAR_MIPMAP_LINEAR; } else { minFilter = gl.LINEAR; } break; case 7: magFilter = gl.NEAREST; minFilter = gl.LINEAR; break; case 1: magFilter = gl.NEAREST; minFilter = gl.NEAREST; break; case 9: magFilter = gl.LINEAR; if (generateMipMaps) { minFilter = gl.NEAREST_MIPMAP_NEAREST; } else { minFilter = gl.NEAREST; } break; case 10: hasMipMaps = true; magFilter = gl.LINEAR; if (generateMipMaps) { minFilter = gl.NEAREST_MIPMAP_LINEAR; } else { minFilter = gl.NEAREST; } break; case 2: magFilter = gl.LINEAR; minFilter = gl.LINEAR; break; case 12: magFilter = gl.LINEAR; minFilter = gl.NEAREST; break; } return { min: minFilter, mag: magFilter, hasMipMaps }; } /** @internal */ _createTexture() { const texture = this._gl.createTexture(); if (!texture) { throw new Error("Unable to create texture"); } return texture; } /** @internal */ _createHardwareTexture() { return new WebGLHardwareTexture(this._createTexture(), this._gl); } /** * Creates an internal texture without binding it to a framebuffer * @internal * @param size defines the size of the texture * @param options defines the options used to create the texture * @param delayGPUTextureCreation true to delay the texture creation the first time it is really needed. false to create it right away * @param source source type of the texture * @returns a new internal texture */ _createInternalTexture(size, options, delayGPUTextureCreation = true, source = 0) { let generateMipMaps = false; let createMipMaps = false; let type = 0; let samplingMode = 3; let format = 5; let useSRGBBuffer = false; let samples = 1; let label; let createMSAATexture = false; let comparisonFunction = 0; if (options !== void 0 && typeof options === "object") { generateMipMaps = !!options.generateMipMaps; createMipMaps = !!options.createMipMaps; type = options.type === void 0 ? 0 : options.type; samplingMode = options.samplingMode === void 0 ? 3 : options.samplingMode; format = options.format === void 0 ? 5 : options.format; useSRGBBuffer = options.useSRGBBuffer === void 0 ? false : options.useSRGBBuffer; samples = options.samples ?? 1; label = options.label; createMSAATexture = !!options.createMSAATexture; comparisonFunction = options.comparisonFunction || 0; } else { generateMipMaps = !!options; } useSRGBBuffer && (useSRGBBuffer = this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU)); if (type === 1 && !this._caps.textureFloatLinearFiltering) { samplingMode = 1; } else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) { samplingMode = 1; } if (type === 1 && !this._caps.textureFloat) { type = 0; Logger.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"); } const isDepthTexture = IsDepthTexture(format); const hasStencil = HasStencilAspect(format); const gl = this._gl; const texture = new InternalTexture(this, source); const width = size.width || size; const height = size.height || size; const depth = size.depth || 0; const layers = size.layers || 0; const filters = this._getSamplingParameters(samplingMode, (generateMipMaps || createMipMaps) && !isDepthTexture); const target = layers !== 0 ? gl.TEXTURE_2D_ARRAY : depth !== 0 ? gl.TEXTURE_3D : gl.TEXTURE_2D; const sizedFormat = isDepthTexture ? this._getInternalFormatFromDepthTextureFormat(format, true, hasStencil) : this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer); const internalFormat = isDepthTexture ? hasStencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT : this._getInternalFormat(format); const textureType = isDepthTexture ? this._getWebGLTextureTypeFromDepthTextureFormat(format) : this._getWebGLTextureType(type); this._bindTextureDirectly(target, texture); if (layers !== 0) { texture.is2DArray = true; gl.texImage3D(target, 0, sizedFormat, width, height, layers, 0, internalFormat, textureType, null); } else if (depth !== 0) { texture.is3D = true; gl.texImage3D(target, 0, sizedFormat, width, height, depth, 0, internalFormat, textureType, null); } else { gl.texImage2D(target, 0, sizedFormat, width, height, 0, internalFormat, textureType, 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); if (isDepthTexture && this.webGLVersion > 1) { if (comparisonFunction === 0) { gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, 515); 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); } } if (generateMipMaps || createMipMaps) { this._gl.generateMipmap(target); } this._bindTextureDirectly(target, null); texture._useSRGBBuffer = useSRGBBuffer; texture.baseWidth = width; texture.baseHeight = height; texture.width = width; texture.height = height; texture.depth = layers || depth; texture.isReady = true; texture.samples = samples; texture.generateMipMaps = generateMipMaps; texture.samplingMode = samplingMode; texture.type = type; texture.format = format; texture.label = label; texture.comparisonFunction = comparisonFunction; this._internalTexturesCache.push(texture); if (createMSAATexture) { let renderBuffer = null; if (IsDepthTexture(texture.format)) { renderBuffer = this._setupFramebufferDepthAttachments(HasStencilAspect(texture.format), texture.format !== 19, texture.width, texture.height, samples, texture.format, true); } else { renderBuffer = this._createRenderBuffer( texture.width, texture.height, samples, -1, this._getRGBABufferInternalSizedFormat(texture.type, texture.format, texture._useSRGBBuffer), -1 /* attachment */ ); } if (!renderBuffer) { throw new Error("Unable to create render buffer"); } texture._autoMSAAManagement = true; let hardwareTexture = texture._hardwareTexture; if (!hardwareTexture) { hardwareTexture = texture._hardwareTexture = this._createHardwareTexture(); } hardwareTexture.addMSAARenderBuffer(renderBuffer); } return texture; } /** * @internal */ _getUseSRGBBuffer(useSRGBBuffer, noMipmap) { return useSRGBBuffer && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || noMipmap); } /** * 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 * @param loaderOptions options to be passed to the loader * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). * @returns a InternalTexture for assignment back into BABYLON.Texture */ createTexture(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, creationFlags, useSRGBBuffer) { return this._createTextureBase(url, noMipmap, invertY, scene, samplingMode, onLoad, onError, (...args) => this._prepareWebGLTexture(...args, format), (potWidth, potHeight, img, extension, texture, continuationCallback) => { const gl = this._gl; const isPot = img.width === potWidth && img.height === potHeight; texture._creationFlags = creationFlags ?? 0; const tip = this._getTexImageParametersForCreateTexture(texture.format, texture._useSRGBBuffer); if (isPot) { gl.texImage2D(gl.TEXTURE_2D, 0, tip.internalFormat, tip.format, tip.type, img); return false; } const 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, tip.internalFormat, tip.format, tip.type, this._workingCanvas); texture.width = potWidth; texture.height = potHeight; return false; } else { const source = new InternalTexture( this, 2 /* InternalTextureSource.Temp */ ); this._bindTextureDirectly(gl.TEXTURE_2D, source, true); gl.texImage2D(gl.TEXTURE_2D, 0, tip.internalFormat, tip.format, tip.type, img); this._rescaleTexture(source, texture, scene, tip.format, () => { this._releaseTexture(source); this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); continuationCallback(); }); } return true; }, buffer, fallback, format, forcedExtension, mimeType, loaderOptions, useSRGBBuffer); } /** * Calls to the GL texImage2D and texImage3D functions require three arguments describing the pixel format of the texture. * createTexture derives these from the babylonFormat and useSRGBBuffer arguments and also the file extension of the URL it's working with. * This function encapsulates that derivation for easy unit testing. * @param babylonFormat Babylon's format enum, as specified in ITextureCreationOptions. * @param fileExtension The file extension including the dot, e.g. .jpg. * @param useSRGBBuffer Use SRGB not linear. * @returns The options to pass to texImage2D or texImage3D calls. * @internal */ _getTexImageParametersForCreateTexture(babylonFormat, useSRGBBuffer) { let format, internalFormat; if (this.webGLVersion === 1) { format = this._getInternalFormat(babylonFormat, useSRGBBuffer); internalFormat = format; } else { format = this._getInternalFormat(babylonFormat, false); internalFormat = this._getRGBABufferInternalSizedFormat(0, babylonFormat, useSRGBBuffer); } return { internalFormat, format, type: this._gl.UNSIGNED_BYTE }; } /** * @internal */ _rescaleTexture(source, destination, scene, internalFormat, onComplete) { } /** * @internal */ _unpackFlipY(value) { if (this._unpackFlipYCached !== value) { this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0); if (this.enableUnpackFlipYCached) { this._unpackFlipYCached = value; } } } /** @internal */ _getUnpackAlignement() { return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT); } /** @internal */ _getTextureTarget(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 */ updateTextureSamplingMode(samplingMode, texture, generateMipMaps = false) { const target = this._getTextureTarget(texture); const filters = this._getSamplingParameters(samplingMode, texture.useMipMaps || generateMipMaps); this._setTextureParameterInteger(target, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture); this._setTextureParameterInteger(target, this._gl.TEXTURE_MIN_FILTER, filters.min); if (generateMipMaps && filters.hasMipMaps) { texture.generateMipMaps = true; this._gl.generateMipmap(target); } this._bindTextureDirectly(target, null); texture.samplingMode = samplingMode; } /** * Update the dimensions of a texture * @param texture texture to update * @param width new width of the texture * @param height new height of the texture * @param depth new depth of the texture */ updateTextureDimensions(texture, width, height, depth = 1) { } /** * 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 */ updateTextureWrappingMode(texture, wrapU, wrapV = null, wrapR = null) { const 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); } /** * @internal */ _uploadCompressedDataToTextureDirectly(texture, internalFormat, width, height, data, faceIndex = 0, lod = 0) { const gl = this._gl; let target = gl.TEXTURE_2D; if (texture.isCube) { target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; } if (texture._useSRGBBuffer) { switch (internalFormat) { case 37492: case 36196: if (this._caps.etc2) { internalFormat = gl.COMPRESSED_SRGB8_ETC2; } else { texture._useSRGBBuffer = false; } break; case 37496: if (this._caps.etc2) { internalFormat = gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; } else { texture._useSRGBBuffer = false; } break; case 36492: internalFormat = gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT; break; case 37808: internalFormat = gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR; break; case 33776: if (this._caps.s3tc_srgb) { internalFormat = gl.COMPRESSED_SRGB_S3TC_DXT1_EXT; } else { texture._useSRGBBuffer = false; } break; case 33777: if (this._caps.s3tc_srgb) { internalFormat = gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; } else { texture._useSRGBBuffer = false; } break; case 33779: if (this._caps.s3tc_srgb) { internalFormat = gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; } else { texture._useSRGBBuffer = false; } break; default: texture._useSRGBBuffer = false; break; } } if (texture.generateMipMaps) { const webGLHardwareTexture = texture._hardwareTexture; if (!webGLHardwareTexture.memoryAllocated) { gl.texStorage2D(gl.TEXTURE_2D, Math.floor(Math.log2(Math.max(width, height))) + 1, internalFormat, texture.width, texture.height); webGLHardwareTexture.memoryAllocated = true; } this._gl.compressedTexSubImage2D(target, lod, 0, 0, width, height, internalFormat, data); } else { this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data); } } /** * @internal */ _uploadDataToTextureDirectly(texture, imageData, faceIndex = 0, lod = 0, babylonInternalFormat, useTextureWidthAndHeight = false) { const gl = this._gl; const textureType = this._getWebGLTextureType(texture.type); const format = this._getInternalFormat(texture.format); const internalFormat = babylonInternalFormat === void 0 ? this._getRGBABufferInternalSizedFormat(texture.type, texture.format, texture._useSRGBBuffer) : this._getInternalFormat(babylonInternalFormat, texture._useSRGBBuffer); this._unpackFlipY(texture.invertY); let target = gl.TEXTURE_2D; if (texture.isCube) { target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; } const lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E); const lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E); const width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0)); const 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) * @param generateMipMaps defines whether to generate mipmaps or not */ updateTextureData(texture, imageData, xOffset, yOffset, width, height, faceIndex = 0, lod = 0, generateMipMaps = false) { const gl = this._gl; const textureType = this._getWebGLTextureType(texture.type); const format = this._getInternalFormat(texture.format); this._unpackFlipY(texture.invertY); let targetForBinding = gl.TEXTURE_2D; let target = gl.TEXTURE_2D; if (texture.isCube) { target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex; targetForBinding = gl.TEXTURE_CUBE_MAP; } this._bindTextureDirectly(targetForBinding, texture, true); gl.texSubImage2D(target, lod, xOffset, yOffset, width, height, format, textureType, imageData); if (generateMipMaps) { this._gl.generateMipmap(target); } this._bindTextureDirectly(targetForBinding, null); } /** * @internal */ _uploadArrayBufferViewToTexture(texture, imageData, faceIndex = 0, lod = 0) { const gl = this._gl; const 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); } _prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode) { const gl = this._gl; if (!gl) { return; } const 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); if (scene) { scene.removePendingData(texture); } texture.onLoadedObservable.notifyObservers(texture); texture.onLoadedObservable.clear(); } _prepareWebGLTexture(texture, extension, scene, img, invertY, noMipmap, isCompressed, processFunction, samplingMode, format) { const maxTextureSize = this.getCaps().maxTextureSize; const potWidth = Math.min(maxTextureSize, this.needPOTTextures ? GetExponentOfTwo(img.width, maxTextureSize) : img.width); const potHeight = Math.min(maxTextureSize, this.needPOTTextures ? GetExponentOfTwo(img.height, maxTextureSize) : img.height); const gl = this._gl; if (!gl) { return; } if (!texture._hardwareTexture) { if (scene) { scene.removePendingData(texture); } return; } this._bindTextureDirectly(gl.TEXTURE_2D, texture, true); this._unpackFlipY(invertY === void 0 ? true : invertY ? true : false); texture.baseWidth = img.width; texture.baseHeight = img.height; texture.width = potWidth; texture.height = potHeight; texture.isReady = true; texture.type = texture.type !== -1 ? texture.type : 0; texture.format = texture.format !== -1 ? texture.format : format ?? (extension === ".jpg" && !texture._useSRGBBuffer ? 4 : 5); if (processFunction(potWidth, potHeight, img, extension, texture, () => { this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode); })) { return; } this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode); } _getInternalFormatFromDepthTextureFormat(textureFormat, hasDepth, hasStencil) { const gl = this._gl; if (!hasDepth) { return gl.STENCIL_INDEX8; } const format = hasStencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT; let internalFormat = format; if (this.webGLVersion > 1) { if (textureFormat === 15) { internalFormat = gl.DEPTH_COMPONENT16; } else if (textureFormat === 16) { internalFormat = gl.DEPTH_COMPONENT24; } else if (textureFormat === 17 || textureFormat === 13) { internalFormat = hasStencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24; } else if (textureFormat === 14) { internalFormat = gl.DEPTH_COMPONENT32F; } else if (textureFormat === 18) { internalFormat = hasStencil ? gl.DEPTH32F_STENCIL8 : gl.DEPTH_COMPONENT32F; } } else { internalFormat = gl.DEPTH_COMPONENT16; } return internalFormat; } _getWebGLTextureTypeFromDepthTextureFormat(textureFormat) { const gl = this._gl; let type = gl.UNSIGNED_INT; if (textureFormat === 15) { type = gl.UNSIGNED_SHORT; } else if (textureFormat === 17 || textureFormat === 13) { type = gl.UNSIGNED_INT_24_8; } else if (textureFormat === 14) { type = gl.FLOAT; } else if (textureFormat === 18) { type = gl.FLOAT_32_UNSIGNED_INT_24_8_REV; } else if (textureFormat === 19) { type = gl.UNSIGNED_BYTE; } return type; } /** * @internal */ _setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height, samples = 1, depthTextureFormat, dontBindRenderBufferToFrameBuffer = false) { const gl = this._gl; depthTextureFormat = depthTextureFormat ?? (generateStencilBuffer ? 13 : 14); const internalFormat = this._getInternalFormatFromDepthTextureFormat(depthTextureFormat, generateDepthBuffer, generateStencilBuffer); if (generateStencilBuffer && generateDepthBuffer) { return this._createRenderBuffer(width, height, samples, gl.DEPTH_STENCIL, internalFormat, dontBindRenderBufferToFrameBuffer ? -1 : gl.DEPTH_STENCIL_ATTACHMENT); } if (generateDepthBuffer) { return this._createRenderBuffer(width, height, samples, internalFormat, internalFormat, dontBindRenderBufferToFrameBuffer ? -1 : gl.DEPTH_ATTACHMENT); } if (generateStencilBuffer) { return this._createRenderBuffer(width, height, samples, internalFormat, internalFormat, dontBindRenderBufferToFrameBuffer ? -1 : gl.STENCIL_ATTACHMENT); } return null; } /** * @internal */ _createRenderBuffer(width, height, samples, internalFormat, msInternalFormat, attachment, unbindBuffer = true) { const gl = this._gl; const renderBuffer = gl.createRenderbuffer(); return this._updateRenderBuffer(renderBuffer, width, height, samples, internalFormat, msInternalFormat, attachment, unbindBuffer); } _updateRenderBuffer(renderBuffer, width, height, samples, internalFormat, msInternalFormat, attachment, unbindBuffer = true) { const gl = this._gl; gl.bindRenderbuffer(gl.RENDERBUFFER, renderBuffer); if (samples > 1 && gl.renderbufferStorageMultisample) { gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, msInternalFormat, width, height); } else { gl.renderbufferStorage(gl.RENDERBUFFER, internalFormat, width, height); } if (attachment !== -1) { gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, renderBuffer); } if (unbindBuffer) { gl.bindRenderbuffer(gl.RENDERBUFFER, null); } return renderBuffer; } /** * @internal */ _releaseTexture(texture) { this._deleteTexture(texture._hardwareTexture); this.unbindAllTextures(); const index = this._internalTexturesCache.indexOf(texture); if (index !== -1) { this._internalTexturesCache.splice(index, 1); } if (texture._lodTextureHigh) { texture._lodTextureHigh.dispose(); } if (texture._lodTextureMid) { texture._lodTextureMid.dispose(); } if (texture._lodTextureLow) { texture._lodTextureLow.dispose(); } if (texture._irradianceTexture) { texture._irradianceTexture.dispose(); } } _deleteTexture(texture) { texture?.release(); } _setProgram(program) { if (this._currentProgram !== program) { _setProgram(program, this._gl); this._currentProgram = program; } } /** * Binds an effect to the webGL context * @param effect defines the effect to bind */ bindSamplers(effect) { const webGLPipelineContext = effect.getPipelineContext(); this._setProgram(webGLPipelineContext.program); const samplers = effect.getSamplers(); for (let index = 0; index < samplers.length; index++) { const uniform = effect.getUniform(samplers[index]); if (uniform) { this._boundUniforms[index] = uniform; } } this._currentEffect = null; } _activateCurrentTexture() { if (this._currentTextureChannel !== this._activeChannel) { this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel); this._currentTextureChannel = this._activeChannel; } } /** * @internal */ _bindTextureDirectly(target, texture, forTextureDataUpdate = false, force = false) { let wasPreviouslyBound = false; const isTextureForRendering = texture && texture._associatedChannel > -1; if (forTextureDataUpdate && isTextureForRendering) { this._activeChannel = texture._associatedChannel; } const currentTextureBound = this._boundTexturesCache[this._activeChannel]; if (currentTextureBound !== texture || force) { this._activateCurrentTexture(); if (texture && texture.isMultiview) { Logger.Error(["_bindTextureDirectly called with a multiview texture!", target, texture]); throw "_bindTextureDirectly called with a multiview texture!"; } else { this._gl.bindTexture(target, texture?._hardwareTexture?.underlyingResource ?? 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; } /** * @internal */ _bindTexture(channel, texture, name260) { if (channel === void 0) { return; } if (texture) { texture._associatedChannel = channel; } this._activeChannel = channel; const target = texture ? this._getTextureTarget(texture) : this._gl.TEXTURE_2D; this._bindTextureDirectly(target, texture); } /** * Unbind all textures from the webGL context */ unbindAllTextures() { for (let 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 * @param name The name of the uniform in the effect */ setTexture(channel, uniform, texture, name260) { if (channel === void 0) { return; } if (uniform) { this._boundUniforms[channel] = uniform; } this._setTexture(channel, texture); } _bindSamplerUniformToChannel(sourceSlot, destination) { const uniform = this._boundUniforms[sourceSlot]; if (!uniform || uniform._currentState === destination) { return; } this._gl.uniform1i(uniform, destination); uniform._currentState = destination; } _getTextureWrapMode(mode) { switch (mode) { case 1: return this._gl.REPEAT; case 0: return this._gl.CLAMP_TO_EDGE; case 2: return this._gl.MIRRORED_REPEAT; } return this._gl.REPEAT; } _setTexture(channel, texture, isPartOfTextureArray = false, depthStencilTexture = false, name260 = "") { 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; } if (texture.video) { this._activeChannel = channel; const videoInternalTexture = texture.getInternalTexture(); if (videoInternalTexture) { videoInternalTexture._associatedChannel = channel; } texture.update(); } else if (texture.delayLoadState === 4) { texture.delayLoad(); return false; } let 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; } let needToBind = true; if (this._boundTexturesCache[channel] === internalTexture) { if (!isPartOfTextureArray) { this._bindSamplerUniformToChannel(internalTexture._associatedChannel, channel); } needToBind = false; } this._activeChannel = channel; const target = this._getTextureTarget(internalTexture); if (needToBind) { this._bindTextureDirectly(target, internalTexture, isPartOfTextureArray); } if (internalTexture && !internalTexture.isMultiview) { if (internalTexture.isCube && internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) { internalTexture._cachedCoordinatesMode = texture.coordinatesMode; const textureWrapMode = texture.coordinatesMode !== 3 && texture.coordinatesMode !== 5 ? 1 : 0; 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 * @param name name of the channel */ setTextureArray(channel, uniform, textures, name260) { if (channel === void 0 || !uniform) { return; } if (!this._textureUnits || this._textureUnits.length !== textures.length) { this._textureUnits = new Int32Array(textures.length); } for (let i = 0; i < textures.length; i++) { const 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 (let index = 0; index < textures.length; index++) { this._setTexture(this._textureUnits[index], textures[index], true); } } /** * @internal */ _setAnisotropicLevel(target, internalTexture, anisotropicFilteringLevel) { const anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension; if (internalTexture.samplingMode !== 11 && internalTexture.samplingMode !== 3 && internalTexture.samplingMode !== 2) { anisotropicFilteringLevel = 1; } if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== anisotropicFilteringLevel) { this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(anisotropicFilteringLevel, this._caps.maxAnisotropy), internalTexture); internalTexture._cachedAnisotropicFilteringLevel = anisotropicFilteringLevel; } } _setTextureParameterFloat(target, parameter, value, texture) { this._bindTextureDirectly(target, texture, true, true); this._gl.texParameterf(target, parameter, value); } _setTextureParameterInteger(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 */ unbindAllAttributes() { if (this._mustWipeVertexAttributes) { this._mustWipeVertexAttributes = false; for (let i = 0; i < this._caps.maxVertexAttribs; i++) { this.disableAttributeByIndex(i); } return; } for (let 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 */ releaseEffects() { this._compiledEffects = {}; this.onReleaseEffectsObservable.notifyObservers(this); } /** * Dispose and release all associated resources */ dispose() { if (IsWindowObjectExist()) { if (this._renderingCanvas) { this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost); if (this._onContextRestored) { this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored); } } } super.dispose(); if (this._dummyFramebuffer) { this._gl.deleteFramebuffer(this._dummyFramebuffer); } this.unbindAllAttributes(); this._boundUniforms = {}; this._workingCanvas = null; this._workingContext = null; this._currentBufferPointers.length = 0; this._currentProgram = null; if (this._creationOptions.loseContextOnDispose) { this._gl.getExtension("WEBGL_lose_context")?.loseContext(); } deleteStateObject(this._gl); } /** * Attach a new callback raised when context lost event is fired * @param callback defines the callback to call */ attachContextLostEvent(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 */ attachContextRestoredEvent(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 */ getError() { return this._gl.getError(); } _canRenderToFloatFramebuffer() { if (this._webGLVersion > 1) { return this._caps.colorBufferFloat; } return this._canRenderToFramebuffer(1); } _canRenderToHalfFloatFramebuffer() { if (this._webGLVersion > 1) { return this._caps.colorBufferFloat; } return this._canRenderToFramebuffer(2); } // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture _canRenderToFramebuffer(type) { const gl = this._gl; while (gl.getError() !== gl.NO_ERROR) { } let successful = true; const 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); const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0); const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); successful = successful && status === gl.FRAMEBUFFER_COMPLETE; successful = successful && gl.getError() === gl.NO_ERROR; if (successful) { gl.clear(gl.COLOR_BUFFER_BIT); successful = successful && gl.getError() === gl.NO_ERROR; } if (successful) { gl.bindFramebuffer(gl.FRAMEBUFFER, null); const readFormat = gl.RGBA; const readType = gl.UNSIGNED_BYTE; const buffer = new Uint8Array(4); gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer); successful = successful && gl.getError() === gl.NO_ERROR; } gl.deleteTexture(texture); gl.deleteFramebuffer(fb); gl.bindFramebuffer(gl.FRAMEBUFFER, null); while (!successful && gl.getError() !== gl.NO_ERROR) { } return successful; } /** * @internal */ _getWebGLTextureType(type) { if (this._webGLVersion === 1) { switch (type) { case 1: return this._gl.FLOAT; case 2: return this._gl.HALF_FLOAT_OES; case 0: return this._gl.UNSIGNED_BYTE; case 8: return this._gl.UNSIGNED_SHORT_4_4_4_4; case 9: return this._gl.UNSIGNED_SHORT_5_5_5_1; case 10: return this._gl.UNSIGNED_SHORT_5_6_5; } return this._gl.UNSIGNED_BYTE; } switch (type) { case 3: return this._gl.BYTE; case 0: return this._gl.UNSIGNED_BYTE; case 4: return this._gl.SHORT; case 5: return this._gl.UNSIGNED_SHORT; case 6: return this._gl.INT; case 7: return this._gl.UNSIGNED_INT; case 1: return this._gl.FLOAT; case 2: return this._gl.HALF_FLOAT; case 8: return this._gl.UNSIGNED_SHORT_4_4_4_4; case 9: return this._gl.UNSIGNED_SHORT_5_5_5_1; case 10: return this._gl.UNSIGNED_SHORT_5_6_5; case 11: return this._gl.UNSIGNED_INT_2_10_10_10_REV; case 12: return this._gl.UNSIGNED_INT_24_8; case 13: return this._gl.UNSIGNED_INT_10F_11F_11F_REV; case 14: return this._gl.UNSIGNED_INT_5_9_9_9_REV; case 15: return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV; } return this._gl.UNSIGNED_BYTE; } /** * @internal */ _getInternalFormat(format, useSRGBBuffer = false) { let internalFormat = useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA; switch (format) { case 0: internalFormat = this._gl.ALPHA; break; case 1: internalFormat = this._gl.LUMINANCE; break; case 2: internalFormat = this._gl.LUMINANCE_ALPHA; break; case 6: case 33322: case 36760: internalFormat = this._gl.RED; break; case 7: case 33324: case 36761: internalFormat = this._gl.RG; break; case 4: case 32852: case 36762: internalFormat = useSRGBBuffer ? this._glSRGBExtensionValues.SRGB : this._gl.RGB; break; case 5: case 32859: case 36763: internalFormat = useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA; break; } if (this._webGLVersion > 1) { switch (format) { case 8: internalFormat = this._gl.RED_INTEGER; break; case 9: internalFormat = this._gl.RG_INTEGER; break; case 10: internalFormat = this._gl.RGB_INTEGER; break; case 11: internalFormat = this._gl.RGBA_INTEGER; break; } } return internalFormat; } /** * @internal */ _getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer = false) { if (this._webGLVersion === 1) { if (format !== void 0) { switch (format) { case 0: return this._gl.ALPHA; case 1: return this._gl.LUMINANCE; case 2: return this._gl.LUMINANCE_ALPHA; case 4: return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB : this._gl.RGB; } } return this._gl.RGBA; } switch (type) { case 3: switch (format) { case 6: return this._gl.R8_SNORM; case 7: return this._gl.RG8_SNORM; case 4: return this._gl.RGB8_SNORM; case 8: return this._gl.R8I; case 9: return this._gl.RG8I; case 10: return this._gl.RGB8I; case 11: return this._gl.RGBA8I; default: return this._gl.RGBA8_SNORM; } case 0: switch (format) { case 6: return this._gl.R8; case 7: return this._gl.RG8; case 4: return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8 : this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8. case 5: return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8. case 8: return this._gl.R8UI; case 9: return this._gl.RG8UI; case 10: return this._gl.RGB8UI; case 11: return this._gl.RGBA8UI; case 0: return this._gl.ALPHA; case 1: return this._gl.LUMINANCE; case 2: return this._gl.LUMINANCE_ALPHA; default: return this._gl.RGBA8; } case 4: switch (format) { case 8: return this._gl.R16I; case 36760: return this._gl.R16_SNORM_EXT; case 36761: return this._gl.RG16_SNORM_EXT; case 36762: return this._gl.RGB16_SNORM_EXT; case 36763: return this._gl.RGBA16_SNORM_EXT; case 9: return this._gl.RG16I; case 10: return this._gl.RGB16I; case 11: return this._gl.RGBA16I; default: return this._gl.RGBA16I; } case 5: switch (format) { case 8: return this._gl.R16UI; case 33322: return this._gl.R16_EXT; case 33324: return this._gl.RG16_EXT; case 32852: return this._gl.RGB16_EXT; case 32859: return this._gl.RGBA16_EXT; case 9: return this._gl.RG16UI; case 10: return this._gl.RGB16UI; case 11: return this._gl.RGBA16UI; default: return this._gl.RGBA16UI; } case 6: switch (format) { case 8: return this._gl.R32I; case 9: return this._gl.RG32I; case 10: return this._gl.RGB32I; case 11: return this._gl.RGBA32I; default: return this._gl.RGBA32I; } case 7: switch (format) { case 8: return this._gl.R32UI; case 9: return this._gl.RG32UI; case 10: return this._gl.RGB32UI; case 11: return this._gl.RGBA32UI; default: return this._gl.RGBA32UI; } case 1: switch (format) { case 6: return this._gl.R32F; // By default. Other possibility is R16F. case 7: return this._gl.RG32F; // By default. Other possibility is RG16F. case 4: return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5. case 5: return this._gl.RGBA32F; // By default. Other possibility is RGBA16F. default: return this._gl.RGBA32F; } case 2: switch (format) { case 6: return this._gl.R16F; case 7: return this._gl.RG16F; case 4: return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5. case 5: return this._gl.RGBA16F; default: return this._gl.RGBA16F; } case 10: return this._gl.RGB565; case 13: return this._gl.R11F_G11F_B10F; case 14: return this._gl.RGB9_E5; case 8: return this._gl.RGBA4; case 9: return this._gl.RGB5_A1; case 11: switch (format) { case 5: return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1. case 11: return this._gl.RGB10_A2UI; default: return this._gl.RGB10_A2; } } return useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : this._gl.RGBA8; } /** * 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) * @param flushRenderer true to flush the renderer from the pending commands before reading the pixels * @param data defines the data to fill with the read pixels (if not provided, a new one will be created) * @returns a ArrayBufferView promise (Uint8Array) containing RGBA colors */ // Async function, not named Async and not marked as async to avoid breaking changes // eslint-disable-next-line @typescript-eslint/promise-function-async readPixels(x, y, width, height, hasAlpha = true, flushRenderer = true, data = null) { const numChannels = hasAlpha ? 4 : 3; const format = hasAlpha ? this._gl.RGBA : this._gl.RGB; const dataLength = width * height * numChannels; if (!data) { data = new Uint8Array(dataLength); } else if (data.length < dataLength) { Logger.Error(`Data buffer is too small to store the read pixels (${data.length} should be more than ${dataLength})`); return Promise.resolve(data); } if (flushRenderer) { this.flushFramebuffer(); } this._gl.readPixels(x, y, width, height, format, this._gl.UNSIGNED_BYTE, data); return Promise.resolve(data); } /** * Gets a Promise indicating if the engine can be instantiated (ie. if a webGL context can be found) */ // eslint-disable-next-line no-restricted-syntax static get IsSupportedAsync() { return Promise.resolve(this.isSupported()); } /** * Gets a boolean indicating if the engine can be instantiated (ie. if a webGL context can be found) */ static get IsSupported() { return this.isSupported(); } /** * Gets a boolean indicating if the engine can be instantiated (ie. if a webGL context can be found) * @returns true if the engine can be created */ // eslint-disable-next-line @typescript-eslint/naming-convention static isSupported() { if (this._HasMajorPerformanceCaveat !== null) { return !this._HasMajorPerformanceCaveat; } if (this._IsSupported === null) { try { const tempcanvas = AbstractEngine._CreateCanvas(1, 1); const gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"); this._IsSupported = gl != null && !!window.WebGLRenderingContext; } catch (e) { this._IsSupported = false; } } return this._IsSupported; } /** * Gets a boolean indicating if the engine can be instantiated on a performant device (ie. if a webGL context can be found and it does not use a slow implementation) */ static get HasMajorPerformanceCaveat() { if (this._HasMajorPerformanceCaveat === null) { try { const tempcanvas = AbstractEngine._CreateCanvas(1, 1); const gl = tempcanvas.getContext("webgl", { failIfMajorPerformanceCaveat: true }) || tempcanvas.getContext("experimental-webgl", { failIfMajorPerformanceCaveat: true }); this._HasMajorPerformanceCaveat = !gl; } catch (e) { this._HasMajorPerformanceCaveat = false; } } return this._HasMajorPerformanceCaveat; } }; ThinEngine._TempClearColorUint32 = new Uint32Array(4); ThinEngine._TempClearColorInt32 = new Int32Array(4); 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"] }, { key: "Mac OS.+Chrome", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }, { key: "Chrome/12\\d\\..+?Mobile", capture: null, captureConstraint: null, targets: ["uniformBuffer"] }, // desktop osx safari 15.4 { key: ".*AppleWebKit.*(15.4).*Safari", capture: null, captureConstraint: null, targets: ["antialias", "maxMSAASamples"] }, // mobile browsers using safari 15.4 on ios { key: ".*(15.4).*AppleWebKit.*Safari", capture: null, captureConstraint: null, targets: ["antialias", "maxMSAASamples"] } ]; ThinEngine._ConcatenateShader = _ConcatenateShader; ThinEngine._IsSupported = null; ThinEngine._HasMajorPerformanceCaveat = null; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/pass.fragment.js var pass_fragment_exports = {}; __export(pass_fragment_exports, { passPixelShader: () => passPixelShader }); var name5, shader5, passPixelShader; var init_pass_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/pass.fragment.js"() { init_shaderStore(); name5 = "passPixelShader"; shader5 = `varying vec2 vUV;uniform sampler2D textureSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(textureSampler,vUV);}`; if (!ShaderStore.ShadersStore[name5]) { ShaderStore.ShadersStore[name5] = shader5; } passPixelShader = { name: name5, shader: shader5 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/postprocess.vertex.js var postprocess_vertex_exports = {}; __export(postprocess_vertex_exports, { postprocessVertexShaderWGSL: () => postprocessVertexShaderWGSL }); var name6, shader6, postprocessVertexShaderWGSL; var init_postprocess_vertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/postprocess.vertex.js"() { init_shaderStore(); name6 = "postprocessVertexShader"; shader6 = `attribute position: vec2;uniform scale: vec2;varying vUV: vec2;const madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN vertexOutputs.vUV=(vertexInputs.position*madd+madd)*uniforms.scale;vertexOutputs.position=vec4(vertexInputs.position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END } `; if (!ShaderStore.ShadersStoreWGSL[name6]) { ShaderStore.ShadersStoreWGSL[name6] = shader6; } postprocessVertexShaderWGSL = { name: name6, shader: shader6 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/postprocess.vertex.js var postprocess_vertex_exports2 = {}; __export(postprocess_vertex_exports2, { postprocessVertexShader: () => postprocessVertexShader }); var name7, shader7, postprocessVertexShader; var init_postprocess_vertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/postprocess.vertex.js"() { init_shaderStore(); name7 = "postprocessVertexShader"; shader7 = `attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`; if (!ShaderStore.ShadersStore[name7]) { ShaderStore.ShadersStore[name7] = shader7; } postprocessVertexShader = { name: name7, shader: shader7 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Buffers/bufferUtils.js function GetFloatValue(dataView, type, byteOffset, normalized) { switch (type) { case 5120: { let value = dataView.getInt8(byteOffset); if (normalized) { value = Math.max(value / 127, -1); } return value; } case 5121: { let value = dataView.getUint8(byteOffset); if (normalized) { value = value / 255; } return value; } case 5122: { let value = dataView.getInt16(byteOffset, true); if (normalized) { value = Math.max(value / 32767, -1); } return value; } case 5123: { let value = dataView.getUint16(byteOffset, true); if (normalized) { value = value / 65535; } return value; } case 5124: { return dataView.getInt32(byteOffset, true); } case 5125: { return dataView.getUint32(byteOffset, true); } case 5126: { return dataView.getFloat32(byteOffset, true); } default: { throw new Error(`Invalid component type ${type}`); } } } function SetFloatValue(dataView, type, byteOffset, normalized, value) { switch (type) { case 5120: { if (normalized) { value = Math.round(value * 127); } dataView.setInt8(byteOffset, value); break; } case 5121: { if (normalized) { value = Math.round(value * 255); } dataView.setUint8(byteOffset, value); break; } case 5122: { if (normalized) { value = Math.round(value * 32767); } dataView.setInt16(byteOffset, value, true); break; } case 5123: { if (normalized) { value = Math.round(value * 65535); } dataView.setUint16(byteOffset, value, true); break; } case 5124: { dataView.setInt32(byteOffset, value, true); break; } case 5125: { dataView.setUint32(byteOffset, value, true); break; } case 5126: { dataView.setFloat32(byteOffset, value, true); break; } default: { throw new Error(`Invalid component type ${type}`); } } } function GetTypeByteLength(type) { switch (type) { case 5120: case 5121: return 1; case 5122: case 5123: return 2; case 5124: case 5125: case 5126: return 4; default: throw new Error(`Invalid type '${type}'`); } } function GetTypedArrayConstructor(componentType) { switch (componentType) { case 5120: return Int8Array; case 5121: return Uint8Array; case 5122: return Int16Array; case 5123: return Uint16Array; case 5124: return Int32Array; case 5125: return Uint32Array; case 5126: return Float32Array; default: throw new Error(`Invalid component type '${componentType}'`); } } function EnumerateFloatValues(data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) { const oldValues = new Array(componentCount); const newValues = new Array(componentCount); if (data instanceof Array) { let offset = byteOffset / 4; const stride = byteStride / 4; for (let index = 0; index < count; index += componentCount) { for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) { oldValues[componentIndex] = newValues[componentIndex] = data[offset + componentIndex]; } callback(newValues, index); for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) { if (oldValues[componentIndex] !== newValues[componentIndex]) { data[offset + componentIndex] = newValues[componentIndex]; } } offset += stride; } } else { const dataView = !ArrayBuffer.isView(data) ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength); const componentByteLength = GetTypeByteLength(componentType); for (let index = 0; index < count; index += componentCount) { for (let componentIndex = 0, componentByteOffset = byteOffset; componentIndex < componentCount; componentIndex++, componentByteOffset += componentByteLength) { oldValues[componentIndex] = newValues[componentIndex] = GetFloatValue(dataView, componentType, componentByteOffset, normalized); } callback(newValues, index); for (let componentIndex = 0, componentByteOffset = byteOffset; componentIndex < componentCount; componentIndex++, componentByteOffset += componentByteLength) { if (oldValues[componentIndex] !== newValues[componentIndex]) { SetFloatValue(dataView, componentType, componentByteOffset, normalized, newValues[componentIndex]); } } byteOffset += byteStride; } } } function GetFloatData(data, size, type, byteOffset, byteStride, normalized, totalVertices, forceCopy) { const tightlyPackedByteStride = size * GetTypeByteLength(type); const count = totalVertices * size; if (type !== 5126 || byteStride !== tightlyPackedByteStride) { const copy = new Float32Array(count); EnumerateFloatValues(data, byteOffset, byteStride, size, type, count, normalized, (values, index) => { for (let i = 0; i < size; i++) { copy[index + i] = values[i]; } }); return copy; } if (!(data instanceof Array || data instanceof Float32Array) || byteOffset !== 0 || data.length !== count) { if (data instanceof Array) { const offset = byteOffset / 4; return data.slice(offset, offset + count); } else if (data instanceof ArrayBuffer) { return new Float32Array(data, byteOffset, count); } else { const offset = data.byteOffset + byteOffset; if ((offset & 3) !== 0) { Logger.Warn("Float array must be aligned to 4-bytes border"); forceCopy = true; } if (forceCopy) { return new Float32Array(data.buffer.slice(offset, offset + count * Float32Array.BYTES_PER_ELEMENT)); } else { return new Float32Array(data.buffer, offset, count); } } } if (forceCopy) { return data.slice(); } return data; } function GetTypedArrayData(data, size, type, byteOffset, byteStride, totalVertices, forceCopy) { const typeByteLength = GetTypeByteLength(type); const constructor = GetTypedArrayConstructor(type); const count = totalVertices * size; if (Array.isArray(data)) { if ((byteOffset & 3) !== 0 || (byteStride & 3) !== 0) { throw new Error("byteOffset and byteStride must be a multiple of 4 for number[] data."); } const offset = byteOffset / 4; const stride = byteStride / 4; const lastIndex = offset + (totalVertices - 1) * stride + size; if (lastIndex > data.length) { throw new Error("Last accessed index is out of bounds."); } if (stride < size) { throw new Error("Data stride cannot be smaller than the component size."); } if (stride !== size) { const copy = new constructor(count); EnumerateFloatValues(data, byteOffset, byteStride, size, type, count, false, (values, index) => { for (let i = 0; i < size; i++) { copy[index + i] = values[i]; } }); return copy; } return new constructor(data.slice(offset, offset + count)); } let buffer; let adjustedByteOffset = byteOffset; if (data instanceof ArrayBuffer) { buffer = data; } else { buffer = data.buffer; adjustedByteOffset += data.byteOffset; } const lastByteOffset = adjustedByteOffset + (totalVertices - 1) * byteStride + size * typeByteLength; if (lastByteOffset > buffer.byteLength) { throw new Error("Last accessed byte is out of bounds."); } const tightlyPackedByteStride = size * typeByteLength; if (byteStride < tightlyPackedByteStride) { throw new Error("Byte stride cannot be smaller than the component's byte size."); } if (byteStride !== tightlyPackedByteStride) { const copy = new constructor(count); EnumerateFloatValues(buffer, adjustedByteOffset, byteStride, size, type, count, false, (values, index) => { for (let i = 0; i < size; i++) { copy[index + i] = values[i]; } }); return copy; } if (typeByteLength !== 1 && (adjustedByteOffset & typeByteLength - 1) !== 0) { Logger.Warn("Array must be aligned to border of element size. Data will be copied."); forceCopy = true; } if (forceCopy) { return new constructor(buffer.slice(adjustedByteOffset, adjustedByteOffset + count * typeByteLength)); } return new constructor(buffer, adjustedByteOffset, count); } function CopyFloatData(input, size, type, byteOffset, byteStride, normalized, totalVertices, output) { const tightlyPackedByteStride = size * GetTypeByteLength(type); const count = totalVertices * size; if (output.length !== count) { throw new Error("Output length is not valid"); } if (type !== 5126 || byteStride !== tightlyPackedByteStride) { EnumerateFloatValues(input, byteOffset, byteStride, size, type, count, normalized, (values, index) => { for (let i = 0; i < size; i++) { output[index + i] = values[i]; } }); return; } if (input instanceof Array) { const offset = byteOffset / 4; output.set(input, offset); } else if (input instanceof ArrayBuffer) { const floatData = new Float32Array(input, byteOffset, count); output.set(floatData); } else { const offset = input.byteOffset + byteOffset; if ((offset & 3) !== 0) { Logger.Warn("Float array must be aligned to 4-bytes border"); output.set(new Float32Array(input.buffer.slice(offset, offset + count * Float32Array.BYTES_PER_ELEMENT))); return; } const floatData = new Float32Array(input.buffer, offset, count); output.set(floatData); } } function AreIndices32Bits(indices, count, start = 0, offset = 0) { if (Array.isArray(indices)) { for (let index = 0; index < count; index++) { if (indices[start + index] - offset > 65535) { return true; } } return false; } return indices.BYTES_PER_ELEMENT === 4; } function CreateAlignedTypedArray(type, elementCount) { let byteSize = elementCount * type.BYTES_PER_ELEMENT; if ((byteSize & 3) === 0) { return new type(elementCount); } byteSize = byteSize + 3 & ~3; const backingBuffer = new ArrayBuffer(byteSize); return new type(backingBuffer, 0, elementCount); } var init_bufferUtils = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Buffers/bufferUtils.js"() { init_logger(); __name(GetFloatValue, "GetFloatValue"); __name(SetFloatValue, "SetFloatValue"); __name(GetTypeByteLength, "GetTypeByteLength"); __name(GetTypedArrayConstructor, "GetTypedArrayConstructor"); __name(EnumerateFloatValues, "EnumerateFloatValues"); __name(GetFloatData, "GetFloatData"); __name(GetTypedArrayData, "GetTypedArrayData"); __name(CopyFloatData, "CopyFloatData"); __name(AreIndices32Bits, "AreIndices32Bits"); __name(CreateAlignedTypedArray, "CreateAlignedTypedArray"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Buffers/buffer.js var Buffer2, VertexBuffer; var init_buffer = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Buffers/buffer.js"() { init_dataBuffer(); init_logger(); init_bufferUtils(); Buffer2 = class { static { __name(this, "Buffer"); } /** * Gets a boolean indicating if the Buffer is disposed */ get isDisposed() { return this._isDisposed; } /** * Constructor * @param engine the engine * @param data the data to use for this buffer * @param updatable whether the data is updatable * @param stride the stride (optional) * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional) * @param instanced whether the buffer is instanced (optional) * @param useBytes set to true if the stride in in bytes (optional) * @param divisor sets an optional divisor for instances (1 by default) * @param label defines the label of the buffer (for debug purpose) */ constructor(engine, data, updatable, stride = 0, postponeInternalCreation = false, instanced = false, useBytes = false, divisor, label) { this._isAlreadyOwned = false; this._isDisposed = false; if (engine && engine.getScene) { this._engine = engine.getScene().getEngine(); } else { this._engine = engine; } this._updatable = updatable; this._instanced = instanced; this._divisor = divisor || 1; this._label = label; if (data instanceof DataBuffer) { this._data = null; this._buffer = data; } else { this._data = data; this._buffer = null; } this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT; if (!postponeInternalCreation) { this.create(); } } /** * Create a new VertexBuffer based on the current buffer * @param kind defines the vertex buffer kind (position, normal, etc.) * @param offset defines offset in the buffer (0 by default) * @param size defines the size in floats of attributes (position is 3 for instance) * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved) * @param instanced defines if the vertex buffer contains indexed data * @param useBytes defines if the offset and stride are in bytes * * @param divisor sets an optional divisor for instances (1 by default) * @returns the new vertex buffer */ createVertexBuffer(kind, offset, size, stride, instanced, useBytes = false, divisor) { const byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT; const byteStride = stride ? useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT : this.byteStride; return new VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === void 0 ? this._instanced : instanced, byteOffset, size, void 0, void 0, true, this._divisor || divisor); } // Properties /** * Gets a boolean indicating if the Buffer is updatable? * @returns true if the buffer is updatable */ isUpdatable() { return this._updatable; } /** * Gets current buffer's data * @returns a DataArray or null */ getData() { return this._data; } /** * Gets underlying native buffer * @returns underlying native buffer */ getBuffer() { return this._buffer; } /** * Gets the stride in float32 units (i.e. byte stride / 4). * May not be an integer if the byte stride is not divisible by 4. * @returns the stride in float32 units * @deprecated Please use byteStride instead. */ getStrideSize() { return this.byteStride / Float32Array.BYTES_PER_ELEMENT; } // Methods /** * Store data into the buffer. Creates the buffer if not used already. * If the buffer was already used, it will be updated only if it is updatable, otherwise it will do nothing. * @param data defines the data to store */ create(data = null) { if (!data && this._buffer) { return; } data = data || this._data; if (!data) { return; } if (!this._buffer) { if (this._updatable) { this._buffer = this._engine.createDynamicVertexBuffer(data, this._label); this._data = data; } else { this._buffer = this._engine.createVertexBuffer(data, void 0, this._label); } } else if (this._updatable) { this._engine.updateDynamicVertexBuffer(this._buffer, data); this._data = data; } } /** @internal */ _rebuild() { if (!this._data) { if (!this._buffer) { return; } if (this._buffer.capacity > 0) { if (this._updatable) { this._buffer = this._engine.createDynamicVertexBuffer(this._buffer.capacity, this._label); } else { this._buffer = this._engine.createVertexBuffer(this._buffer.capacity, void 0, this._label); } return; } Logger.Warn(`Missing data for buffer "${this._label}" ${this._buffer ? "(uniqueId: " + this._buffer.uniqueId + ")" : ""}. Buffer reconstruction failed.`); this._buffer = null; } else { this._buffer = null; this.create(this._data); } } /** * Update current buffer data * @param data defines the data to store */ update(data) { this.create(data); } /** * Updates the data directly. * @param data the new data * @param offset the new offset * @param vertexCount the vertex count (optional) * @param useBytes set to true if the offset is in bytes */ updateDirectly(data, offset, vertexCount, useBytes = false) { if (!this._buffer) { return; } if (this._updatable) { this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, vertexCount ? vertexCount * this.byteStride : void 0); if (offset === 0 && vertexCount === void 0) { this._data = data; } else { this._data = null; } } } /** @internal */ _increaseReferences() { if (!this._buffer) { return; } if (!this._isAlreadyOwned) { this._isAlreadyOwned = true; return; } this._buffer.references++; } /** * Release all resources */ dispose() { if (!this._buffer) { return; } if (this._engine._releaseBuffer(this._buffer)) { this._isDisposed = true; this._data = null; this._buffer = null; } } }; VertexBuffer = class _VertexBuffer { static { __name(this, "VertexBuffer"); } /** * Gets a boolean indicating if the Buffer is disposed */ get isDisposed() { return this._isDisposed; } /** * Gets or sets the instance divisor when in instanced mode */ get instanceDivisor() { return this._instanceDivisor; } set instanceDivisor(value) { const isInstanced = value != 0; this._instanceDivisor = value; if (isInstanced !== this._instanced) { this._instanced = isInstanced; this._computeHashCode(); } } /** * Gets the max possible amount of vertices stored within the current vertex buffer. * We do not have the end offset or count so this will be too big for concatenated vertex buffers. * @internal */ get _maxVerticesCount() { const data = this.getData(); if (!data) { return 0; } if (Array.isArray(data)) { return data.length / (this.byteStride / 4) - this.byteOffset / 4; } return (data.byteLength - this.byteOffset) / this.byteStride; } /** @internal */ constructor(engine, data, kind, updatableOrOptions, postponeInternalCreation, stride, instanced, offset, size, type, normalized = false, useBytes = false, divisor = 1, takeBufferOwnership = false) { this._isDisposed = false; let updatable = false; this.engine = engine; if (typeof updatableOrOptions === "object" && updatableOrOptions !== null) { updatable = updatableOrOptions.updatable ?? false; postponeInternalCreation = updatableOrOptions.postponeInternalCreation; stride = updatableOrOptions.stride; instanced = updatableOrOptions.instanced; offset = updatableOrOptions.offset; size = updatableOrOptions.size; type = updatableOrOptions.type; normalized = updatableOrOptions.normalized ?? false; useBytes = updatableOrOptions.useBytes ?? false; divisor = updatableOrOptions.divisor ?? 1; takeBufferOwnership = updatableOrOptions.takeBufferOwnership ?? false; this._label = updatableOrOptions.label; } else { updatable = !!updatableOrOptions; } if (data instanceof Buffer2) { this._buffer = data; this._ownsBuffer = takeBufferOwnership; } else { this._buffer = new Buffer2(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes, divisor, this._label); this._ownsBuffer = true; } this.uniqueId = _VertexBuffer._Counter++; this._kind = kind; if (type === void 0) { const vertexData = this.getData(); this.type = vertexData ? _VertexBuffer.GetDataType(vertexData) : _VertexBuffer.FLOAT; } else { this.type = type; } const typeByteLength = GetTypeByteLength(this.type); if (useBytes) { this._size = size || (stride ? stride / typeByteLength : _VertexBuffer.DeduceStride(kind)); this.byteStride = stride || this._buffer.byteStride || this._size * typeByteLength; this.byteOffset = offset || 0; } else { this._size = size || stride || _VertexBuffer.DeduceStride(kind); this.byteStride = stride ? stride * typeByteLength : this._buffer.byteStride || this._size * typeByteLength; this.byteOffset = (offset || 0) * typeByteLength; } this.normalized = normalized; this._instanced = instanced !== void 0 ? instanced : false; this._instanceDivisor = instanced ? divisor : 0; this._alignBuffer(); this._computeHashCode(); } _computeHashCode() { this.hashCode = (this.type - 5120 << 0) + ((this.normalized ? 1 : 0) << 3) + (this._size << 4) + ((this._instanced ? 1 : 0) << 6) + /* keep 5 bits free */ (this.byteStride << 12); } /** @internal */ _rebuild() { this._buffer?._rebuild(); } /** * Returns the kind of the VertexBuffer (string) * @returns a string */ getKind() { return this._kind; } // Properties /** * Gets a boolean indicating if the VertexBuffer is updatable? * @returns true if the buffer is updatable */ isUpdatable() { return this._buffer.isUpdatable(); } /** * Gets the raw data from the underlying buffer. * Note: The data may include more than just this vertex buffer's values. * @returns the buffer data as a DataArray, or null. */ getData() { return this._buffer.getData(); } /** * Gets this vertex buffer's data as a float array. Float data is constructed if the vertex buffer data cannot be returned directly. * @param totalVertices number of vertices in the buffer to take into account * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it * @returns a float array containing vertex data */ getFloatData(totalVertices, forceCopy) { const data = this.getData(); if (!data) { return null; } return GetFloatData(data, this._size, this.type, this.byteOffset, this.byteStride, this.normalized, totalVertices, forceCopy); } /** * Gets underlying native buffer * @returns underlying native buffer */ getBuffer() { return this._buffer.getBuffer(); } /** * Gets the Buffer instance that wraps the native GPU buffer * @returns the wrapper buffer */ getWrapperBuffer() { return this._buffer; } /** * Gets the stride in float32 units (i.e. byte stride / 4). * May not be an integer if the byte stride is not divisible by 4. * @returns the stride in float32 units * @deprecated Please use byteStride instead. */ getStrideSize() { return this.byteStride / GetTypeByteLength(this.type); } /** * Returns the offset as a multiple of the type byte length. * @returns the offset in bytes * @deprecated Please use byteOffset instead. */ getOffset() { return this.byteOffset / GetTypeByteLength(this.type); } /** * Returns the number of components or the byte size per vertex attribute * @param sizeInBytes If true, returns the size in bytes or else the size in number of components of the vertex attribute (default: false) * @returns the number of components */ getSize(sizeInBytes = false) { return sizeInBytes ? this._size * GetTypeByteLength(this.type) : this._size; } /** * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced * @returns true if this buffer is instanced */ getIsInstanced() { return this._instanced; } /** * Returns the instancing divisor, zero for non-instanced (integer). * @returns a number */ getInstanceDivisor() { return this._instanceDivisor; } // Methods /** * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property * @param data defines the data to store */ create(data) { this._buffer.create(data); this._alignBuffer(); } /** * Updates the underlying buffer according to the passed numeric array or Float32Array. * This function will create a new buffer if the current one is not updatable * @param data defines the data to store */ update(data) { this._buffer.update(data); this._alignBuffer(); } /** * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array. * Returns the directly updated WebGLBuffer. * @param data the new data * @param offset the new offset * @param useBytes set to true if the offset is in bytes */ updateDirectly(data, offset, useBytes = false) { this._buffer.updateDirectly(data, offset, void 0, useBytes); this._alignBuffer(); } /** * Disposes the VertexBuffer and the underlying WebGLBuffer. */ dispose() { if (this._ownsBuffer) { this._buffer.dispose(); } this._isDisposed = true; } /** * Enumerates each value of this vertex buffer as numbers. * @param count the number of values to enumerate * @param callback the callback function called for each value */ forEach(count, callback) { EnumerateFloatValues(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, (values, index) => { for (let i = 0; i < this._size; i++) { callback(values[i], index + i); } }); } /** @internal */ _alignBuffer() { } /** * Deduces the stride given a kind. * @param kind The kind string to deduce * @returns The deduced stride */ static DeduceStride(kind) { switch (kind) { case _VertexBuffer.UVKind: case _VertexBuffer.UV2Kind: case _VertexBuffer.UV3Kind: case _VertexBuffer.UV4Kind: case _VertexBuffer.UV5Kind: case _VertexBuffer.UV6Kind: return 2; case _VertexBuffer.NormalKind: case _VertexBuffer.PositionKind: return 3; case _VertexBuffer.ColorKind: case _VertexBuffer.ColorInstanceKind: case _VertexBuffer.MatricesIndicesKind: case _VertexBuffer.MatricesIndicesExtraKind: case _VertexBuffer.MatricesWeightsKind: case _VertexBuffer.MatricesWeightsExtraKind: case _VertexBuffer.TangentKind: return 4; default: throw new Error("Invalid kind '" + kind + "'"); } } /** * Gets the vertex buffer type of the given data array. * @param data the data array * @returns the vertex buffer type */ static GetDataType(data) { if (data instanceof Int8Array) { return _VertexBuffer.BYTE; } else if (data instanceof Uint8Array) { return _VertexBuffer.UNSIGNED_BYTE; } else if (data instanceof Int16Array) { return _VertexBuffer.SHORT; } else if (data instanceof Uint16Array) { return _VertexBuffer.UNSIGNED_SHORT; } else if (data instanceof Int32Array) { return _VertexBuffer.INT; } else if (data instanceof Uint32Array) { return _VertexBuffer.UNSIGNED_INT; } else { return _VertexBuffer.FLOAT; } } /** * Gets the byte length of the given type. * @param type the type * @returns the number of bytes * @deprecated Use `getTypeByteLength` from `bufferUtils` instead */ static GetTypeByteLength(type) { return GetTypeByteLength(type); } /** * Enumerates each value of the given parameters as numbers. * @param data the data to enumerate * @param byteOffset the byte offset of the data * @param byteStride the byte stride of the data * @param componentCount the number of components per element * @param componentType the type of the component * @param count the number of values to enumerate * @param normalized whether the data is normalized * @param callback the callback function called for each value * @deprecated Use `EnumerateFloatValues` from `bufferUtils` instead */ static ForEach(data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) { EnumerateFloatValues(data, byteOffset, byteStride, componentCount, componentType, count, normalized, (values, index) => { for (let componentIndex = 0; componentIndex < componentCount; componentIndex++) { callback(values[componentIndex], index + componentIndex); } }); } /** * Gets the given data array as a float array. Float data is constructed if the data array cannot be returned directly. * @param data the input data array * @param size the number of components * @param type the component type * @param byteOffset the byte offset of the data * @param byteStride the byte stride of the data * @param normalized whether the data is normalized * @param totalVertices number of vertices in the buffer to take into account * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it * @returns a float array containing vertex data * @deprecated Use `GetFloatData` from `bufferUtils` instead */ static GetFloatData(data, size, type, byteOffset, byteStride, normalized, totalVertices, forceCopy) { return GetFloatData(data, size, type, byteOffset, byteStride, normalized, totalVertices, forceCopy); } }; VertexBuffer._Counter = 0; VertexBuffer.BYTE = 5120; VertexBuffer.UNSIGNED_BYTE = 5121; VertexBuffer.SHORT = 5122; VertexBuffer.UNSIGNED_SHORT = 5123; VertexBuffer.INT = 5124; VertexBuffer.UNSIGNED_INT = 5125; VertexBuffer.FLOAT = 5126; VertexBuffer.PositionKind = `position`; VertexBuffer.NormalKind = `normal`; VertexBuffer.TangentKind = `tangent`; VertexBuffer.UVKind = `uv`; VertexBuffer.UV2Kind = `uv2`; VertexBuffer.UV3Kind = `uv3`; VertexBuffer.UV4Kind = `uv4`; VertexBuffer.UV5Kind = `uv5`; VertexBuffer.UV6Kind = `uv6`; VertexBuffer.ColorKind = `color`; VertexBuffer.ColorInstanceKind = `instanceColor`; VertexBuffer.MatricesIndicesKind = `matricesIndices`; VertexBuffer.MatricesWeightsKind = `matricesWeights`; VertexBuffer.MatricesIndicesExtraKind = `matricesIndicesExtra`; VertexBuffer.MatricesWeightsExtraKind = `matricesWeightsExtra`; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/drawWrapper.js var DrawWrapper; var init_drawWrapper = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/drawWrapper.js"() { init_timingTools(); DrawWrapper = class { static { __name(this, "DrawWrapper"); } /** * Retrieves the effect from a DrawWrapper or Effect instance. * @param effect The effect or DrawWrapper instance to retrieve the effect from. * @returns The effect associated with the given instance, or null if not found. */ static GetEffect(effect) { return effect.getPipelineContext === void 0 ? effect.effect : effect; } /** * Creates a new DrawWrapper instance. * Note that drawContext is always created (but may end up being undefined if the engine doesn't need draw contexts), but materialContext is optional. * @param engine The engine to create the draw wrapper for. * @param createMaterialContext If true, creates a material context for this wrapper (default is true). */ constructor(engine, createMaterialContext = true) { this._wasPreviouslyReady = false; this._forceRebindOnNextCall = true; this._wasPreviouslyUsingInstances = null; this.effect = null; this.defines = null; this.drawContext = engine.createDrawContext(); if (createMaterialContext) { this.materialContext = engine.createMaterialContext(); } } /** * Sets the effect and its associated defines for this wrapper. * @param effect The effect to associate with this wrapper. * @param defines The defines to associate with this wrapper. * @param resetContext If true, resets the draw context (default is true). */ setEffect(effect, defines, resetContext = true) { this.effect = effect; if (defines !== void 0) { this.defines = defines; } if (resetContext) { this.drawContext?.reset(); } } /** * Disposes the effect wrapper and its resources * @param immediate if the effect should be disposed immediately or on the next frame. * If dispose() is not called during a scene or engine dispose, we want to delay the dispose of the underlying effect. Mostly to give a chance to user code to reuse the effect in some way. */ dispose(immediate = false) { if (this.effect) { const effect = this.effect; if (immediate) { effect.dispose(); } else { TimingTools.SetImmediate(() => { effect.getEngine().onEndFrameObservable.addOnce(() => { effect.dispose(); }); }); } this.effect = null; } this.drawContext?.dispose(); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effectRenderer.js var DefaultOptions, EffectRenderer, EffectWrapper; var init_effectRenderer = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effectRenderer.js"() { init_buffer(); init_math_viewport(); init_observable(); init_effect(); init_drawWrapper(); init_postprocess_vertex2(); DefaultOptions = { positions: [1, 1, -1, 1, -1, -1, 1, -1], indices: [0, 1, 2, 0, 2, 3] }; EffectRenderer = class { static { __name(this, "EffectRenderer"); } /** * Creates an effect renderer * @param engine the engine to use for rendering * @param options defines the options of the effect renderer */ constructor(engine, options = DefaultOptions) { this._fullscreenViewport = new Viewport(0, 0, 1, 1); const positions = options.positions ?? DefaultOptions.positions; const indices = options.indices ?? DefaultOptions.indices; this.engine = engine; this._vertexBuffers = { // Note, always assumes stride of 2. [VertexBuffer.PositionKind]: new VertexBuffer(engine, positions, VertexBuffer.PositionKind, false, false, 2) }; this._indexBuffer = engine.createIndexBuffer(indices); this._indexBufferLength = indices.length; this._onContextRestoredObserver = engine.onContextRestoredObservable.add(() => { this._indexBuffer = engine.createIndexBuffer(indices); for (const key in this._vertexBuffers) { const vertexBuffer = this._vertexBuffers[key]; vertexBuffer._rebuild(); } }); } /** * Sets the current viewport in normalized coordinates 0-1 * @param viewport Defines the viewport to set (defaults to 0 0 1 1) */ setViewport(viewport = this._fullscreenViewport) { this.engine.setViewport(viewport); } /** * Binds the embedded attributes buffer to the effect. * @param effect Defines the effect to bind the attributes for */ bindBuffers(effect) { this.engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); } /** * Sets the current effect wrapper to use during draw. * The effect needs to be ready before calling this api. * This also sets the default full screen position attribute. * @param effectWrapper Defines the effect to draw with * @param depthTest Whether to enable depth testing (default: false) * @param stencilTest Whether to enable stencil testing (default: false) */ applyEffectWrapper(effectWrapper, depthTest = false, stencilTest = false) { this.engine.setState(true); this.engine.depthCullingState.depthTest = depthTest; this.engine.stencilState.stencilTest = stencilTest; this.engine.enableEffect(effectWrapper.drawWrapper); this.bindBuffers(effectWrapper.effect); effectWrapper.onApplyObservable.notifyObservers({}); } /** * Saves engine states */ saveStates() { this._savedStateDepthTest = this.engine.depthCullingState.depthTest; this._savedStateStencilTest = this.engine.stencilState.stencilTest; } /** * Restores engine states */ restoreStates() { this.engine.depthCullingState.depthTest = this._savedStateDepthTest; this.engine.stencilState.stencilTest = this._savedStateStencilTest; } /** * Draws a full screen quad. */ draw() { this.engine.drawElementsType(0, 0, this._indexBufferLength); } _isRenderTargetTexture(texture) { return texture.renderTarget !== void 0; } /** * renders one or more effects to a specified texture * @param effectWrapper the effect to renderer * @param outputTexture texture to draw to, if null it will render to the currently bound frame buffer */ render(effectWrapper, outputTexture = null) { if (!effectWrapper.effect.isReady()) { return; } this.saveStates(); this.setViewport(); const out = outputTexture === null ? null : this._isRenderTargetTexture(outputTexture) ? outputTexture.renderTarget : outputTexture; if (out) { this.engine.bindFramebuffer(out); } this.applyEffectWrapper(effectWrapper); this.draw(); if (out) { this.engine.unBindFramebuffer(out); } this.restoreStates(); } /** * Disposes of the effect renderer */ dispose() { const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind]; if (vertexBuffer) { vertexBuffer.dispose(); delete this._vertexBuffers[VertexBuffer.PositionKind]; } if (this._indexBuffer) { this.engine._releaseBuffer(this._indexBuffer); } if (this._onContextRestoredObserver) { this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver); this._onContextRestoredObserver = null; } } }; EffectWrapper = class _EffectWrapper { static { __name(this, "EffectWrapper"); } /** * Registers a shader code processing with an effect wrapper name. * @param effectWrapperName name of the effect wrapper. Use null for the fallback shader code processing. This is the shader code processing that will be used in case no specific shader code processing has been associated to an effect wrapper name * @param customShaderCodeProcessing shader code processing to associate to the effect wrapper name */ static RegisterShaderCodeProcessing(effectWrapperName, customShaderCodeProcessing) { if (!customShaderCodeProcessing) { delete _EffectWrapper._CustomShaderCodeProcessing[effectWrapperName ?? ""]; return; } _EffectWrapper._CustomShaderCodeProcessing[effectWrapperName ?? ""] = customShaderCodeProcessing; } static _GetShaderCodeProcessing(effectWrapperName) { return _EffectWrapper._CustomShaderCodeProcessing[effectWrapperName] ?? _EffectWrapper._CustomShaderCodeProcessing[""]; } /** * Gets or sets the name of the effect wrapper */ get name() { return this.options.name; } set name(value) { this.options.name = value; } /** * Get a value indicating if the effect is ready to be used * @returns true if the post-process is ready (shader is compiled) */ isReady() { return this._drawWrapper.effect?.isReady() ?? false; } /** * Get the draw wrapper associated with the effect wrapper * @returns the draw wrapper associated with the effect wrapper */ get drawWrapper() { return this._drawWrapper; } /** * The underlying effect */ get effect() { return this._drawWrapper.effect; } set effect(effect) { this._drawWrapper.effect = effect; } /** * Creates an effect to be rendered * @param creationOptions options to create the effect */ constructor(creationOptions) { this.alphaMode = 0; this.onEffectCreatedObservable = new Observable(void 0, true); this.onApplyObservable = new Observable(); this._shadersLoaded = false; this._webGPUReady = false; this._importPromises = []; this.options = { ...creationOptions, name: creationOptions.name || "effectWrapper", engine: creationOptions.engine, uniforms: creationOptions.uniforms || creationOptions.uniformNames || [], uniformNames: void 0, samplers: creationOptions.samplers || creationOptions.samplerNames || [], samplerNames: void 0, attributeNames: creationOptions.attributeNames || ["position"], uniformBuffers: creationOptions.uniformBuffers || [], defines: creationOptions.defines || "", useShaderStore: creationOptions.useShaderStore || false, vertexUrl: creationOptions.vertexUrl || creationOptions.vertexShader || "postprocess", vertexShader: void 0, fragmentShader: creationOptions.fragmentShader || "pass", indexParameters: creationOptions.indexParameters, blockCompilation: creationOptions.blockCompilation || false, shaderLanguage: creationOptions.shaderLanguage || 0, onCompiled: creationOptions.onCompiled || void 0, extraInitializations: creationOptions.extraInitializations || void 0, extraInitializationsAsync: creationOptions.extraInitializationsAsync || void 0, useAsPostProcess: creationOptions.useAsPostProcess ?? false, allowEmptySourceTexture: creationOptions.allowEmptySourceTexture ?? false }; this.options.uniformNames = this.options.uniforms; this.options.samplerNames = this.options.samplers; this.options.vertexShader = this.options.vertexUrl; if (this.options.useAsPostProcess) { if (!this.options.allowEmptySourceTexture && this.options.samplers.indexOf("textureSampler") === -1) { this.options.samplers.push("textureSampler"); } if (this.options.uniforms.indexOf("scale") === -1) { this.options.uniforms.push("scale"); } } if (creationOptions.vertexUrl || creationOptions.vertexShader) { this._shaderPath = { vertexSource: this.options.vertexShader }; } else { if (!this.options.useAsPostProcess) { this.options.uniforms.push("scale"); this.onApplyObservable.add(() => { this.effect.setFloat2("scale", 1, 1); }); } this._shaderPath = { vertex: this.options.vertexShader }; } this._shaderPath.fragmentSource = this.options.fragmentShader; this._shaderPath.spectorName = this.options.name; if (this.options.useShaderStore) { this._shaderPath.fragment = this._shaderPath.fragmentSource; if (!this._shaderPath.vertex) { this._shaderPath.vertex = this._shaderPath.vertexSource; } delete this._shaderPath.fragmentSource; delete this._shaderPath.vertexSource; } this.onApplyObservable.add(() => { this.bind(); }); if (!this.options.useShaderStore) { this._onContextRestoredObserver = this.options.engine.onContextRestoredObservable.add(() => { this.effect._pipelineContext = null; this.effect._prepareEffect(); }); } this._drawWrapper = new DrawWrapper(this.options.engine); this._webGPUReady = this.options.shaderLanguage === 1; const defines = Array.isArray(this.options.defines) ? this.options.defines.join("\n") : this.options.defines; this._postConstructor(this.options.blockCompilation, defines, this.options.extraInitializations); } _gatherImports(useWebGPU = false, list) { if (!this.options.useAsPostProcess) { return; } if (useWebGPU && this._webGPUReady) { list.push(Promise.all([Promise.resolve().then(() => (init_postprocess_vertex(), postprocess_vertex_exports))])); } else { list.push(Promise.all([Promise.resolve().then(() => (init_postprocess_vertex2(), postprocess_vertex_exports2))])); } } /** @internal */ _postConstructor(blockCompilation, defines = null, extraInitializations, importPromises) { this._importPromises.length = 0; if (importPromises) { this._importPromises.push(...importPromises); } const useWebGPU = this.options.engine.isWebGPU && !_EffectWrapper.ForceGLSL; this._gatherImports(useWebGPU, this._importPromises); if (extraInitializations !== void 0) { extraInitializations(useWebGPU, this._importPromises); } if (useWebGPU && this._webGPUReady) { this.options.shaderLanguage = 1; } if (!blockCompilation) { this.updateEffect(defines); } } /** * Updates the effect with the current effect wrapper compile time values and recompiles the shader. * @param defines Define statements that should be added at the beginning of the shader. (default: null) * @param uniforms Set of uniform variables that will be passed to the shader. (default: null) * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null) * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx * @param onCompiled Called when the shader has been compiled. * @param onError Called if there is an error when compiling a shader. * @param vertexUrl The url of the vertex shader to be used (default: the one given at construction time) * @param fragmentUrl The url of the fragment shader to be used (default: the one given at construction time) */ updateEffect(defines = null, uniforms = null, samplers = null, indexParameters, onCompiled, onError, vertexUrl, fragmentUrl) { const customShaderCodeProcessing = _EffectWrapper._GetShaderCodeProcessing(this.name); if (customShaderCodeProcessing?.defineCustomBindings) { const newUniforms = uniforms?.slice() ?? []; newUniforms.push(...this.options.uniforms); const newSamplers = samplers?.slice() ?? []; newSamplers.push(...this.options.samplers); defines = customShaderCodeProcessing.defineCustomBindings(this.name, defines, newUniforms, newSamplers); uniforms = newUniforms; samplers = newSamplers; } this.options.defines = defines || ""; const waitImportsLoaded = this._shadersLoaded || this._importPromises.length === 0 ? void 0 : async () => { await Promise.all(this._importPromises); this._shadersLoaded = true; }; let extraInitializationsAsync; if (this.options.extraInitializationsAsync) { extraInitializationsAsync = /* @__PURE__ */ __name(async () => { waitImportsLoaded?.(); await this.options.extraInitializationsAsync(); }, "extraInitializationsAsync"); } else { extraInitializationsAsync = waitImportsLoaded; } if (this.options.useShaderStore) { this._drawWrapper.effect = this.options.engine.createEffect({ vertex: vertexUrl ?? this._shaderPath.vertex, fragment: fragmentUrl ?? this._shaderPath.fragment }, { attributes: this.options.attributeNames, uniformsNames: uniforms || this.options.uniforms, uniformBuffersNames: this.options.uniformBuffers, samplers: samplers || this.options.samplers, defines: defines !== null ? defines : "", fallbacks: null, onCompiled: onCompiled ?? this.options.onCompiled, onError: onError ?? null, indexParameters: indexParameters || this.options.indexParameters, processCodeAfterIncludes: customShaderCodeProcessing?.processCodeAfterIncludes ? (shaderType, code) => customShaderCodeProcessing.processCodeAfterIncludes(this.name, shaderType, code) : null, processFinalCode: customShaderCodeProcessing?.processFinalCode ? (shaderType, code) => customShaderCodeProcessing.processFinalCode(this.name, shaderType, code) : null, shaderLanguage: this.options.shaderLanguage, extraInitializationsAsync }, this.options.engine); } else { this._drawWrapper.effect = new Effect(this._shaderPath, this.options.attributeNames, uniforms || this.options.uniforms, samplers || this.options.samplerNames, this.options.engine, defines, void 0, onCompiled || this.options.onCompiled, void 0, void 0, void 0, this.options.shaderLanguage, extraInitializationsAsync); } this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect); } /** * Binds the data to the effect. * @param noDefaultBindings if true, the default bindings (scale and alpha mode) will not be set. */ bind(noDefaultBindings = false) { if (this.options.useAsPostProcess && !noDefaultBindings) { this.options.engine.setAlphaMode(this.alphaMode); this.drawWrapper.effect.setFloat2("scale", 1, 1); } _EffectWrapper._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name, this._drawWrapper.effect); } /** * Disposes of the effect wrapper * @param _ignored kept for backward compatibility */ dispose(_ignored = false) { if (this._onContextRestoredObserver) { this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver); this._onContextRestoredObserver = null; } this.onEffectCreatedObservable.clear(); this._drawWrapper.dispose(true); } }; EffectWrapper.ForceGLSL = false; EffectWrapper._CustomShaderCodeProcessing = {}; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/dumpTools.js var dumpTools_exports = {}; __export(dumpTools_exports, { Dispose: () => Dispose, DumpData: () => DumpData, DumpDataAsync: () => DumpDataAsync, DumpFramebuffer: () => DumpFramebuffer, DumpTools: () => DumpTools }); async function _CreateDumpResourcesAsync() { const canvas = EngineStore.LastCreatedEngine?.createCanvas(100, 100) ?? new OffscreenCanvas(100, 100); if (canvas instanceof OffscreenCanvas) { Logger.Warn("DumpData: OffscreenCanvas will be used for dumping data. This may result in lossy alpha values."); } const { ThinEngine: thinEngineClass } = await Promise.resolve().then(() => (init_thinEngine(), thinEngine_exports)); if (!thinEngineClass.IsSupported) { if (!canvas.getContext("bitmaprenderer")) { throw new Error("DumpData: No WebGL or bitmap rendering context available. Cannot dump data."); } return { canvas }; } const options = { preserveDrawingBuffer: true, depth: false, stencil: false, alpha: true, premultipliedAlpha: false, antialias: false, failIfMajorPerformanceCaveat: false }; const engine = new thinEngineClass(canvas, false, options); EngineStore.Instances.pop(); EngineStore.OnEnginesDisposedObservable.add((e) => { if (engine && e !== engine && !engine.isDisposed && EngineStore.Instances.length === 0) { Dispose(); } }); engine.getCaps().parallelShaderCompile = void 0; const renderer = new EffectRenderer(engine); const { passPixelShader: passPixelShader2 } = await Promise.resolve().then(() => (init_pass_fragment(), pass_fragment_exports)); const wrapper = new EffectWrapper({ engine, name: passPixelShader2.name, fragmentShader: passPixelShader2.shader, samplerNames: ["textureSampler"] }); return { canvas, dumpEngine: { engine, renderer, wrapper } }; } async function _GetDumpResourcesAsync() { if (!ResourcesPromise) { ResourcesPromise = _CreateDumpResourcesAsync(); } return await ResourcesPromise; } async function DumpFramebuffer(width, height, engine, successCallback, mimeType = "image/png", fileName, quality) { const bufferView = await engine.readPixels(0, 0, width, height); const data = new Uint8Array(bufferView.buffer); DumpData(width, height, data, successCallback, mimeType, fileName, true, void 0, quality); } async function DumpDataAsync(width, height, data, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) { if (data instanceof Float32Array) { const data2 = new Uint8Array(data.length); let n = data.length; while (n--) { const v = data[n]; data2[n] = Math.round(Clamp(v) * 255); } data = data2; } const resources = await _GetDumpResourcesAsync(); return await new Promise(async (resolve) => { if (resources.dumpEngine) { const dumpEngine = resources.dumpEngine; dumpEngine.engine.setSize(width, height, true); const texture = dumpEngine.engine.createRawTexture(data, width, height, 5, false, !invertY, 1); dumpEngine.renderer.setViewport(); dumpEngine.renderer.applyEffectWrapper(dumpEngine.wrapper); dumpEngine.wrapper.effect._bindTexture("textureSampler", texture); dumpEngine.renderer.draw(); texture.dispose(); } else { const ctx = resources.canvas.getContext("bitmaprenderer"); resources.canvas.width = width; resources.canvas.height = height; const imageData = new ImageData(width, height); imageData.data.set(data); const imageBitmap = await createImageBitmap(imageData, { premultiplyAlpha: "none", imageOrientation: invertY ? "flipY" : "from-image" }); ctx.transferFromImageBitmap(imageBitmap); } Tools.ToBlob(resources.canvas, (blob) => { if (!blob) { throw new Error("DumpData: Failed to convert canvas to blob."); } if (fileName !== void 0) { Tools.DownloadBlob(blob, fileName); } const fileReader = new FileReader(); fileReader.onload = (event) => { const result = event.target.result; resolve(result); }; if (toArrayBuffer) { fileReader.readAsArrayBuffer(blob); } else { fileReader.readAsDataURL(blob); } }, mimeType, quality); }); } function DumpData(width, height, data, successCallback, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) { if (fileName === void 0 && !successCallback) { fileName = ""; } DumpDataAsync(width, height, data, mimeType, fileName, invertY, toArrayBuffer, quality).then((result) => { if (successCallback) { successCallback(result); } }); } function Dispose() { if (!ResourcesPromise) { return; } ResourcesPromise?.then((resources) => { if (resources.canvas instanceof HTMLCanvasElement) { resources.canvas.remove(); } if (resources.dumpEngine) { resources.dumpEngine.engine.dispose(); resources.dumpEngine.renderer.dispose(); resources.dumpEngine.wrapper.dispose(); } }); ResourcesPromise = null; } var ResourcesPromise, DumpTools, InitSideEffects; var init_dumpTools = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/dumpTools.js"() { init_effectRenderer(); init_tools(); init_math_scalar_functions(); init_engineStore(); init_logger(); ResourcesPromise = null; __name(_CreateDumpResourcesAsync, "_CreateDumpResourcesAsync"); __name(_GetDumpResourcesAsync, "_GetDumpResourcesAsync"); __name(DumpFramebuffer, "DumpFramebuffer"); __name(DumpDataAsync, "DumpDataAsync"); __name(DumpData, "DumpData"); __name(Dispose, "Dispose"); DumpTools = { // eslint-disable-next-line @typescript-eslint/naming-convention DumpData, // eslint-disable-next-line @typescript-eslint/naming-convention DumpDataAsync, // eslint-disable-next-line @typescript-eslint/naming-convention DumpFramebuffer, // eslint-disable-next-line @typescript-eslint/naming-convention Dispose }; InitSideEffects = /* @__PURE__ */ __name(() => { Tools.DumpData = DumpData; Tools.DumpDataAsync = DumpDataAsync; Tools.DumpFramebuffer = DumpFramebuffer; }, "InitSideEffects"); InitSideEffects(); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/postProcessManager.js var PostProcessManager; var init_postProcessManager = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/postProcessManager.js"() { init_buffer(); init_observable(); PostProcessManager = class { static { __name(this, "PostProcessManager"); } /** * Creates a new instance PostProcess * @param scene The scene that the post process is associated with. */ constructor(scene) { this._vertexBuffers = {}; this.onBeforeRenderObservable = new Observable(); this._scene = scene; } _prepareBuffers() { if (this._vertexBuffers[VertexBuffer.PositionKind]) { return; } const vertices = []; vertices.push(1, 1); vertices.push(-1, 1); vertices.push(-1, -1); vertices.push(1, -1); this._vertexBuffers[VertexBuffer.PositionKind] = new VertexBuffer(this._scene.getEngine(), vertices, VertexBuffer.PositionKind, false, false, 2); this._buildIndexBuffer(); } _buildIndexBuffer() { const indices = []; indices.push(0); indices.push(1); indices.push(2); indices.push(0); indices.push(2); indices.push(3); this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices); } /** * Rebuilds the vertex buffers of the manager. * @internal */ _rebuild() { const vb = this._vertexBuffers[VertexBuffer.PositionKind]; if (!vb) { return; } vb._rebuild(); this._buildIndexBuffer(); } // Methods /** * Prepares a frame to be run through a post process. * @param sourceTexture The input texture to the post processes. (default: null) * @param postProcesses An array of post processes to be run. (default: null) * @returns True if the post processes were able to be run. * @internal */ _prepareFrame(sourceTexture = null, postProcesses = null) { const camera = this._scene.activeCamera; if (!camera) { return false; } postProcesses = postProcesses || camera._postProcesses.filter((pp) => { return pp != null; }); if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) { return false; } postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== void 0); return true; } /** * Manually render a set of post processes to a texture. * Please note, the frame buffer won't be unbound after the call in case you have more render to do. * @param postProcesses An array of post processes to be run. * @param targetTexture The render target wrapper to render to. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight * @param faceIndex defines the face to render to if a cubemap is defined as the target * @param lodLevel defines which lod of the texture to render to * @param doNotBindFrambuffer If set to true, assumes that the framebuffer has been bound previously * @param numPostsProcesses The number of post processes to render. Defaults to the length of the postProcesses array. */ directRender(postProcesses, targetTexture = null, forceFullscreenViewport = false, faceIndex = 0, lodLevel = 0, doNotBindFrambuffer = false, numPostsProcesses = postProcesses.length) { const engine = this._scene.getEngine(); for (let index = 0; index < numPostsProcesses; index++) { if (index < postProcesses.length - 1) { postProcesses[index + 1].activate(this._scene.activeCamera || this._scene, targetTexture?.texture); } else { if (targetTexture) { engine.bindFramebuffer(targetTexture, faceIndex, void 0, void 0, forceFullscreenViewport, lodLevel); } else if (!doNotBindFrambuffer) { engine.restoreDefaultFramebuffer(); } engine._debugInsertMarker?.(`post process ${postProcesses[index].name} output`); } const pp = postProcesses[index]; const effect = pp.apply(); if (effect) { pp.onBeforeRenderObservable.notifyObservers(effect); this._prepareBuffers(); engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); engine.drawElementsType(0, 0, 6); pp.onAfterRenderObservable.notifyObservers(effect); } } engine.setDepthBuffer(true); engine.setDepthWrite(true); } /** * Finalize the result of the output of the postprocesses. * @param doNotPresent If true the result will not be displayed to the screen. * @param targetTexture The render target wrapper to render to. * @param faceIndex The index of the face to bind the target texture to. * @param postProcesses The array of post processes to render. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false) * @internal */ _finalizeFrame(doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport = false) { const camera = this._scene.activeCamera; if (!camera) { return; } this.onBeforeRenderObservable.notifyObservers(this); postProcesses = postProcesses || camera._postProcesses.filter((pp) => { return pp != null; }); if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) { return; } const engine = this._scene.getEngine(); for (let index = 0, len = postProcesses.length; index < len; index++) { const pp = postProcesses[index]; if (index < len - 1) { pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture?.texture); } else { if (targetTexture) { engine.bindFramebuffer(targetTexture, faceIndex, void 0, void 0, forceFullscreenViewport); pp._outputTexture = targetTexture; } else { engine.restoreDefaultFramebuffer(); pp._outputTexture = null; } engine._debugInsertMarker?.(`post process ${postProcesses[index].name} output`); } if (doNotPresent) { break; } const effect = pp.apply(); if (effect) { pp.onBeforeRenderObservable.notifyObservers(effect); this._prepareBuffers(); engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); engine.drawElementsType(0, 0, 6); pp.onAfterRenderObservable.notifyObservers(effect); } } engine.setDepthBuffer(true); engine.setDepthWrite(true); engine.setAlphaMode(0); } /** * Disposes of the post process manager. */ dispose() { const buffer = this._vertexBuffers[VertexBuffer.PositionKind]; if (buffer) { buffer.dispose(); this._vertexBuffers[VertexBuffer.PositionKind] = null; } if (this._indexBuffer) { this._scene.getEngine()._releaseBuffer(this._indexBuffer); this._indexBuffer = null; } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/smartArray.js var SmartArray, SmartArrayNoDuplicate; var init_smartArray = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/smartArray.js"() { SmartArray = class _SmartArray { static { __name(this, "SmartArray"); } /** * Instantiates a Smart Array. * @param capacity defines the default capacity of the array. */ constructor(capacity) { this.length = 0; this.data = new Array(capacity); this._id = _SmartArray._GlobalId++; } /** * Pushes a value at the end of the active data. * @param value defines the object to push in the array. */ push(value) { this.data[this.length++] = value; if (this.length > this.data.length) { this.data.length *= 2; } } /** * Iterates over the active data and apply the lambda to them. * @param func defines the action to apply on each value. */ forEach(func) { for (let index = 0; index < this.length; index++) { func(this.data[index]); } } /** * Sorts the full sets of data. * @param compareFn defines the comparison function to apply. */ sort(compareFn) { this.data.sort(compareFn); } /** * Resets the active data to an empty array. */ reset() { this.length = 0; } /** * Releases all the data from the array as well as the array. */ dispose() { this.reset(); if (this.data) { this.data.length = 0; } } /** * Concats the active data with a given array. * @param array defines the data to concatenate with. */ concat(array) { if (array.length === 0) { return; } if (this.length + array.length > this.data.length) { this.data.length = (this.length + array.length) * 2; } for (let index = 0; index < array.length; index++) { this.data[this.length++] = (array.data || array)[index]; } } /** * Returns the position of a value in the active data. * @param value defines the value to find the index for * @returns the index if found in the active data otherwise -1 */ indexOf(value) { const position = this.data.indexOf(value); if (position >= this.length) { return -1; } return position; } /** * Returns whether an element is part of the active data. * @param value defines the value to look for * @returns true if found in the active data otherwise false */ contains(value) { return this.indexOf(value) !== -1; } }; SmartArray._GlobalId = 0; SmartArrayNoDuplicate = class extends SmartArray { static { __name(this, "SmartArrayNoDuplicate"); } constructor() { super(...arguments); this._duplicateId = 0; } /** * Pushes a value at the end of the active data. * THIS DOES NOT PREVENT DUPPLICATE DATA * @param value defines the object to push in the array. */ push(value) { super.push(value); if (!value.__smartArrayFlags) { value.__smartArrayFlags = {}; } value.__smartArrayFlags[this._id] = this._duplicateId; } /** * Pushes a value at the end of the active data. * If the data is already present, it won t be added again * @param value defines the object to push in the array. * @returns true if added false if it was already present */ pushNoDuplicate(value) { if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) { return false; } this.push(value); return true; } /** * Resets the active data to an empty array. */ reset() { super.reset(); this._duplicateId++; } /** * Concats the active data with a given array. * This ensures no duplicate will be present in the result. * @param array defines the data to concatenate with. */ concatWithNoDuplicate(array) { if (array.length === 0) { return; } if (this.length + array.length > this.data.length) { this.data.length = (this.length + array.length) * 2; } for (let index = 0; index < array.length; index++) { const item = (array.data || array)[index]; this.pushNoDuplicate(item); } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/renderingGroup.js var RenderingGroup; var init_renderingGroup = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/renderingGroup.js"() { init_smartArray(); init_math_vector(); RenderingGroup = class _RenderingGroup { static { __name(this, "RenderingGroup"); } /** * Set the opaque sort comparison function. * If null the sub meshes will be render in the order they were created */ set opaqueSortCompareFn(value) { if (value) { this._opaqueSortCompareFn = value; } else { this._opaqueSortCompareFn = _RenderingGroup.PainterSortCompare; } this._renderOpaque = this._renderOpaqueSorted; } /** * Set the alpha test sort comparison function. * If null the sub meshes will be render in the order they were created */ set alphaTestSortCompareFn(value) { if (value) { this._alphaTestSortCompareFn = value; } else { this._alphaTestSortCompareFn = _RenderingGroup.PainterSortCompare; } this._renderAlphaTest = this._renderAlphaTestSorted; } /** * Set the transparent sort comparison function. * If null the sub meshes will be render in the order they were created */ set transparentSortCompareFn(value) { if (value) { this._transparentSortCompareFn = value; } else { this._transparentSortCompareFn = _RenderingGroup.defaultTransparentSortCompare; } this._renderTransparent = this._renderTransparentSorted; } /** * Creates a new rendering group. * @param index The rendering group index * @param scene * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied */ constructor(index, scene, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) { this.index = index; this._opaqueSubMeshes = new SmartArray(256); this._transparentSubMeshes = new SmartArray(256); this._alphaTestSubMeshes = new SmartArray(256); this._depthOnlySubMeshes = new SmartArray(256); this._particleSystems = new SmartArray(256); this._spriteManagers = new SmartArray(256); this._empty = true; this._edgesRenderers = new SmartArrayNoDuplicate(16); this.disableDepthPrePass = false; this._scene = scene; this.opaqueSortCompareFn = opaqueSortCompareFn; this.alphaTestSortCompareFn = alphaTestSortCompareFn; this.transparentSortCompareFn = transparentSortCompareFn; } /** * Render all the sub meshes contained in the group. * @param customRenderFunction Used to override the default render behaviour of the group. * @param renderSprites * @param renderParticles * @param activeMeshes */ render(customRenderFunction, renderSprites, renderParticles, activeMeshes) { if (customRenderFunction) { customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes); return; } const engine = this._scene.getEngine(); if (this._depthOnlySubMeshes.length !== 0) { engine.setColorWrite(false); this._renderAlphaTest(this._depthOnlySubMeshes); engine.setColorWrite(true); } if (this._opaqueSubMeshes.length !== 0) { this._renderOpaque(this._opaqueSubMeshes); } if (this._alphaTestSubMeshes.length !== 0) { this._renderAlphaTest(this._alphaTestSubMeshes); } const stencilState = engine.getStencilBuffer(); engine.setStencilBuffer(false); if (renderSprites) { this._renderSprites(); } if (renderParticles) { this._renderParticles(activeMeshes); } if (this.onBeforeTransparentRendering) { this.onBeforeTransparentRendering(); } if (this._transparentSubMeshes.length !== 0 || this._scene.useOrderIndependentTransparency) { engine.setStencilBuffer(stencilState); if (this._scene.useOrderIndependentTransparency) { const excludedMeshes = this._scene.depthPeelingRenderer.render(this._transparentSubMeshes); if (excludedMeshes.length) { this._renderTransparent(excludedMeshes); } } else { this._renderTransparent(this._transparentSubMeshes); } engine.setAlphaMode(0); } engine.setStencilBuffer(false); if (this._edgesRenderers.length) { for (let edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) { this._edgesRenderers.data[edgesRendererIndex].render(); } engine.setAlphaMode(0); } engine.setStencilBuffer(stencilState); } /** * Renders the opaque submeshes in the order from the opaqueSortCompareFn. * @param subMeshes The submeshes to render */ _renderOpaqueSorted(subMeshes) { _RenderingGroup._RenderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false, this.disableDepthPrePass); } /** * Renders the opaque submeshes in the order from the alphatestSortCompareFn. * @param subMeshes The submeshes to render */ _renderAlphaTestSorted(subMeshes) { _RenderingGroup._RenderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false, this.disableDepthPrePass); } /** * Renders the opaque submeshes in the order from the transparentSortCompareFn. * @param subMeshes The submeshes to render */ _renderTransparentSorted(subMeshes) { _RenderingGroup._RenderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true, this.disableDepthPrePass); } /** * Renders the submeshes in a specified order. * @param subMeshes The submeshes to sort before render * @param sortCompareFn The comparison function use to sort * @param camera The camera position use to preprocess the submeshes to help sorting * @param transparent Specifies to activate blending if true * @param disableDepthPrePass Specifies to disable depth pre-pass if true (default: false) */ static _RenderSorted(subMeshes, sortCompareFn, camera, transparent, disableDepthPrePass) { let subIndex = 0; let subMesh; const cameraPosition = camera ? camera.globalPosition : _RenderingGroup._ZeroVector; if (transparent) { for (; subIndex < subMeshes.length; subIndex++) { subMesh = subMeshes.data[subIndex]; subMesh._alphaIndex = subMesh.getMesh().alphaIndex; subMesh._distanceToCamera = Vector3.Distance(subMesh.getBoundingInfo().boundingSphere.centerWorld, cameraPosition); } } const sortedArray = subMeshes.length === subMeshes.data.length ? subMeshes.data : subMeshes.data.slice(0, subMeshes.length); if (sortCompareFn) { sortedArray.sort(sortCompareFn); } const scene = sortedArray[0].getMesh().getScene(); for (subIndex = 0; subIndex < sortedArray.length; subIndex++) { subMesh = sortedArray[subIndex]; if (scene._activeMeshesFrozenButKeepClipping && !subMesh.isInFrustum(scene._frustumPlanes)) { continue; } if (transparent) { const material = subMesh.getMaterial(); if (material && material.needDepthPrePass && !disableDepthPrePass) { const engine = material.getScene().getEngine(); engine.setColorWrite(false); engine.setAlphaMode(0); subMesh.render(false); engine.setColorWrite(true); } } subMesh.render(transparent); } } /** * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) * are rendered back to front if in the same alpha index. * * @param a The first submesh * @param b The second submesh * @returns The result of the comparison */ // eslint-disable-next-line @typescript-eslint/naming-convention static defaultTransparentSortCompare(a, b) { if (a._alphaIndex > b._alphaIndex) { return 1; } if (a._alphaIndex < b._alphaIndex) { return -1; } return _RenderingGroup.backToFrontSortCompare(a, b); } /** * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) * are rendered back to front. * * @param a The first submesh * @param b The second submesh * @returns The result of the comparison */ // eslint-disable-next-line @typescript-eslint/naming-convention static backToFrontSortCompare(a, b) { if (a._distanceToCamera < b._distanceToCamera) { return 1; } if (a._distanceToCamera > b._distanceToCamera) { return -1; } return 0; } /** * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) * are rendered front to back (prevent overdraw). * * @param a The first submesh * @param b The second submesh * @returns The result of the comparison */ // eslint-disable-next-line @typescript-eslint/naming-convention static frontToBackSortCompare(a, b) { if (a._distanceToCamera < b._distanceToCamera) { return -1; } if (a._distanceToCamera > b._distanceToCamera) { return 1; } return 0; } /** * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) * are grouped by material then geometry. * * @param a The first submesh * @param b The second submesh * @returns The result of the comparison */ static PainterSortCompare(a, b) { const meshA = a.getMesh(); const meshB = b.getMesh(); if (meshA.material && meshB.material) { return meshA.material.uniqueId - meshB.material.uniqueId; } return meshA.uniqueId - meshB.uniqueId; } /** * Resets the different lists of submeshes to prepare a new frame. */ prepare() { this._opaqueSubMeshes.reset(); this._transparentSubMeshes.reset(); this._alphaTestSubMeshes.reset(); this._depthOnlySubMeshes.reset(); this._particleSystems.reset(); this.prepareSprites(); this._edgesRenderers.reset(); this._empty = true; } /** * Resets the different lists of sprites to prepare a new frame. */ prepareSprites() { this._spriteManagers.reset(); } dispose() { this._opaqueSubMeshes.dispose(); this._transparentSubMeshes.dispose(); this._alphaTestSubMeshes.dispose(); this._depthOnlySubMeshes.dispose(); this._particleSystems.dispose(); this._spriteManagers.dispose(); this._edgesRenderers.dispose(); } /** * Inserts the submesh in its correct queue depending on its material. * @param subMesh The submesh to dispatch * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance. */ dispatch(subMesh, mesh, material) { if (mesh === void 0) { mesh = subMesh.getMesh(); } if (material === void 0) { material = subMesh.getMaterial(); } if (material === null || material === void 0) { return; } if (material.needAlphaBlendingForMesh(mesh)) { this._transparentSubMeshes.push(subMesh); } else if (material.needAlphaTestingForMesh(mesh)) { if (material.needDepthPrePass && !this.disableDepthPrePass) { this._depthOnlySubMeshes.push(subMesh); } this._alphaTestSubMeshes.push(subMesh); } else { if (material.needDepthPrePass && !this.disableDepthPrePass) { this._depthOnlySubMeshes.push(subMesh); } this._opaqueSubMeshes.push(subMesh); } mesh._renderingGroup = this; if (mesh._edgesRenderer && mesh.isEnabled() && mesh.isVisible && mesh._edgesRenderer.isEnabled) { this._edgesRenderers.pushNoDuplicate(mesh._edgesRenderer); } this._empty = false; } dispatchSprites(spriteManager) { this._spriteManagers.push(spriteManager); this._empty = false; } dispatchParticles(particleSystem) { this._particleSystems.push(particleSystem); this._empty = false; } _renderParticles(activeMeshes) { if (this._particleSystems.length === 0) { return; } const activeCamera = this._scene.activeCamera; this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene); for (let particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) { const particleSystem = this._particleSystems.data[particleIndex]; if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) { continue; } const emitter = particleSystem.emitter; if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) { this._scene._activeParticles.addCount(particleSystem.render(), false); } } this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene); } _renderSprites() { if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) { return; } const activeCamera = this._scene.activeCamera; this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene); for (let id = 0; id < this._spriteManagers.length; id++) { const spriteManager = this._spriteManagers.data[id]; if ((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0) { spriteManager.render(); } } this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene); } }; RenderingGroup._ZeroVector = Vector3.Zero(); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/renderingManager.js var RenderingGroupInfo, RenderingManager; var init_renderingManager = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/renderingManager.js"() { init_renderingGroup(); RenderingGroupInfo = class { static { __name(this, "RenderingGroupInfo"); } }; RenderingManager = class _RenderingManager { static { __name(this, "RenderingManager"); } /** * Specifies to disable depth pre-pass if true (default: false) */ get disableDepthPrePass() { return this._disableDepthPrePass; } set disableDepthPrePass(value) { this._disableDepthPrePass = value; for (const group of this._renderingGroups) { group.disableDepthPrePass = value; } } /** * Gets or sets a boolean indicating that the manager will not reset between frames. * This means that if a mesh becomes invisible or transparent it will not be visible until this boolean is set to false again. * By default, the rendering manager will dispatch all active meshes per frame (moving them to the transparent, opaque or alpha testing lists). * By turning this property on, you will accelerate the rendering by keeping all these lists unchanged between frames. */ get maintainStateBetweenFrames() { return this._maintainStateBetweenFrames; } set maintainStateBetweenFrames(value) { if (value === this._maintainStateBetweenFrames) { return; } this._maintainStateBetweenFrames = value; if (!this._maintainStateBetweenFrames) { this.restoreDispachedFlags(); } } /** * Restore wasDispatched flags on the lists of elements to render. */ restoreDispachedFlags() { for (const mesh of this._scene.meshes) { if (mesh.subMeshes) { for (const subMesh of mesh.subMeshes) { subMesh._wasDispatched = false; } } } if (this._scene.spriteManagers) { for (const spriteManager of this._scene.spriteManagers) { spriteManager._wasDispatched = false; } } for (const particleSystem of this._scene.particleSystems) { particleSystem._wasDispatched = false; } } /** * Instantiates a new rendering group for a particular scene * @param scene Defines the scene the groups belongs to */ constructor(scene) { this._useSceneAutoClearSetup = false; this._disableDepthPrePass = false; this._renderingGroups = new Array(); this._autoClearDepthStencil = {}; this._customOpaqueSortCompareFn = {}; this._customAlphaTestSortCompareFn = {}; this._customTransparentSortCompareFn = {}; this._renderingGroupInfo = new RenderingGroupInfo(); this._maintainStateBetweenFrames = false; this._scene = scene; for (let i = _RenderingManager.MIN_RENDERINGGROUPS; i < _RenderingManager.MAX_RENDERINGGROUPS; i++) { this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true }; } } /** * @returns the rendering group with the specified id. * @param id the id of the rendering group (0 by default) */ getRenderingGroup(id) { const renderingGroupId = id || 0; this._prepareRenderingGroup(renderingGroupId); return this._renderingGroups[renderingGroupId]; } _clearDepthStencilBuffer(depth = true, stencil = true) { if (this._depthStencilBufferAlreadyCleaned) { return; } this._scene.getEngine().clear(null, false, depth, stencil); this._depthStencilBufferAlreadyCleaned = true; } /** * Renders the entire managed groups. This is used by the scene or the different render targets. * @internal */ render(customRenderFunction, activeMeshes, renderParticles, renderSprites) { const info = this._renderingGroupInfo; info.scene = this._scene; info.camera = this._scene.activeCamera; info.renderingManager = this; if (this._scene.spriteManagers && renderSprites) { for (let index = 0; index < this._scene.spriteManagers.length; index++) { const manager = this._scene.spriteManagers[index]; this.dispatchSprites(manager); } } for (let index = _RenderingManager.MIN_RENDERINGGROUPS; index < _RenderingManager.MAX_RENDERINGGROUPS; index++) { this._depthStencilBufferAlreadyCleaned = index === _RenderingManager.MIN_RENDERINGGROUPS; const renderingGroup = this._renderingGroups[index]; if (!renderingGroup || renderingGroup._empty) { continue; } const renderingGroupMask = 1 << index; info.renderingGroupId = index; this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask); if (_RenderingManager.AUTOCLEAR) { const autoClear = this._useSceneAutoClearSetup ? this._scene.getAutoClearDepthStencilSetup(index) : this._autoClearDepthStencil[index]; if (autoClear && autoClear.autoClear) { this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil); } } for (const step of this._scene._beforeRenderingGroupDrawStage) { step.action(index); } renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes); for (const step of this._scene._afterRenderingGroupDrawStage) { step.action(index); } this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask); } } /** * Resets the different information of the group to prepare a new frame * @internal */ reset() { if (this.maintainStateBetweenFrames) { return; } for (let index = _RenderingManager.MIN_RENDERINGGROUPS; index < _RenderingManager.MAX_RENDERINGGROUPS; index++) { const renderingGroup = this._renderingGroups[index]; if (renderingGroup) { renderingGroup.prepare(); } } } /** * Resets the sprites information of the group to prepare a new frame * @internal */ resetSprites() { if (this.maintainStateBetweenFrames) { return; } for (let index = _RenderingManager.MIN_RENDERINGGROUPS; index < _RenderingManager.MAX_RENDERINGGROUPS; index++) { const renderingGroup = this._renderingGroups[index]; if (renderingGroup) { renderingGroup.prepareSprites(); } } } /** * Dispose and release the group and its associated resources. * @internal */ dispose() { this.freeRenderingGroups(); this._renderingGroups.length = 0; this._renderingGroupInfo = null; } /** * Clear the info related to rendering groups preventing retention points during dispose. */ freeRenderingGroups() { for (let index = _RenderingManager.MIN_RENDERINGGROUPS; index < _RenderingManager.MAX_RENDERINGGROUPS; index++) { const renderingGroup = this._renderingGroups[index]; if (renderingGroup) { renderingGroup.dispose(); } } } _prepareRenderingGroup(renderingGroupId) { if (this._renderingGroups[renderingGroupId] === void 0) { this._renderingGroups[renderingGroupId] = new RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]); this._renderingGroups[renderingGroupId].disableDepthPrePass = this._disableDepthPrePass; } } /** * Add a sprite manager to the rendering manager in order to render it this frame. * @param spriteManager Define the sprite manager to render */ dispatchSprites(spriteManager) { if (this.maintainStateBetweenFrames && spriteManager._wasDispatched) { return; } spriteManager._wasDispatched = true; this.getRenderingGroup(spriteManager.renderingGroupId).dispatchSprites(spriteManager); } /** * Add a particle system to the rendering manager in order to render it this frame. * @param particleSystem Define the particle system to render */ dispatchParticles(particleSystem) { if (this.maintainStateBetweenFrames && particleSystem._wasDispatched) { return; } particleSystem._wasDispatched = true; this.getRenderingGroup(particleSystem.renderingGroupId).dispatchParticles(particleSystem); } /** * Add a submesh to the manager in order to render it this frame * @param subMesh The submesh to dispatch * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance. */ dispatch(subMesh, mesh, material) { if (mesh === void 0) { mesh = subMesh.getMesh(); } if (this.maintainStateBetweenFrames && subMesh._wasDispatched) { return; } subMesh._wasDispatched = true; this.getRenderingGroup(mesh.renderingGroupId).dispatch(subMesh, mesh, material); } /** * Overrides the default sort function applied in the rendering group to prepare the meshes. * This allowed control for front to back rendering or reversely depending of the special needs. * * @param renderingGroupId The rendering group id corresponding to its index * @param opaqueSortCompareFn The opaque queue comparison function use to sort. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort. * @param transparentSortCompareFn The transparent queue comparison function use to sort. */ setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) { this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn; this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn; this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn; if (this._renderingGroups[renderingGroupId]) { const group = this._renderingGroups[renderingGroupId]; group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId]; group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId]; group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId]; } } /** * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. * * @param renderingGroupId The rendering group id corresponding to its index * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. * @param depth Automatically clears depth between groups if true and autoClear is true. * @param stencil Automatically clears stencil between groups if true and autoClear is true. */ setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) { this._autoClearDepthStencil[renderingGroupId] = { autoClear: autoClearDepthStencil, depth, stencil }; } /** * Gets the current auto clear configuration for one rendering group of the rendering * manager. * @param index the rendering group index to get the information for * @returns The auto clear setup for the requested rendering group */ getAutoClearDepthStencilSetup(index) { return this._autoClearDepthStencil[index]; } }; RenderingManager.MAX_RENDERINGGROUPS = 4; RenderingManager.MIN_RENDERINGGROUPS = 0; RenderingManager.AUTOCLEAR = true; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/lightConstants.js var LightConstants; var init_lightConstants = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/lightConstants.js"() { LightConstants = class { static { __name(this, "LightConstants"); } /** * Sort function to order lights for rendering. * @param a First Light object to compare to second. * @param b Second Light object to compare first. * @returns -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b. */ static CompareLightsPriority(a, b) { if (a.shadowEnabled !== b.shadowEnabled) { return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0); } return b.renderPriority - a.renderPriority; } }; LightConstants.FALLOFF_DEFAULT = 0; LightConstants.FALLOFF_PHYSICAL = 1; LightConstants.FALLOFF_GLTF = 2; LightConstants.FALLOFF_STANDARD = 3; LightConstants.LIGHTMAP_DEFAULT = 0; LightConstants.LIGHTMAP_SPECULAR = 1; LightConstants.LIGHTMAP_SHADOWSONLY = 2; LightConstants.INTENSITYMODE_AUTOMATIC = 0; LightConstants.INTENSITYMODE_LUMINOUSPOWER = 1; LightConstants.INTENSITYMODE_LUMINOUSINTENSITY = 2; LightConstants.INTENSITYMODE_ILLUMINANCE = 3; LightConstants.INTENSITYMODE_LUMINANCE = 4; LightConstants.LIGHTTYPEID_POINTLIGHT = 0; LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT = 1; LightConstants.LIGHTTYPEID_SPOTLIGHT = 2; LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT = 3; LightConstants.LIGHTTYPEID_RECT_AREALIGHT = 4; LightConstants.LIGHTTYPEID_CLUSTERED_CONTAINER = 5; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/objectRenderer.js var ObjectRenderer; var init_objectRenderer = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/objectRenderer.js"() { init_observable(); init_renderingManager(); init_arrayTools(); init_timingTools(); init_logger(); init_smartArray(); init_lightConstants(); ObjectRenderer = class _ObjectRenderer { static { __name(this, "ObjectRenderer"); } /** * Use this list to define the list of mesh you want to render. */ get renderList() { return this._renderList; } set renderList(value) { if (this._renderList === value) { return; } if (this._unObserveRenderList) { this._unObserveRenderList(); this._unObserveRenderList = null; } if (value) { this._unObserveRenderList = _ObserveArray(value, this._renderListHasChanged); } this._renderList = value; } /** * If true, the object renderer will render all objects without any image processing applied. * If false (default value), the renderer will use the current setting of the scene's image processing configuration. */ get disableImageProcessing() { return this._disableImageProcessing; } set disableImageProcessing(value) { if (value === this._disableImageProcessing) { return; } this._disableImageProcessing = value; this._scene.markAllMaterialsAsDirty(64); } /** * Specifies to disable depth pre-pass if true (default: false) */ get disableDepthPrePass() { return this._disableDepthPrePass; } set disableDepthPrePass(value) { this._disableDepthPrePass = value; this._renderingManager.disableDepthPrePass = value; } /** * Friendly name of the object renderer */ get name() { return this._name; } set name(value) { if (this._name === value) { return; } this._name = value; if (this._sceneUBOs) { for (let i = 0; i < this._sceneUBOs.length; ++i) { this._sceneUBOs[i].name = `Scene ubo #${i} for ${this.name}`; } } if (!this._scene) { return; } for (let i = 0; i < this._renderPassIds.length; ++i) { const renderPassId = this._renderPassIds[i]; this._engine._renderPassNames[renderPassId] = `${this._name}#${i}`; } } /** * Gets the render pass ids used by the object renderer. */ get renderPassIds() { return this._renderPassIds; } /** * Gets the current value of the refreshId counter */ get currentRefreshId() { return this._currentRefreshId; } /** * Gets the array of active meshes * @returns an array of AbstractMesh */ getActiveMeshes() { return this._activeMeshes; } /** * Sets a specific material to be used to render a mesh/a list of meshes with this object renderer * @param mesh mesh or array of meshes * @param material material or array of materials to use for this render pass. If undefined is passed, no specific material will be used but the regular material instead (mesh.material). It's possible to provide an array of materials to use a different material for each rendering pass. */ setMaterialForRendering(mesh, material) { let meshes; if (!Array.isArray(mesh)) { meshes = [mesh]; } else { meshes = mesh; } for (let j = 0; j < meshes.length; ++j) { for (let i = 0; i < this.options.numPasses; ++i) { let mesh2 = meshes[j]; if (meshes[j].isAnInstance) { mesh2 = meshes[j].sourceMesh; } mesh2.setMaterialForRenderPass(this._renderPassIds[i], material !== void 0 ? Array.isArray(material) ? material[i] : material : void 0); } } } /** @internal */ _freezeActiveMeshes(freezeMeshes) { this._freezeActiveMeshesCancel = _RetryWithInterval(() => { return this._checkReadiness(); }, () => { this._freezeActiveMeshesCancel = null; if (freezeMeshes) { for (let index = 0; index < this._activeMeshes.length; index++) { this._activeMeshes.data[index]._freeze(); } } this._prepareRenderingManager(0, true); this._isFrozen = true; }, (err, isTimeout) => { this._freezeActiveMeshesCancel = null; if (!isTimeout) { Logger.Error("ObjectRenderer: An unexpected error occurred while waiting for the renderer to be ready."); if (err) { Logger.Error(err); if (err.stack) { Logger.Error(err.stack); } } } else { Logger.Error(`ObjectRenderer: Timeout while waiting for the renderer to be ready.`); if (err) { Logger.Error(err); } } }); } /** @internal */ _unfreezeActiveMeshes() { this._freezeActiveMeshesCancel?.(); this._freezeActiveMeshesCancel = null; for (let index = 0; index < this._activeMeshes.length; index++) { this._activeMeshes.data[index]._unFreeze(); } this._isFrozen = false; } /** * Instantiates an object renderer. * @param name The friendly name of the object renderer * @param scene The scene the renderer belongs to * @param options The options used to create the renderer (optional) */ constructor(name260, scene, options) { this._unObserveRenderList = null; this._renderListHasChanged = (_functionName, previousLength) => { const newLength = this._renderList ? this._renderList.length : 0; if (previousLength === 0 && newLength > 0 || newLength === 0) { for (const mesh of this._scene.meshes) { mesh._markSubMeshesAsLightDirty(); } } }; this.particleSystemList = null; this.getCustomRenderList = null; this.renderParticles = true; this.renderSprites = false; this.forceLayerMaskCheck = false; this.enableBoundingBoxRendering = false; this.enableOutlineRendering = true; this._disableImageProcessing = false; this.dontSetTransformationMatrix = false; this._disableDepthPrePass = false; this.onBeforeRenderObservable = new Observable(); this.onAfterRenderObservable = new Observable(); this.onBeforeRenderingManagerRenderObservable = new Observable(); this.onAfterRenderingManagerRenderObservable = new Observable(); this.onInitRenderingObservable = new Observable(); this.onFinishRenderingObservable = new Observable(); this.onFastPathRenderObservable = new Observable(); this._currentRefreshId = -1; this._refreshRate = 1; this._currentApplyByPostProcessSetting = false; this._activeMeshes = new SmartArray(256); this._activeBoundingBoxes = new SmartArray(32); this._currentFrameId = -1; this._currentSceneUBOIndex = 0; this._isFrozen = false; this._freezeActiveMeshesCancel = null; this._currentSceneCamera = null; this.name = name260; this._scene = scene; this._engine = this._scene.getEngine(); this._useUBO = this._engine.supportsUniformBuffers; if (this._useUBO) { this._sceneUBOs = []; this._createSceneUBO(); } this.renderList = []; this._renderPassIds = []; this.options = { numPasses: 1, doNotChangeAspectRatio: true, enableClusteredLights: false, ...options }; this._createRenderPassId(); this.renderPassId = this._renderPassIds[0]; this._renderingManager = new RenderingManager(scene); this._renderingManager._useSceneAutoClearSetup = true; if (this.options.enableClusteredLights) { this.onInitRenderingObservable.add(() => { for (const light of this._scene.lights) { if (light.getTypeID() === LightConstants.LIGHTTYPEID_CLUSTERED_CONTAINER && light.isSupported) { light._updateBatches(this.activeCamera).render(); } } }); } this._scene.addObjectRenderer(this); } _releaseRenderPassId() { for (let i = 0; i < this.options.numPasses; ++i) { this._engine.releaseRenderPassId(this._renderPassIds[i]); } this._renderPassIds.length = 0; } _createRenderPassId() { this._releaseRenderPassId(); for (let i = 0; i < this.options.numPasses; ++i) { this._renderPassIds[i] = this._engine.createRenderPassId(`${this.name}#${i}`); } } _createSceneUBO() { const index = this._sceneUBOs.length; this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene ubo #${index} for ${this.name}`, false)); } _getSceneUBO() { if (this._currentFrameId !== this._engine.frameId) { this._currentSceneUBOIndex = 0; this._currentFrameId = this._engine.frameId; } if (this._currentSceneUBOIndex >= this._sceneUBOs.length) { this._createSceneUBO(); } const ubo = this._sceneUBOs[this._currentSceneUBOIndex++]; ubo.unbindEffect(); return ubo; } /** * Resets the refresh counter of the renderer and start back from scratch. * Could be useful to re-render if it is setup to render only once. */ resetRefreshCounter() { this._currentRefreshId = -1; } /** * Defines the refresh rate of the rendering or the rendering frequency. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on... */ get refreshRate() { return this._refreshRate; } set refreshRate(value) { this._refreshRate = value; this.resetRefreshCounter(); } /** * Indicates if the renderer should render the current frame. * The output is based on the specified refresh rate. * @returns true if the renderer should render the current frame */ shouldRender() { if (this._currentRefreshId === -1) { this._currentRefreshId = 1; return true; } if (this.refreshRate === this._currentRefreshId) { this._currentRefreshId = 1; return true; } this._currentRefreshId++; return false; } /** * This function will check if the renderer is ready to render (textures are loaded, shaders are compiled) * @param viewportWidth defines the width of the viewport * @param viewportHeight defines the height of the viewport * @returns true if all required resources are ready */ isReadyForRendering(viewportWidth, viewportHeight) { this.prepareRenderList(); this.initRender(viewportWidth, viewportHeight); const isReady = this._checkReadiness(); this.finishRender(); return isReady; } /** * Makes sure the list of meshes is ready to be rendered * You should call this function before "initRender", but if you know the render list is ok, you may call "initRender" directly */ prepareRenderList() { const scene = this._scene; if (this._waitingRenderList) { if (!this.renderListPredicate) { this.renderList = []; for (let index = 0; index < this._waitingRenderList.length; index++) { const id = this._waitingRenderList[index]; const mesh = scene.getMeshById(id); if (mesh) { this.renderList.push(mesh); } } } this._waitingRenderList = void 0; } if (this.renderListPredicate) { if (this.renderList) { this.renderList.length = 0; } else { this.renderList = []; } const sceneMeshes = this._scene.meshes; for (let index = 0; index < sceneMeshes.length; index++) { const mesh = sceneMeshes[index]; if (this.renderListPredicate(mesh)) { this.renderList.push(mesh); } } } this._currentApplyByPostProcessSetting = this._scene.imageProcessingConfiguration.applyByPostProcess; if (this._disableImageProcessing) { this._scene.imageProcessingConfiguration._applyByPostProcess = this._disableImageProcessing; } } /** * This method makes sure everything is setup before "render" can be called * @param viewportWidth Width of the viewport to render to * @param viewportHeight Height of the viewport to render to */ initRender(viewportWidth, viewportHeight) { const camera = this.activeCamera ?? this._scene.activeCamera; this._currentSceneCamera = this._scene.activeCamera; if (this._useUBO) { this._currentSceneUBO = this._scene.getSceneUniformBuffer(); this._currentSceneUBO.unbindEffect(); this._scene.setSceneUniformBuffer(this._getSceneUBO()); } this.onInitRenderingObservable.notifyObservers(this); if (camera) { if (!this.dontSetTransformationMatrix) { this._scene.setTransformMatrix(camera.getViewMatrix(), camera.getProjectionMatrix(true)); } this._scene.activeCamera = camera; this._engine.setViewport(camera.rigParent ? camera.rigParent.viewport : camera.viewport, viewportWidth, viewportHeight); } if (this._useUBO) { this._scene.finalizeSceneUbo(); } this._defaultRenderListPrepared = false; } /** * This method must be called after the "render" call(s), to complete the rendering process. */ finishRender() { const scene = this._scene; if (this._useUBO) { this._scene.setSceneUniformBuffer(this._currentSceneUBO); } if (this._disableImageProcessing) { scene.imageProcessingConfiguration._applyByPostProcess = this._currentApplyByPostProcessSetting; } scene.activeCamera = this._currentSceneCamera; if (this._currentSceneCamera) { if (this.activeCamera && this.activeCamera !== scene.activeCamera) { scene.setTransformMatrix(this._currentSceneCamera.getViewMatrix(), this._currentSceneCamera.getProjectionMatrix(true)); } this._engine.setViewport(this._currentSceneCamera.viewport); } scene.resetCachedMaterial(); this.onFinishRenderingObservable.notifyObservers(this); } /** * Renders all the objects (meshes, particles systems, sprites) to the currently bound render target texture. * @param passIndex defines the pass index to use (default: 0) * @param skipOnAfterRenderObservable defines a flag to skip raising the onAfterRenderObservable */ render(passIndex = 0, skipOnAfterRenderObservable = false) { const currentRenderPassId = this._engine.currentRenderPassId; this._engine.currentRenderPassId = this._renderPassIds[passIndex]; this.onBeforeRenderObservable.notifyObservers(passIndex); const fastPath = this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1; if (!fastPath) { const currentRenderList = this._prepareRenderingManager(passIndex); const outlineRenderer = this._scene.getOutlineRenderer?.(); const outlineRendererIsEnabled = outlineRenderer?.enabled; if (outlineRenderer) { outlineRenderer.enabled = this.enableOutlineRendering; } this.onBeforeRenderingManagerRenderObservable.notifyObservers(passIndex); this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites); this.onAfterRenderingManagerRenderObservable.notifyObservers(passIndex); if (outlineRenderer) { outlineRenderer.enabled = outlineRendererIsEnabled; } } else { this.onFastPathRenderObservable.notifyObservers(passIndex); } if (!skipOnAfterRenderObservable) { this.onAfterRenderObservable.notifyObservers(passIndex); } this._engine.currentRenderPassId = currentRenderPassId; } /** @internal */ _checkReadiness() { const scene = this._scene; const currentRenderPassId = this._engine.currentRenderPassId; let returnValue = true; if (!scene.getViewMatrix()) { scene.updateTransformMatrix(); } const numPasses = this.options.numPasses; for (let passIndex = 0; passIndex < numPasses && returnValue; passIndex++) { let currentRenderList = null; const defaultRenderList = this.renderList ? this.renderList : scene.frameGraph ? scene.meshes : scene.getActiveMeshes().data; const defaultRenderListLength = this.renderList ? this.renderList.length : scene.frameGraph ? scene.meshes.length : scene.getActiveMeshes().length; this._engine.currentRenderPassId = this._renderPassIds[passIndex]; this.onBeforeRenderObservable.notifyObservers(passIndex); if (this.getCustomRenderList) { currentRenderList = this.getCustomRenderList(passIndex, defaultRenderList, defaultRenderListLength); } if (!currentRenderList) { currentRenderList = defaultRenderList; } if (!this.options.doNotChangeAspectRatio) { scene.updateTransformMatrix(true); } for (let i = 0; i < currentRenderList.length && returnValue; ++i) { const mesh = currentRenderList[i]; if (!mesh.isEnabled() || mesh.isBlocked || !mesh.isVisible || !mesh.subMeshes) { continue; } if (this.customIsReadyFunction) { if (!this.customIsReadyFunction(mesh, this.refreshRate, true)) { returnValue = false; continue; } } else if (!mesh.isReady(true)) { returnValue = false; continue; } } this.onAfterRenderObservable.notifyObservers(passIndex); if (numPasses > 1) { scene.incrementRenderId(); scene.resetCachedMaterial(); } } const particleSystems = this.particleSystemList || scene.particleSystems; for (const particleSystem of particleSystems) { if (!particleSystem.isReady()) { returnValue = false; } } this._engine.currentRenderPassId = currentRenderPassId; return returnValue; } _prepareRenderingManager(passIndex = 0, winterIsComing = false) { const scene = this._scene; let currentRenderList = null; let currentRenderListLength = 0; let checkLayerMask = false; const defaultRenderList = this.renderList ? this.renderList : scene.frameGraph ? scene.meshes : scene.getActiveMeshes().data; const defaultRenderListLength = this.renderList ? this.renderList.length : scene.frameGraph ? scene.meshes.length : scene.getActiveMeshes().length; if (this.getCustomRenderList) { currentRenderList = this.getCustomRenderList(passIndex, defaultRenderList, defaultRenderListLength); } if (!currentRenderList) { if (this._defaultRenderListPrepared && !winterIsComing) { return defaultRenderList; } this._defaultRenderListPrepared = true; currentRenderList = defaultRenderList; currentRenderListLength = defaultRenderListLength; checkLayerMask = !this.renderList || this.forceLayerMaskCheck; } else { currentRenderListLength = currentRenderList.length; checkLayerMask = this.forceLayerMaskCheck; } const camera = scene.activeCamera; const cameraForLOD = this.cameraForLOD ?? camera; const boundingBoxRenderer = scene.getBoundingBoxRenderer?.(); if (scene._activeMeshesFrozen && this._isFrozen) { this._renderingManager.resetSprites(); if (this.enableBoundingBoxRendering && boundingBoxRenderer) { boundingBoxRenderer.reset(); for (let i = 0; i < this._activeBoundingBoxes.length; i++) { const boundingBox = this._activeBoundingBoxes.data[i]; boundingBoxRenderer.renderList.push(boundingBox); } } return currentRenderList; } this._renderingManager.reset(); this._activeMeshes.reset(); this._activeBoundingBoxes.reset(); boundingBoxRenderer && boundingBoxRenderer.reset(); const sceneRenderId = scene.getRenderId(); const currentFrameId = scene.getFrameId(); for (let meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) { const mesh = currentRenderList[meshIndex]; if (mesh && !mesh.isBlocked) { if (this.customIsReadyFunction) { if (!this.customIsReadyFunction(mesh, this.refreshRate, false)) { this.resetRefreshCounter(); continue; } } else if (!mesh.isReady(this.refreshRate === 0)) { this.resetRefreshCounter(); continue; } let meshToRender = null; if (cameraForLOD) { const meshToRenderAndFrameId = mesh._internalAbstractMeshDataInfo._currentLOD.get(cameraForLOD); if (!meshToRenderAndFrameId || meshToRenderAndFrameId[1] !== currentFrameId) { meshToRender = scene.customLODSelector ? scene.customLODSelector(mesh, cameraForLOD) : mesh.getLOD(cameraForLOD); if (!meshToRenderAndFrameId) { mesh._internalAbstractMeshDataInfo._currentLOD.set(cameraForLOD, [meshToRender, currentFrameId]); } else { meshToRenderAndFrameId[0] = meshToRender; meshToRenderAndFrameId[1] = currentFrameId; } } else { meshToRender = meshToRenderAndFrameId[0]; } } else { meshToRender = mesh; } if (!meshToRender) { continue; } if (meshToRender !== mesh && meshToRender.billboardMode !== 0) { meshToRender.computeWorldMatrix(); } meshToRender._preActivateForIntermediateRendering(sceneRenderId); let isMasked; if (checkLayerMask && camera) { isMasked = (mesh.layerMask & camera.layerMask) === 0; } else { isMasked = false; } if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) { this._activeMeshes.push(mesh); meshToRender._internalAbstractMeshDataInfo._wasActiveLastFrame = true; if (meshToRender !== mesh) { meshToRender._activate(sceneRenderId, true); } this.enableBoundingBoxRendering && boundingBoxRenderer && boundingBoxRenderer._preActiveMesh(mesh); if (mesh._activate(sceneRenderId, true) && mesh.subMeshes.length) { if (!mesh.isAnInstance) { meshToRender._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = false; } else { if (mesh._internalAbstractMeshDataInfo._actAsRegularMesh) { meshToRender = mesh; } } meshToRender._internalAbstractMeshDataInfo._isActiveIntermediate = true; scene._prepareSkeleton(meshToRender); for (let subIndex = 0; subIndex < meshToRender.subMeshes.length; subIndex++) { const subMesh = meshToRender.subMeshes[subIndex]; this.enableBoundingBoxRendering && boundingBoxRenderer && boundingBoxRenderer._evaluateSubMesh(mesh, subMesh); this._renderingManager.dispatch(subMesh, meshToRender); } } mesh._postActivate(); } } } if (this.enableBoundingBoxRendering && boundingBoxRenderer && winterIsComing) { for (let i = 0; i < boundingBoxRenderer.renderList.length; i++) { const boundingBox = boundingBoxRenderer.renderList.data[i]; this._activeBoundingBoxes.push(boundingBox); } } if (this._scene.particlesEnabled) { this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene); const particleSystems = this.particleSystemList || scene.particleSystems; for (let particleIndex = 0; particleIndex < particleSystems.length; particleIndex++) { const particleSystem = particleSystems[particleIndex]; const emitter = particleSystem.emitter; if (!particleSystem.isStarted() || !emitter || emitter.position && !emitter.isEnabled()) { continue; } this._renderingManager.dispatchParticles(particleSystem); } this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene); } return currentRenderList; } /** * Gets the rendering manager */ get renderingManager() { return this._renderingManager; } /** * Overrides the default sort function applied in the rendering group to prepare the meshes. * This allowed control for front to back rendering or reversely depending of the special needs. * * @param renderingGroupId The rendering group id corresponding to its index * @param opaqueSortCompareFn The opaque queue comparison function use to sort. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort. * @param transparentSortCompareFn The transparent queue comparison function use to sort. */ setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) { this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn); } /** * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. * * @param renderingGroupId The rendering group id corresponding to its index * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. * @param depth Automatically clears depth between groups if true and autoClear is true. * @param stencil Automatically clears stencil between groups if true and autoClear is true. */ setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) { this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil); this._renderingManager._useSceneAutoClearSetup = false; } /** * Clones the renderer. * @returns the cloned renderer */ clone() { const newRenderer = new _ObjectRenderer(this.name, this._scene, this.options); if (this.renderList) { newRenderer.renderList = this.renderList.slice(0); } return newRenderer; } /** * Dispose the renderer and release its associated resources. */ dispose() { const renderList = this.renderList ? this.renderList : this._scene.getActiveMeshes().data; const renderListLength = this.renderList ? this.renderList.length : this._scene.getActiveMeshes().length; for (let i = 0; i < renderListLength; i++) { const mesh = renderList[i]; if (mesh && mesh.getMaterialForRenderPass(this.renderPassId) !== void 0) { mesh.setMaterialForRenderPass(this.renderPassId, void 0); } } this.onInitRenderingObservable.clear(); this.onFinishRenderingObservable.clear(); this.onBeforeRenderObservable.clear(); this.onAfterRenderObservable.clear(); this.onBeforeRenderingManagerRenderObservable.clear(); this.onAfterRenderingManagerRenderObservable.clear(); this.onFastPathRenderObservable.clear(); this._releaseRenderPassId(); this.renderList = null; if (this._sceneUBOs) { for (const ubo of this._sceneUBOs) { ubo.dispose(); } } this._sceneUBOs = void 0; this._scene.removeObjectRenderer(this); } /** @internal */ _rebuild() { if (this.refreshRate === _ObjectRenderer.REFRESHRATE_RENDER_ONCE) { this.refreshRate = _ObjectRenderer.REFRESHRATE_RENDER_ONCE; } } /** * Clear the info related to rendering groups preventing retention point in material dispose. */ freeRenderingGroups() { if (this._renderingManager) { this._renderingManager.freeRenderingGroups(); } } }; ObjectRenderer.REFRESHRATE_RENDER_ONCE = 0; ObjectRenderer.REFRESHRATE_RENDER_ONEVERYFRAME = 1; ObjectRenderer.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/renderTargetTexture.js var RenderTargetTexture; var init_renderTargetTexture = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/renderTargetTexture.js"() { init_observable(); init_math_vector(); init_texture(); init_postProcessManager(); init_tools_functions(); init_effect(); init_logger(); init_objectRenderer(); Effect.prototype.setDepthStencilTexture = function(channel, texture) { this._engine.setDepthStencilTexture(this._samplers[channel], this._uniforms[channel], texture, channel); }; RenderTargetTexture = class _RenderTargetTexture extends Texture { static { __name(this, "RenderTargetTexture"); } /** * Use this predicate to dynamically define the list of mesh you want to render. * If set, the renderList property will be overwritten. */ get renderListPredicate() { return this._objectRenderer.renderListPredicate; } set renderListPredicate(value) { this._objectRenderer.renderListPredicate = value; } /** * Use this list to define the list of mesh you want to render. */ get renderList() { return this._objectRenderer.renderList; } set renderList(value) { this._objectRenderer.renderList = value; } /** * Define the list of particle systems to render in the texture. If not provided, will render all the particle systems of the scene. * Note that the particle systems are rendered only if renderParticles is set to true. */ get particleSystemList() { return this._objectRenderer.particleSystemList; } set particleSystemList(value) { this._objectRenderer.particleSystemList = value; } /** * Use this function to overload the renderList array at rendering time. * Return null to render with the current renderList, else return the list of meshes to use for rendering. * For 2DArray RTT, layerOrFace is the index of the layer that is going to be rendered, else it is the faceIndex of * the cube (if the RTT is a cube, else layerOrFace=0). * The renderList passed to the function is the current render list (the one that will be used if the function returns null). * The length of this list is passed through renderListLength: don't use renderList.length directly because the array can * hold dummy elements! */ get getCustomRenderList() { return this._objectRenderer.getCustomRenderList; } set getCustomRenderList(value) { this._objectRenderer.getCustomRenderList = value; } /** * Define if particles should be rendered in your texture (default: true). */ get renderParticles() { return this._objectRenderer.renderParticles; } set renderParticles(value) { this._objectRenderer.renderParticles = value; } /** * Define if sprites should be rendered in your texture (default: false). */ get renderSprites() { return this._objectRenderer.renderSprites; } set renderSprites(value) { this._objectRenderer.renderSprites = value; } /** * Define if bounding box rendering should be enabled (still subject to Mesh.showBoundingBox or scene.forceShowBoundingBoxes). (Default: false). */ get enableBoundingBoxRendering() { return this._objectRenderer.enableBoundingBoxRendering; } set enableBoundingBoxRendering(value) { this._objectRenderer.enableBoundingBoxRendering = value; } /** * Define if outline/overlay rendering should be enabled (still subject to Mesh.renderOutline/Mesh.renderOverlay). (Default: true). */ get enableOutlineRendering() { return this._objectRenderer.enableOutlineRendering; } set enableOutlineRendering(value) { this._objectRenderer.enableOutlineRendering = value; } /** * Force checking the layerMask property even if a custom list of meshes is provided (ie. if renderList is not undefined) (default: false). */ get forceLayerMaskCheck() { return this._objectRenderer.forceLayerMaskCheck; } set forceLayerMaskCheck(value) { this._objectRenderer.forceLayerMaskCheck = value; } /** * Define the camera used to render the texture. */ get activeCamera() { return this._objectRenderer.activeCamera; } set activeCamera(value) { this._objectRenderer.activeCamera = value; } /** * Define the camera used to calculate the LOD of the objects. * If not defined, activeCamera will be used. If not defined nor activeCamera, scene's active camera will be used. */ get cameraForLOD() { return this._objectRenderer.cameraForLOD; } set cameraForLOD(value) { this._objectRenderer.cameraForLOD = value; } /** * If true, the renderer will render all objects without any image processing applied. * If false (default value), the renderer will use the current setting of the scene's image processing configuration. */ get disableImageProcessing() { return this._objectRenderer.disableImageProcessing; } set disableImageProcessing(value) { this._objectRenderer.disableImageProcessing = value; } /** * Override the mesh isReady function with your own one. */ get customIsReadyFunction() { return this._objectRenderer.customIsReadyFunction; } set customIsReadyFunction(value) { this._objectRenderer.customIsReadyFunction = value; } /** * Override the render function of the texture with your own one. */ get customRenderFunction() { return this._objectRenderer.customRenderFunction; } set customRenderFunction(value) { this._objectRenderer.customRenderFunction = value; } /** * Post-processes for this render target */ get postProcesses() { return this._postProcesses; } get _prePassEnabled() { return !!this._prePassRenderTarget && this._prePassRenderTarget.enabled; } /** * Set a after unbind callback in the texture. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended. */ set onAfterUnbind(callback) { if (this._onAfterUnbindObserver) { this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver); } this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback); } /** * An event triggered before rendering the texture */ get onBeforeRenderObservable() { return this._objectRenderer.onBeforeRenderObservable; } /** * Set a before render callback in the texture. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended. */ set onBeforeRender(callback) { if (this._onBeforeRenderObserver) { this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); } this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); } /** * An event triggered after rendering the texture */ get onAfterRenderObservable() { return this._objectRenderer.onAfterRenderObservable; } /** * Set a after render callback in the texture. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended. */ set onAfterRender(callback) { if (this._onAfterRenderObserver) { this.onAfterRenderObservable.remove(this._onAfterRenderObserver); } this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); } /** * Set a clear callback in the texture. * This has been kept for backward compatibility and use of onClearObservable is recommended. */ set onClear(callback) { if (this._onClearObserver) { this.onClearObservable.remove(this._onClearObserver); } this._onClearObserver = this.onClearObservable.add(callback); } /** @internal */ get _waitingRenderList() { return this._objectRenderer._waitingRenderList; } /** @internal */ set _waitingRenderList(value) { this._objectRenderer._waitingRenderList = value; } /** * Current render pass id of the render target texture. Note it can change over the rendering as there's a separate id for each face of a cube / each layer of an array layer! */ get renderPassId() { return this._objectRenderer.renderPassId; } /** * Gets the render pass ids used by the render target texture. For a single render target the array length will be 1, for a cube texture it will be 6 and for * a 2D texture array it will return an array of ids the size of the 2D texture array */ get renderPassIds() { return this._objectRenderer.renderPassIds; } /** * Gets the current value of the refreshId counter */ get currentRefreshId() { return this._objectRenderer.currentRefreshId; } /** * Sets a specific material to be used to render a mesh/a list of meshes in this render target texture * @param mesh mesh or array of meshes * @param material material or array of materials to use for this render pass. If undefined is passed, no specific material will be used but the regular material instead (mesh.material). It's possible to provide an array of materials to use a different material for each rendering in the case of a cube texture (6 rendering) and a 2D texture array (as many rendering as the length of the array) */ setMaterialForRendering(mesh, material) { this._objectRenderer.setMaterialForRendering(mesh, material); } /** * Define if the texture has multiple draw buffers or if false a single draw buffer. */ get isMulti() { return this._renderTarget?.isMulti ?? false; } /** * Gets render target creation options that were used. */ get renderTargetOptions() { return this._renderTargetOptions; } /** * Gets the render target wrapper associated with this render target */ get renderTarget() { return this._renderTarget; } _onRatioRescale() { if (this._sizeRatio) { this.resize(this._initialSizeParameter); } } /** * Gets or sets the size of the bounding box associated with the texture (when in cube mode) * When defined, the cubemap will switch to local mode * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity * @example https://www.babylonjs-playground.com/#RNASML */ set boundingBoxSize(value) { if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) { return; } this._boundingBoxSize = value; const scene = this.getScene(); if (scene) { scene.markAllMaterialsAsDirty(1); } } get boundingBoxSize() { return this._boundingBoxSize; } /** * In case the RTT has been created with a depth texture, get the associated * depth texture. * Otherwise, return null. */ get depthStencilTexture() { return this._renderTarget?._depthStencilTexture ?? null; } /** @internal */ constructor(name260, size, scene, generateMipMaps = false, doNotChangeAspectRatio = true, type = 0, isCube = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, generateDepthBuffer = true, generateStencilBuffer = false, isMulti = false, format = 5, delayAllocation = false, samples, creationFlags, noColorAttachment = false, useSRGBBuffer = false) { let colorAttachment = void 0; let gammaSpace = true; let existingObjectRenderer = void 0; let enableClusteredLights = false; if (typeof generateMipMaps === "object") { const options = generateMipMaps; generateMipMaps = !!options.generateMipMaps; doNotChangeAspectRatio = options.doNotChangeAspectRatio ?? true; type = options.type ?? 0; isCube = !!options.isCube; samplingMode = options.samplingMode ?? Texture.TRILINEAR_SAMPLINGMODE; generateDepthBuffer = options.generateDepthBuffer ?? true; generateStencilBuffer = !!options.generateStencilBuffer; isMulti = !!options.isMulti; format = options.format ?? 5; delayAllocation = !!options.delayAllocation; samples = options.samples; creationFlags = options.creationFlags; noColorAttachment = !!options.noColorAttachment; useSRGBBuffer = !!options.useSRGBBuffer; colorAttachment = options.colorAttachment; gammaSpace = options.gammaSpace ?? gammaSpace; existingObjectRenderer = options.existingObjectRenderer; enableClusteredLights = !!options.enableClusteredLights; } super(null, scene, !generateMipMaps, void 0, samplingMode, void 0, void 0, void 0, void 0, format); this.ignoreCameraViewport = false; this.onBeforeBindObservable = new Observable(); this.onAfterUnbindObservable = new Observable(); this.onClearObservable = new Observable(); this.onResizeObservable = new Observable(); this._cleared = false; this.skipInitialClear = false; this._samples = 1; this._canRescale = true; this._renderTarget = null; this._dontDisposeObjectRenderer = false; this.boundingBoxPosition = Vector3.Zero(); this._disableEngineStages = false; this._dumpToolsLoading = false; scene = this.getScene(); if (!scene) { return; } const engine = this.getScene().getEngine(); this._gammaSpace = gammaSpace; this._coordinatesMode = Texture.PROJECTION_MODE; this.name = name260; this.isRenderTarget = true; this._initialSizeParameter = size; this._dontDisposeObjectRenderer = !!existingObjectRenderer; this._processSizeParameter(size); this._objectRenderer = existingObjectRenderer ?? new ObjectRenderer(name260, scene, { numPasses: isCube ? 6 : this.getRenderLayers() || 1, doNotChangeAspectRatio, enableClusteredLights }); this._onBeforeRenderingManagerRenderObserver = this._objectRenderer.onBeforeRenderingManagerRenderObservable.add(() => { if (!this._disableEngineStages) { for (const step of this._scene._beforeRenderTargetClearStage) { step.action(this, this._currentFaceIndex, this._currentLayer); } } if (this.onClearObservable.hasObservers()) { this.onClearObservable.notifyObservers(engine); } else if (!this.skipInitialClear) { engine.clear(this.clearColor || this._scene.clearColor, true, true, true); } if (!this._doNotChangeAspectRatio) { this._scene.updateTransformMatrix(true); } if (!this._disableEngineStages) { for (const step of this._scene._beforeRenderTargetDrawStage) { step.action(this, this._currentFaceIndex, this._currentLayer); } } }); this._onAfterRenderingManagerRenderObserver = this._objectRenderer.onAfterRenderingManagerRenderObservable.add(() => { if (!this._disableEngineStages) { for (const step of this._scene._afterRenderTargetDrawStage) { step.action(this, this._currentFaceIndex, this._currentLayer); } } const saveGenerateMipMaps = this._texture?.generateMipMaps ?? false; if (this._texture) { this._texture.generateMipMaps = false; } if (this._postProcessManager) { this._postProcessManager._finalizeFrame(false, this._renderTarget ?? void 0, this._currentFaceIndex, this._postProcesses, this.ignoreCameraViewport); } else if (this._currentUseCameraPostProcess) { this._scene.postProcessManager._finalizeFrame(false, this._renderTarget ?? void 0, this._currentFaceIndex); } if (!this._disableEngineStages) { for (const step of this._scene._afterRenderTargetPostProcessStage) { step.action(this, this._currentFaceIndex, this._currentLayer); } } if (this._texture) { this._texture.generateMipMaps = saveGenerateMipMaps; } if (!this._doNotChangeAspectRatio) { this._scene.updateTransformMatrix(true); } if (this._currentDumpForDebug) { if (!this._dumpTools) { Logger.Error("dumpTools module is still being loaded. To speed up the process import dump tools directly in your project"); } else { this._dumpTools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine); } } }); this._onFastPathRenderObserver = this._objectRenderer.onFastPathRenderObservable.add(() => { if (this.onClearObservable.hasObservers()) { this.onClearObservable.notifyObservers(engine); } else { if (!this.skipInitialClear) { engine.clear(this.clearColor || this._scene.clearColor, true, true, true); } } }); this._resizeObserver = engine.onResizeObservable.add(() => { }); this._generateMipMaps = generateMipMaps ? true : false; this._doNotChangeAspectRatio = doNotChangeAspectRatio; if (isMulti) { return; } this._renderTargetOptions = { generateMipMaps, type, format: this._format ?? void 0, samplingMode: this.samplingMode, generateDepthBuffer, generateStencilBuffer, samples, creationFlags, noColorAttachment, useSRGBBuffer, colorAttachment, label: this.name }; if (this.samplingMode === Texture.NEAREST_SAMPLINGMODE) { this.wrapU = Texture.CLAMP_ADDRESSMODE; this.wrapV = Texture.CLAMP_ADDRESSMODE; } if (!delayAllocation) { if (isCube) { this._renderTarget = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions); this.coordinatesMode = Texture.INVCUBIC_MODE; this._textureMatrix = Matrix.Identity(); } else { this._renderTarget = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions); } this._texture = this._renderTarget.texture; if (samples !== void 0) { this.samples = samples; } } } /** * Creates a depth stencil texture. * This is only available in WebGL 2 or with the depth texture extension available. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode (default: 0) * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture (default: true) * @param generateStencil Specifies whether or not a stencil should be allocated in the texture (default: false) * @param samples sample count of the depth/stencil texture (default: 1) * @param format format of the depth texture (default: 14) * @param label defines the label of the texture (for debugging purpose) */ createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14, label) { this._renderTarget?.createDepthStencilTexture(comparisonFunction, bilinearFiltering, generateStencil, samples, format, label); } _processSizeParameter(size) { if (size.ratio) { this._sizeRatio = size.ratio; const engine = this._getEngine(); this._size = { width: this._bestReflectionRenderTargetDimension(engine.getRenderWidth(), this._sizeRatio), height: this._bestReflectionRenderTargetDimension(engine.getRenderHeight(), this._sizeRatio) }; } else { this._size = size; } } /** * Define the number of samples to use in case of MSAA. * It defaults to one meaning no MSAA has been enabled. */ get samples() { return this._renderTarget?.samples ?? this._samples; } set samples(value) { if (this._renderTarget) { this._samples = this._renderTarget.setSamples(value); } } /** * Adds a post process to the render target rendering passes. * @param postProcess define the post process to add */ addPostProcess(postProcess) { if (!this._postProcessManager) { const scene = this.getScene(); if (!scene) { return; } this._postProcessManager = new PostProcessManager(scene); this._postProcesses = new Array(); } this._postProcesses.push(postProcess); this._postProcesses[0].autoClear = false; } /** * Clear all the post processes attached to the render target * @param dispose define if the cleared post processes should also be disposed (false by default) */ clearPostProcesses(dispose = false) { if (!this._postProcesses) { return; } if (dispose) { for (const postProcess of this._postProcesses) { postProcess.dispose(); } } this._postProcesses = []; } /** * Remove one of the post process from the list of attached post processes to the texture * @param postProcess define the post process to remove from the list */ removePostProcess(postProcess) { if (!this._postProcesses) { return; } const index = this._postProcesses.indexOf(postProcess); if (index === -1) { return; } this._postProcesses.splice(index, 1); if (this._postProcesses.length > 0) { this._postProcesses[0].autoClear = false; } } /** * Resets the refresh counter of the texture and start bak from scratch. * Could be useful to regenerate the texture if it is setup to render only once. */ resetRefreshCounter() { this._objectRenderer.resetRefreshCounter(); } /** * Define the refresh rate of the texture or the rendering frequency. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on... */ get refreshRate() { return this._objectRenderer.refreshRate; } set refreshRate(value) { this._objectRenderer.refreshRate = value; } /** @internal */ _shouldRender() { return this._objectRenderer.shouldRender(); } /** * Gets the actual render size of the texture. * @returns the width of the render size */ getRenderSize() { return this.getRenderWidth(); } /** * Gets the actual render width of the texture. * @returns the width of the render size */ getRenderWidth() { if (this._size.width) { return this._size.width; } return this._size; } /** * Gets the actual render height of the texture. * @returns the height of the render size */ getRenderHeight() { if (this._size.width) { return this._size.height; } return this._size; } /** * Gets the actual number of layers of the texture or, in the case of a 3D texture, return the depth. * @returns the number of layers */ getRenderLayers() { const layers = this._size.layers; if (layers) { return layers; } const depth = this._size.depth; if (depth) { return depth; } return 0; } /** * Don't allow this render target texture to rescale. Mainly used to prevent rescaling by the scene optimizer. */ disableRescaling() { this._canRescale = false; } /** * Get if the texture can be rescaled or not. */ get canRescale() { return this._canRescale; } /** * Resize the texture using a ratio. * @param ratio the ratio to apply to the texture size in order to compute the new target size */ scale(ratio) { const newSize = Math.max(1, this.getRenderSize() * ratio); this.resize(newSize); } /** * Get the texture reflection matrix used to rotate/transform the reflection. * @returns the reflection matrix */ getReflectionTextureMatrix() { if (this.isCube) { return this._textureMatrix; } return super.getReflectionTextureMatrix(); } /** * Resize the texture to a new desired size. * Be careful as it will recreate all the data in the new texture. * @param size Define the new size. It can be: * - a number for squared texture, * - an object containing { width: number, height: number } * - or an object containing a ratio { ratio: number } */ resize(size) { const wasCube = this.isCube; this._renderTarget?.dispose(); this._renderTarget = null; const scene = this.getScene(); if (!scene) { return; } this._processSizeParameter(size); if (wasCube) { this._renderTarget = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions); } else { this._renderTarget = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions); } this._texture = this._renderTarget.texture; if (this._renderTargetOptions.samples !== void 0) { this.samples = this._renderTargetOptions.samples; } if (this.onResizeObservable.hasObservers()) { this.onResizeObservable.notifyObservers(this); } } /** * Renders all the objects from the render list into the texture. * @param useCameraPostProcess Define if camera post processes should be used during the rendering * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose */ render(useCameraPostProcess = false, dumpForDebug = false) { this._render(useCameraPostProcess, dumpForDebug); } /** * This function will check if the render target texture can be rendered (textures are loaded, shaders are compiled) * @returns true if all required resources are ready */ isReadyForRendering() { if (!this._dumpToolsLoading) { this._dumpToolsLoading = true; Promise.resolve().then(() => (init_dumpTools(), dumpTools_exports)).then((module2) => this._dumpTools = module2); } this._objectRenderer.prepareRenderList(); this.onBeforeBindObservable.notifyObservers(this); this._objectRenderer.initRender(this.getRenderWidth(), this.getRenderHeight()); const isReady = this._objectRenderer._checkReadiness(); this.onAfterUnbindObservable.notifyObservers(this); this._objectRenderer.finishRender(); return isReady; } _render(useCameraPostProcess = false, dumpForDebug = false) { const scene = this.getScene(); if (!scene) { return; } if (this.useCameraPostProcesses !== void 0) { useCameraPostProcess = this.useCameraPostProcesses; } this._objectRenderer.prepareRenderList(); this.onBeforeBindObservable.notifyObservers(this); this._objectRenderer.initRender(this.getRenderWidth(), this.getRenderHeight()); if ((this.is2DArray || this.is3D) && !this.isMulti) { for (let layer = 0; layer < this.getRenderLayers(); layer++) { this._renderToTarget(0, useCameraPostProcess, dumpForDebug, layer); scene.incrementRenderId(); scene.resetCachedMaterial(); } } else if (this.isCube && !this.isMulti) { for (let face = 0; face < 6; face++) { this._renderToTarget(face, useCameraPostProcess, dumpForDebug); scene.incrementRenderId(); scene.resetCachedMaterial(); } } else { this._renderToTarget(0, useCameraPostProcess, dumpForDebug); } this.onAfterUnbindObservable.notifyObservers(this); this._objectRenderer.finishRender(); } _bestReflectionRenderTargetDimension(renderDimension, scale) { const minimum = 128; const x = renderDimension * scale; const curved = NearestPOT(x + minimum * minimum / (minimum + x)); return Math.min(FloorPOT(renderDimension), curved); } /** * @internal * @param faceIndex face index to bind to if this is a cubetexture * @param layer defines the index of the texture to bind in the array */ _bindFrameBuffer(faceIndex = 0, layer = 0) { const scene = this.getScene(); if (!scene) { return; } const engine = scene.getEngine(); if (this._renderTarget) { engine.bindFramebuffer(this._renderTarget, this.isCube ? faceIndex : void 0, void 0, void 0, this.ignoreCameraViewport, 0, layer); } } _unbindFrameBuffer(engine, faceIndex) { if (!this._renderTarget) { return; } engine.unBindFramebuffer(this._renderTarget, this.isCube, () => { this.onAfterRenderObservable.notifyObservers(faceIndex); }); } /** * @internal */ _prepareFrame(scene, faceIndex, layer, useCameraPostProcess) { if (this._postProcessManager) { if (!this._prePassEnabled) { if (!this._postProcessManager._prepareFrame(this._texture, this._postProcesses)) { this._bindFrameBuffer(faceIndex, layer); } } } else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) { this._bindFrameBuffer(faceIndex, layer); } } _renderToTarget(faceIndex, useCameraPostProcess, dumpForDebug, layer = 0) { const scene = this.getScene(); if (!scene) { return; } const engine = scene.getEngine(); this._currentFaceIndex = faceIndex; this._currentLayer = layer; this._currentUseCameraPostProcess = useCameraPostProcess; this._currentDumpForDebug = dumpForDebug; this._prepareFrame(scene, faceIndex, layer, useCameraPostProcess); engine._debugPushGroup?.(`render to face #${faceIndex} layer #${layer}`, 2); this._objectRenderer.render(faceIndex + layer, true); engine._debugPopGroup?.(2); this._unbindFrameBuffer(engine, faceIndex); if (this._texture && this.isCube && faceIndex === 5) { engine.generateMipMapsForCubemap(this._texture, true); } } /** * Overrides the default sort function applied in the rendering group to prepare the meshes. * This allowed control for front to back rendering or reversely depending of the special needs. * * @param renderingGroupId The rendering group id corresponding to its index * @param opaqueSortCompareFn The opaque queue comparison function use to sort. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort. * @param transparentSortCompareFn The transparent queue comparison function use to sort. */ setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) { this._objectRenderer.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn); } /** * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. * * @param renderingGroupId The rendering group id corresponding to its index * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. */ setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil) { this._objectRenderer.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil); } /** * Clones the texture. * @returns the cloned texture */ clone() { const textureSize = this.getSize(); const newTexture = new _RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer, void 0, this._renderTargetOptions.format, void 0, this._renderTargetOptions.samples); newTexture.hasAlpha = this.hasAlpha; newTexture.level = this.level; newTexture.coordinatesMode = this.coordinatesMode; if (this.renderList) { newTexture.renderList = this.renderList.slice(0); } return newTexture; } /** * Serialize the texture to a JSON representation we can easily use in the respective Parse function. * @returns The JSON representation of the texture */ serialize() { if (!this.name) { return null; } const serializationObject = super.serialize(); serializationObject.renderTargetSize = this.getRenderSize(); serializationObject.renderList = []; if (this.renderList) { for (let index = 0; index < this.renderList.length; index++) { serializationObject.renderList.push(this.renderList[index].id); } } return serializationObject; } /** * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore */ disposeFramebufferObjects() { this._renderTarget?.dispose(true); } /** * Release and destroy the underlying lower level texture aka internalTexture. */ releaseInternalTexture() { this._renderTarget?.releaseTextures(); this._texture = null; } /** * Dispose the texture and release its associated resources. */ dispose() { this.onResizeObservable.clear(); this.onClearObservable.clear(); this.onAfterUnbindObservable.clear(); this.onBeforeBindObservable.clear(); if (this._postProcessManager) { this._postProcessManager.dispose(); this._postProcessManager = null; } if (this._prePassRenderTarget) { this._prePassRenderTarget.dispose(); } this._objectRenderer.onBeforeRenderingManagerRenderObservable.remove(this._onBeforeRenderingManagerRenderObserver); this._objectRenderer.onAfterRenderingManagerRenderObservable.remove(this._onAfterRenderingManagerRenderObserver); this._objectRenderer.onFastPathRenderObservable.remove(this._onFastPathRenderObserver); if (!this._dontDisposeObjectRenderer) { this._objectRenderer.dispose(); } this.clearPostProcesses(true); if (this._resizeObserver) { this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver); this._resizeObserver = null; } const scene = this.getScene(); if (!scene) { return; } let index = scene.customRenderTargets.indexOf(this); if (index >= 0) { scene.customRenderTargets.splice(index, 1); } for (const camera of scene.cameras) { index = camera.customRenderTargets.indexOf(this); if (index >= 0) { camera.customRenderTargets.splice(index, 1); } } this._renderTarget?.dispose(); this._renderTarget = null; this._texture = null; super.dispose(); } /** @internal */ _rebuild() { this._objectRenderer._rebuild(); if (this._postProcessManager) { this._postProcessManager._rebuild(); } } /** * Clear the info related to rendering groups preventing retention point in material dispose. */ freeRenderingGroups() { this._objectRenderer.freeRenderingGroups(); } /** * Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1) * @returns the view count */ getViewCount() { return 1; } }; RenderTargetTexture.REFRESHRATE_RENDER_ONCE = ObjectRenderer.REFRESHRATE_RENDER_ONCE; RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = ObjectRenderer.REFRESHRATE_RENDER_ONEVERYFRAME; RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = ObjectRenderer.REFRESHRATE_RENDER_ONEVERYTWOFRAMES; Texture._CreateRenderTargetTexture = (name260, renderTargetSize, scene, generateMipMaps, creationFlags) => { return new RenderTargetTexture(name260, renderTargetSize, scene, generateMipMaps); }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/postProcess.js var PostProcess; var init_postProcess = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/postProcess.js"() { init_tslib_es6(); init_smartArray(); init_observable(); init_math_vector(); init_effect(); init_decorators(); init_decorators_serialization(); init_typeStore(); init_abstractEngine(); init_tools_functions(); init_effectRenderer(); AbstractEngine.prototype.setTextureFromPostProcess = function(channel, postProcess, name260) { let postProcessInput = null; if (postProcess) { if (postProcess._forcedOutputTexture) { postProcessInput = postProcess._forcedOutputTexture; } else if (postProcess._textures.data[postProcess._currentRenderTextureInd]) { postProcessInput = postProcess._textures.data[postProcess._currentRenderTextureInd]; } } this._bindTexture(channel, postProcessInput?.texture ?? null, name260); }; AbstractEngine.prototype.setTextureFromPostProcessOutput = function(channel, postProcess, name260) { this._bindTexture(channel, postProcess?._outputTexture?.texture ?? null, name260); }; Effect.prototype.setTextureFromPostProcess = function(channel, postProcess) { this._engine.setTextureFromPostProcess(this._samplers[channel], postProcess, channel); }; Effect.prototype.setTextureFromPostProcessOutput = function(channel, postProcess) { this._engine.setTextureFromPostProcessOutput(this._samplers[channel], postProcess, channel); }; PostProcess = class _PostProcess { static { __name(this, "PostProcess"); } /** * Force all the postprocesses to compile to glsl even on WebGPU engines. * False by default. This is mostly meant for backward compatibility. */ static get ForceGLSL() { return EffectWrapper.ForceGLSL; } static set ForceGLSL(force) { EffectWrapper.ForceGLSL = force; } /** * Registers a shader code processing with a post process name. * @param postProcessName name of the post process. Use null for the fallback shader code processing. This is the shader code processing that will be used in case no specific shader code processing has been associated to a post process name * @param customShaderCodeProcessing shader code processing to associate to the post process name */ static RegisterShaderCodeProcessing(postProcessName, customShaderCodeProcessing) { EffectWrapper.RegisterShaderCodeProcessing(postProcessName, customShaderCodeProcessing); } /** Name of the PostProcess. */ get name() { return this._effectWrapper.name; } set name(value) { this._effectWrapper.name = value; } /** * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE) */ get alphaMode() { return this._effectWrapper.alphaMode; } set alphaMode(value) { this._effectWrapper.alphaMode = value; } /** * Number of sample textures (default: 1) */ get samples() { return this._samples; } set samples(n) { this._samples = Math.min(n, this._engine.getCaps().maxMSAASamples); this._textures.forEach((texture) => { texture.setSamples(this._samples); }); } /** * Gets the shader language type used to generate vertex and fragment source code. */ get shaderLanguage() { return this._shaderLanguage; } /** * Returns the fragment url or shader name used in the post process. * @returns the fragment url or name in the shader store. */ getEffectName() { return this._fragmentUrl; } /** * A function that is added to the onActivateObservable */ set onActivate(callback) { if (this._onActivateObserver) { this.onActivateObservable.remove(this._onActivateObserver); } if (callback) { this._onActivateObserver = this.onActivateObservable.add(callback); } } /** * A function that is added to the onSizeChangedObservable */ set onSizeChanged(callback) { if (this._onSizeChangedObserver) { this.onSizeChangedObservable.remove(this._onSizeChangedObserver); } this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback); } /** * A function that is added to the onApplyObservable */ set onApply(callback) { if (this._onApplyObserver) { this.onApplyObservable.remove(this._onApplyObserver); } this._onApplyObserver = this.onApplyObservable.add(callback); } /** * A function that is added to the onBeforeRenderObservable */ set onBeforeRender(callback) { if (this._onBeforeRenderObserver) { this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); } this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); } /** * A function that is added to the onAfterRenderObservable */ set onAfterRender(callback) { if (this._onAfterRenderObserver) { this.onAfterRenderObservable.remove(this._onAfterRenderObserver); } this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); } /** * The input texture for this post process and the output texture of the previous post process. When added to a pipeline the previous post process will * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process. */ get inputTexture() { return this._textures.data[this._currentRenderTextureInd]; } set inputTexture(value) { this._forcedOutputTexture = value; } /** * Since inputTexture should always be defined, if we previously manually set `inputTexture`, * the only way to unset it is to use this function to restore its internal state */ restoreDefaultInputTexture() { if (this._forcedOutputTexture) { this._forcedOutputTexture = null; this.markTextureDirty(); } } /** * Gets the camera which post process is applied to. * @returns The camera the post process is applied to. */ getCamera() { return this._camera; } /** * Gets the texel size of the postprocess. * See https://en.wikipedia.org/wiki/Texel_(graphics) */ get texelSize() { if (this._shareOutputWithPostProcess) { return this._shareOutputWithPostProcess.texelSize; } if (this._forcedOutputTexture) { this._texelSize.copyFromFloats(1 / this._forcedOutputTexture.width, 1 / this._forcedOutputTexture.height); } return this._texelSize; } /** @internal */ constructor(name260, fragmentUrl, parameters, samplers, _size, camera, samplingMode = 1, engine, reusable, defines = null, textureType = 0, vertexUrl = "postprocess", indexParameters, blockCompilation = false, textureFormat = 5, shaderLanguage, extraInitializations) { this._parentContainer = null; this.width = -1; this.height = -1; this.nodeMaterialSource = null; this._outputTexture = null; this.autoClear = true; this.forceAutoClearInAlphaMode = false; this.animations = []; this.enablePixelPerfectMode = false; this.forceFullscreenViewport = true; this.scaleMode = 1; this.alwaysForcePOT = false; this._samples = 1; this.adaptScaleToCurrentViewport = false; this._webGPUReady = false; this._reusable = false; this._renderId = 0; this.externalTextureSamplerBinding = false; this._textures = new SmartArray(2); this._textureCache = []; this._currentRenderTextureInd = 0; this._scaleRatio = new Vector2(1, 1); this._texelSize = Vector2.Zero(); this.onActivateObservable = new Observable(); this.onSizeChangedObservable = new Observable(); this.onApplyObservable = new Observable(); this.onBeforeRenderObservable = new Observable(); this.onAfterRenderObservable = new Observable(); this.onDisposeObservable = new Observable(); let size = 1; let uniformBuffers = null; let effectWrapper; if (parameters && !Array.isArray(parameters)) { const options = parameters; parameters = options.uniforms ?? null; samplers = options.samplers ?? null; size = options.size ?? 1; camera = options.camera ?? null; samplingMode = options.samplingMode ?? 1; engine = options.engine; reusable = options.reusable; defines = Array.isArray(options.defines) ? options.defines.join("\n") : options.defines ?? null; textureType = options.textureType ?? 0; vertexUrl = options.vertexUrl ?? "postprocess"; indexParameters = options.indexParameters; blockCompilation = options.blockCompilation ?? false; textureFormat = options.textureFormat ?? 5; shaderLanguage = options.shaderLanguage ?? 0; uniformBuffers = options.uniformBuffers ?? null; extraInitializations = options.extraInitializations; effectWrapper = options.effectWrapper; } else if (_size) { if (typeof _size === "number") { size = _size; } else { size = { width: _size.width, height: _size.height }; } } this._useExistingThinPostProcess = !!effectWrapper; this._effectWrapper = effectWrapper ?? new EffectWrapper({ name: name260, useShaderStore: true, useAsPostProcess: true, fragmentShader: fragmentUrl, engine: engine || camera?.getScene().getEngine(), uniforms: parameters, samplers, uniformBuffers, defines, vertexUrl, indexParameters, blockCompilation: true, shaderLanguage, extraInitializations: void 0 }); this.name = name260; this.onEffectCreatedObservable = this._effectWrapper.onEffectCreatedObservable; if (camera != null) { this._camera = camera; this._scene = camera.getScene(); camera.attachPostProcess(this); this._engine = this._scene.getEngine(); this._scene.addPostProcess(this); this.uniqueId = this._scene.getUniqueId(); } else if (engine) { this._engine = engine; this._engine.postProcesses.push(this); } this._options = size; this.renderTargetSamplingMode = samplingMode ? samplingMode : 1; this._reusable = reusable || false; this._textureType = textureType; this._textureFormat = textureFormat; this._shaderLanguage = shaderLanguage || 0; this._samplers = samplers || []; if (this._samplers.indexOf("textureSampler") === -1) { this._samplers.push("textureSampler"); } this._fragmentUrl = fragmentUrl; this._vertexUrl = vertexUrl; this._parameters = parameters || []; if (this._parameters.indexOf("scale") === -1) { this._parameters.push("scale"); } this._uniformBuffers = uniformBuffers || []; this._indexParameters = indexParameters; if (!this._useExistingThinPostProcess) { this._webGPUReady = this._shaderLanguage === 1; const importPromises = []; this._gatherImports(this._engine.isWebGPU && !_PostProcess.ForceGLSL, importPromises); this._effectWrapper._webGPUReady = this._webGPUReady; this._effectWrapper._postConstructor(blockCompilation, defines, extraInitializations, importPromises); } } _gatherImports(useWebGPU = false, list) { if (useWebGPU && this._webGPUReady) { list.push(Promise.all([Promise.resolve().then(() => (init_postprocess_vertex(), postprocess_vertex_exports))])); } else { list.push(Promise.all([Promise.resolve().then(() => (init_postprocess_vertex2(), postprocess_vertex_exports2))])); } } /** * Gets a string identifying the name of the class * @returns "PostProcess" string */ getClassName() { return "PostProcess"; } /** * Gets the engine which this post process belongs to. * @returns The engine the post process was enabled with. */ getEngine() { return this._engine; } /** * The effect that is created when initializing the post process. * @returns The created effect corresponding to the postprocess. */ getEffect() { return this._effectWrapper.drawWrapper.effect; } /** * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another. * @param postProcess The post process to share the output with. * @returns This post process. */ shareOutputWith(postProcess) { this._disposeTextures(); this._shareOutputWithPostProcess = postProcess; return this; } /** * Reverses the effect of calling shareOutputWith and returns the post process back to its original state. * This should be called if the post process that shares output with this post process is disabled/disposed. */ useOwnOutput() { if (this._textures.length == 0) { this._textures = new SmartArray(2); } this._shareOutputWithPostProcess = null; } /** * Updates the effect with the current post process compile time values and recompiles the shader. * @param defines Define statements that should be added at the beginning of the shader. (default: null) * @param uniforms Set of uniform variables that will be passed to the shader. (default: null) * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null) * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx * @param onCompiled Called when the shader has been compiled. * @param onError Called if there is an error when compiling a shader. * @param vertexUrl The url of the vertex shader to be used (default: the one given at construction time) * @param fragmentUrl The url of the fragment shader to be used (default: the one given at construction time) */ updateEffect(defines = null, uniforms = null, samplers = null, indexParameters, onCompiled, onError, vertexUrl, fragmentUrl) { this._effectWrapper.updateEffect(defines, uniforms, samplers, indexParameters, onCompiled, onError, vertexUrl, fragmentUrl); this._postProcessDefines = Array.isArray(this._effectWrapper.options.defines) ? this._effectWrapper.options.defines.join("\n") : this._effectWrapper.options.defines; } /** * The post process is reusable if it can be used multiple times within one frame. * @returns If the post process is reusable */ isReusable() { return this._reusable; } /** invalidate frameBuffer to hint the postprocess to create a depth buffer */ markTextureDirty() { this.width = -1; } _createRenderTargetTexture(textureSize, textureOptions, channel = 0) { for (let i = 0; i < this._textureCache.length; i++) { if (this._textureCache[i].texture.width === textureSize.width && this._textureCache[i].texture.height === textureSize.height && this._textureCache[i].postProcessChannel === channel && this._textureCache[i].texture._generateDepthBuffer === textureOptions.generateDepthBuffer && this._textureCache[i].texture.samples === textureOptions.samples) { return this._textureCache[i].texture; } } const tex = this._engine.createRenderTargetTexture(textureSize, textureOptions); this._textureCache.push({ texture: tex, postProcessChannel: channel, lastUsedRenderId: -1 }); return tex; } _flushTextureCache() { const currentRenderId = this._renderId; for (let i = this._textureCache.length - 1; i >= 0; i--) { if (currentRenderId - this._textureCache[i].lastUsedRenderId > 100) { let currentlyUsed = false; for (let j = 0; j < this._textures.length; j++) { if (this._textures.data[j] === this._textureCache[i].texture) { currentlyUsed = true; break; } } if (!currentlyUsed) { this._textureCache[i].texture.dispose(); this._textureCache.splice(i, 1); } } } } /** * Resizes the post-process texture * @param width Width of the texture * @param height Height of the texture * @param camera The camera this post-process is applied to. Pass null if the post-process is used outside the context of a camera post-process chain (default: null) * @param needMipMaps True if mip maps need to be generated after render (default: false) * @param forceDepthStencil True to force post-process texture creation with stencil depth and buffer (default: false) */ resize(width, height, camera = null, needMipMaps = false, forceDepthStencil = false) { if (this._textures.length > 0) { this._textures.reset(); } this.width = width; this.height = height; let firstPP = null; if (camera) { for (let i = 0; i < camera._postProcesses.length; i++) { if (camera._postProcesses[i] !== null) { firstPP = camera._postProcesses[i]; break; } } } const textureSize = { width: this.width, height: this.height }; const textureOptions = { generateMipMaps: needMipMaps, generateDepthBuffer: forceDepthStencil || firstPP === this, generateStencilBuffer: (forceDepthStencil || firstPP === this) && this._engine.isStencilEnable, samplingMode: this.renderTargetSamplingMode, type: this._textureType, format: this._textureFormat, samples: this._samples, label: "PostProcessRTT-" + this.name }; this._textures.push(this._createRenderTargetTexture(textureSize, textureOptions, 0)); if (this._reusable) { this._textures.push(this._createRenderTargetTexture(textureSize, textureOptions, 1)); } this._texelSize.copyFromFloats(1 / this.width, 1 / this.height); this.onSizeChangedObservable.notifyObservers(this); } _getTarget() { let target; if (this._shareOutputWithPostProcess) { target = this._shareOutputWithPostProcess.inputTexture; } else if (this._forcedOutputTexture) { target = this._forcedOutputTexture; this.width = this._forcedOutputTexture.width; this.height = this._forcedOutputTexture.height; } else { target = this.inputTexture; let cache; for (let i = 0; i < this._textureCache.length; i++) { if (this._textureCache[i].texture === target) { cache = this._textureCache[i]; break; } } if (cache) { cache.lastUsedRenderId = this._renderId; } } return target; } /** * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable. * When this post process is used in a pipeline, this is call will bind the input texture of this post process to the output of the previous. * @param cameraOrScene The camera that will be used in the post process. This camera will be used when calling onActivateObservable. You can also pass the scene if no camera is available. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null) * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false) * @returns The render target wrapper that was bound to be written to. */ activate(cameraOrScene, sourceTexture = null, forceDepthStencil) { const camera = cameraOrScene === null || cameraOrScene.cameraRigMode !== void 0 ? cameraOrScene || this._camera : null; const scene = camera?.getScene() ?? cameraOrScene; const engine = scene.getEngine(); const maxSize = engine.getCaps().maxTextureSize; const requiredWidth = (sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options | 0; const requiredHeight = (sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options | 0; let desiredWidth = this._options.width || requiredWidth; let desiredHeight = this._options.height || requiredHeight; const needMipMaps = this.renderTargetSamplingMode !== 7 && this.renderTargetSamplingMode !== 1 && this.renderTargetSamplingMode !== 2; let target = null; if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) { if (this.adaptScaleToCurrentViewport) { const currentViewport = engine.currentViewport; if (currentViewport) { desiredWidth *= currentViewport.width; desiredHeight *= currentViewport.height; } } if (needMipMaps || this.alwaysForcePOT) { if (!this._options.width) { desiredWidth = engine.needPOTTextures ? GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth; } if (!this._options.height) { desiredHeight = engine.needPOTTextures ? GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight; } } if (this.width !== desiredWidth || this.height !== desiredHeight || !(target = this._getTarget())) { this.resize(desiredWidth, desiredHeight, camera, needMipMaps, forceDepthStencil); } this._textures.forEach((texture) => { if (texture.samples !== this.samples) { this._engine.updateRenderTargetTextureSampleCount(texture, this.samples); } }); this._flushTextureCache(); this._renderId++; } if (!target) { target = this._getTarget(); } if (this.enablePixelPerfectMode) { this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight); this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport); } else { this._scaleRatio.copyFromFloats(1, 1); this._engine.bindFramebuffer(target, 0, void 0, void 0, this.forceFullscreenViewport); } this._engine._debugInsertMarker?.(`post process ${this.name} input`); this.onActivateObservable.notifyObservers(camera); if (this.autoClear && (this.alphaMode === 0 || this.forceAutoClearInAlphaMode)) { this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true); } if (this._reusable) { this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2; } return target; } /** * If the post process is supported. */ get isSupported() { return this._effectWrapper.drawWrapper.effect.isSupported; } /** * The aspect ratio of the output texture. */ get aspectRatio() { if (this._shareOutputWithPostProcess) { return this._shareOutputWithPostProcess.aspectRatio; } if (this._forcedOutputTexture) { return this._forcedOutputTexture.width / this._forcedOutputTexture.height; } return this.width / this.height; } /** * Get a value indicating if the post-process is ready to be used * @returns true if the post-process is ready (shader is compiled) */ isReady() { return this._effectWrapper.isReady(); } /** * Binds all textures and uniforms to the shader, this will be run on every pass. * @returns the effect corresponding to this post process. Null if not compiled or not ready. */ apply() { if (!this._effectWrapper.isReady()) { return null; } this._engine.enableEffect(this._effectWrapper.drawWrapper); this._engine.setState(false); this._engine.setDepthBuffer(false); this._engine.setDepthWrite(false); if (this.alphaConstants) { this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a); } this._engine.setAlphaMode(this.alphaMode); let source; if (this._shareOutputWithPostProcess) { source = this._shareOutputWithPostProcess.inputTexture; } else if (this._forcedOutputTexture) { source = this._forcedOutputTexture; } else { source = this.inputTexture; } if (!this.externalTextureSamplerBinding) { this._effectWrapper.drawWrapper.effect._bindTexture("textureSampler", source?.texture); } this._effectWrapper.drawWrapper.effect.setVector2("scale", this._scaleRatio); this.onApplyObservable.notifyObservers(this._effectWrapper.drawWrapper.effect); this._effectWrapper.bind(true); return this._effectWrapper.drawWrapper.effect; } _disposeTextures() { if (this._shareOutputWithPostProcess || this._forcedOutputTexture) { this._disposeTextureCache(); return; } this._disposeTextureCache(); this._textures.dispose(); } _disposeTextureCache() { for (let i = this._textureCache.length - 1; i >= 0; i--) { this._textureCache[i].texture.dispose(); } this._textureCache.length = 0; } /** * Sets the required values to the prepass renderer. * @param prePassRenderer defines the prepass renderer to setup. * @returns true if the pre pass is needed. */ setPrePassRenderer(prePassRenderer) { if (this._prePassEffectConfiguration) { this._prePassEffectConfiguration = prePassRenderer.addEffectConfiguration(this._prePassEffectConfiguration); this._prePassEffectConfiguration.enabled = true; return true; } return false; } /** * Disposes the post process. * @param camera The camera to dispose the post process on. */ dispose(camera) { camera = camera || this._camera; if (!this._useExistingThinPostProcess) { this._effectWrapper.dispose(); } this._disposeTextures(); let index; if (this._scene) { index = this._scene.removePostProcess(this); } if (this._parentContainer) { const index2 = this._parentContainer.postProcesses.indexOf(this); if (index2 > -1) { this._parentContainer.postProcesses.splice(index2, 1); } this._parentContainer = null; } index = this._engine.postProcesses.indexOf(this); if (index !== -1) { this._engine.postProcesses.splice(index, 1); } this.onDisposeObservable.notifyObservers(); if (!camera) { return; } camera.detachPostProcess(this); index = camera._postProcesses.indexOf(this); if (index === 0 && camera._postProcesses.length > 0) { const firstPostProcess = this._camera._getFirstPostProcess(); if (firstPostProcess) { firstPostProcess.markTextureDirty(); } } this.onActivateObservable.clear(); this.onAfterRenderObservable.clear(); this.onApplyObservable.clear(); this.onBeforeRenderObservable.clear(); this.onSizeChangedObservable.clear(); this.onEffectCreatedObservable.clear(); } /** * Serializes the post process to a JSON object * @returns the JSON object */ serialize() { const serializationObject = SerializationHelper.Serialize(this); const camera = this.getCamera() || this._scene && this._scene.activeCamera; serializationObject.customType = "BABYLON." + this.getClassName(); serializationObject.cameraId = camera ? camera.id : null; serializationObject.reusable = this._reusable; serializationObject.textureType = this._textureType; serializationObject.fragmentUrl = this._fragmentUrl; serializationObject.parameters = this._parameters; serializationObject.samplers = this._samplers; serializationObject.uniformBuffers = this._uniformBuffers; serializationObject.options = this._options; serializationObject.defines = this._postProcessDefines; serializationObject.textureFormat = this._textureFormat; serializationObject.vertexUrl = this._vertexUrl; serializationObject.indexParameters = this._indexParameters; return serializationObject; } /** * Clones this post process * @returns a new post process similar to this one */ clone() { const serializationObject = this.serialize(); serializationObject._engine = this._engine; serializationObject.cameraId = null; const result = _PostProcess.Parse(serializationObject, this._scene, ""); if (!result) { return null; } result.onActivateObservable = this.onActivateObservable.clone(); result.onSizeChangedObservable = this.onSizeChangedObservable.clone(); result.onApplyObservable = this.onApplyObservable.clone(); result.onBeforeRenderObservable = this.onBeforeRenderObservable.clone(); result.onAfterRenderObservable = this.onAfterRenderObservable.clone(); result._prePassEffectConfiguration = this._prePassEffectConfiguration; return result; } /** * Creates a material from parsed material data * @param parsedPostProcess defines parsed post process data * @param scene defines the hosting scene * @param rootUrl defines the root URL to use to load textures * @returns a new post process */ static Parse(parsedPostProcess, scene, rootUrl) { const postProcessType = GetClass(parsedPostProcess.customType); if (!postProcessType || !postProcessType._Parse) { return null; } const camera = scene ? scene.getCameraById(parsedPostProcess.cameraId) : null; return postProcessType._Parse(parsedPostProcess, camera, scene, rootUrl); } /** * @internal */ static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { return SerializationHelper.Parse(() => { return new _PostProcess(parsedPostProcess.name, parsedPostProcess.fragmentUrl, parsedPostProcess.parameters, parsedPostProcess.samplers, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable, parsedPostProcess.defines, parsedPostProcess.textureType, parsedPostProcess.vertexUrl, parsedPostProcess.indexParameters, false, parsedPostProcess.textureFormat); }, parsedPostProcess, scene, rootUrl); } }; __decorate([ serialize() ], PostProcess.prototype, "uniqueId", void 0); __decorate([ serialize() ], PostProcess.prototype, "name", null); __decorate([ serialize() ], PostProcess.prototype, "width", void 0); __decorate([ serialize() ], PostProcess.prototype, "height", void 0); __decorate([ serialize() ], PostProcess.prototype, "renderTargetSamplingMode", void 0); __decorate([ serializeAsColor4() ], PostProcess.prototype, "clearColor", void 0); __decorate([ serialize() ], PostProcess.prototype, "autoClear", void 0); __decorate([ serialize() ], PostProcess.prototype, "forceAutoClearInAlphaMode", void 0); __decorate([ serialize() ], PostProcess.prototype, "alphaMode", null); __decorate([ serialize() ], PostProcess.prototype, "alphaConstants", void 0); __decorate([ serialize() ], PostProcess.prototype, "enablePixelPerfectMode", void 0); __decorate([ serialize() ], PostProcess.prototype, "forceFullscreenViewport", void 0); __decorate([ serialize() ], PostProcess.prototype, "scaleMode", void 0); __decorate([ serialize() ], PostProcess.prototype, "alwaysForcePOT", void 0); __decorate([ serialize("samples") ], PostProcess.prototype, "_samples", void 0); __decorate([ serialize() ], PostProcess.prototype, "adaptScaleToCurrentViewport", void 0); RegisterClass("BABYLON.PostProcess", PostProcess); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/pass.fragment.js var pass_fragment_exports2 = {}; __export(pass_fragment_exports2, { passPixelShaderWGSL: () => passPixelShaderWGSL }); var name8, shader8, passPixelShaderWGSL; var init_pass_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/pass.fragment.js"() { init_shaderStore(); name8 = "passPixelShader"; shader8 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);}`; if (!ShaderStore.ShadersStoreWGSL[name8]) { ShaderStore.ShadersStoreWGSL[name8] = shader8; } passPixelShaderWGSL = { name: name8, shader: shader8 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/passCube.fragment.js var passCube_fragment_exports = {}; __export(passCube_fragment_exports, { passCubePixelShaderWGSL: () => passCubePixelShaderWGSL }); var name9, shader9, passCubePixelShaderWGSL; var init_passCube_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/passCube.fragment.js"() { init_shaderStore(); name9 = "passCubePixelShader"; shader9 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_cube; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var uv: vec2f=input.vUV*2.0-1.0; #ifdef POSITIVEX fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(1.001,uv.y,uv.x)); #endif #ifdef NEGATIVEX fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(-1.001,uv.y,uv.x)); #endif #ifdef POSITIVEY fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv.y,1.001,uv.x)); #endif #ifdef NEGATIVEY fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv.y,-1.001,uv.x)); #endif #ifdef POSITIVEZ fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,1.001)); #endif #ifdef NEGATIVEZ fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,vec3f(uv,-1.001)); #endif }`; if (!ShaderStore.ShadersStoreWGSL[name9]) { ShaderStore.ShadersStoreWGSL[name9] = shader9; } passCubePixelShaderWGSL = { name: name9, shader: shader9 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/passCube.fragment.js var passCube_fragment_exports2 = {}; __export(passCube_fragment_exports2, { passCubePixelShader: () => passCubePixelShader }); var name10, shader10, passCubePixelShader; var init_passCube_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/passCube.fragment.js"() { init_shaderStore(); name10 = "passCubePixelShader"; shader10 = `varying vec2 vUV;uniform samplerCube textureSampler; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec2 uv=vUV*2.0-1.0; #ifdef POSITIVEX gl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x)); #endif #ifdef NEGATIVEX gl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x)); #endif #ifdef POSITIVEY gl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x)); #endif #ifdef NEGATIVEY gl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x)); #endif #ifdef POSITIVEZ gl_FragColor=textureCube(textureSampler,vec3(uv,1.001)); #endif #ifdef NEGATIVEZ gl_FragColor=textureCube(textureSampler,vec3(uv,-1.001)); #endif }`; if (!ShaderStore.ShadersStore[name10]) { ShaderStore.ShadersStore[name10] = shader10; } passCubePixelShader = { name: name10, shader: shader10 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/performanceMonitor.js var PerformanceMonitor, RollingAverage; var init_performanceMonitor = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/performanceMonitor.js"() { init_precisionDate(); PerformanceMonitor = class { static { __name(this, "PerformanceMonitor"); } /** * constructor * @param frameSampleSize The number of samples required to saturate the sliding window */ constructor(frameSampleSize = 30) { this._enabled = true; this._rollingFrameTime = new RollingAverage(frameSampleSize); } /** * Samples current frame * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames */ sampleFrame(timeMs = PrecisionDate.Now) { if (!this._enabled) { return; } if (this._lastFrameTimeMs != null) { const dt = timeMs - this._lastFrameTimeMs; this._rollingFrameTime.add(dt); } this._lastFrameTimeMs = timeMs; } /** * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far) */ get averageFrameTime() { return this._rollingFrameTime.average; } /** * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far) */ get averageFrameTimeVariance() { return this._rollingFrameTime.variance; } /** * Returns the frame time of the most recent frame */ get instantaneousFrameTime() { return this._rollingFrameTime.history(0); } /** * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far) */ get averageFPS() { return 1e3 / this._rollingFrameTime.average; } /** * Returns the average framerate in frames per second using the most recent frame time */ get instantaneousFPS() { const history = this._rollingFrameTime.history(0); if (history === 0) { return 0; } return 1e3 / history; } /** * Returns true if enough samples have been taken to completely fill the sliding window */ get isSaturated() { return this._rollingFrameTime.isSaturated(); } /** * Enables contributions to the sliding window sample set */ enable() { this._enabled = true; } /** * Disables contributions to the sliding window sample set * Samples will not be interpolated over the disabled period */ disable() { this._enabled = false; this._lastFrameTimeMs = null; } /** * Returns true if sampling is enabled */ get isEnabled() { return this._enabled; } /** * Resets performance monitor */ reset() { this._lastFrameTimeMs = null; this._rollingFrameTime.reset(); } }; RollingAverage = class { static { __name(this, "RollingAverage"); } /** * constructor * @param length The number of samples required to saturate the sliding window */ constructor(length) { this._samples = new Array(length); this.reset(); } /** * Adds a sample to the sample set * @param v The sample value */ add(v) { let delta; if (this.isSaturated()) { const bottomValue = this._samples[this._pos]; delta = bottomValue - this.average; this.average -= delta / (this._sampleCount - 1); this._m2 -= delta * (bottomValue - this.average); } else { this._sampleCount++; } delta = v - this.average; this.average += delta / this._sampleCount; this._m2 += delta * (v - this.average); this.variance = this._m2 / (this._sampleCount - 1); this._samples[this._pos] = v; this._pos++; this._pos %= this._samples.length; } /** * Returns previously added values or null if outside of history or outside the sliding window domain * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that * @returns Value previously recorded with add() or null if outside of range */ history(i) { if (i >= this._sampleCount || i >= this._samples.length) { return 0; } const i0 = this._wrapPosition(this._pos - 1); return this._samples[this._wrapPosition(i0 - i)]; } /** * Returns true if enough samples have been taken to completely fill the sliding window * @returns true if sample-set saturated */ isSaturated() { return this._sampleCount >= this._samples.length; } /** * Resets the rolling average (equivalent to 0 samples taken so far) */ reset() { this.average = 0; this.variance = 0; this._sampleCount = 0; this._pos = 0; this._m2 = 0; } /** * Wraps a value around the sample range boundaries * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned. * @returns Wrapped position in sample range */ _wrapPosition(i) { const max = this._samples.length; return (i % max + max) % max; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.alpha.js var init_engine_alpha = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.alpha.js"() { init_thinEngine(); ThinEngine.prototype.setAlphaMode = function(mode, noDepthWriteChange = false, targetIndex = 0) { if (this._alphaMode[targetIndex] === mode) { if (!noDepthWriteChange) { const depthMask = mode === 0; if (this.depthCullingState.depthMask !== depthMask) { this.depthCullingState.depthMask = depthMask; } } return; } const alphaBlendDisabled = mode === 0; this._alphaState.setAlphaBlend(!alphaBlendDisabled, targetIndex); this._alphaState.setAlphaMode(mode, targetIndex); if (!noDepthWriteChange) { this.depthCullingState.depthMask = alphaBlendDisabled; } this._alphaMode[targetIndex] = mode; }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.rawTexture.js function ConvertRGBtoRGBATextureData(rgbData, width, height, textureType) { let rgbaData; let val1 = 1; if (textureType === 1) { rgbaData = new Float32Array(width * height * 4); } else if (textureType === 2) { rgbaData = new Uint16Array(width * height * 4); val1 = 15360; } else if (textureType === 7) { rgbaData = new Uint32Array(width * height * 4); } else { rgbaData = new Uint8Array(width * height * 4); } for (let x = 0; x < width; x++) { for (let y = 0; y < height; y++) { const index = (y * width + x) * 3; const newIndex = (y * width + x) * 4; rgbaData[newIndex + 0] = rgbData[index + 0]; rgbaData[newIndex + 1] = rgbData[index + 1]; rgbaData[newIndex + 2] = rgbData[index + 2]; rgbaData[newIndex + 3] = val1; } } return rgbaData; } function MakeCreateRawTextureFunction(is3D) { return function(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression = null, textureType = 0) { const target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY; const source = is3D ? 10 : 11; const texture = new 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); const 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; }; } function MakeUpdateRawTextureFunction(is3D) { return function(texture, data, format, invertY, compression = null, textureType = 0) { const target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY; const internalType = this._getWebGLTextureType(textureType); const internalFormat = this._getInternalFormat(format); const internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format); this._bindTextureDirectly(target, texture, true); this._unpackFlipY(invertY === void 0 ? 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); texture.isReady = true; }; } var init_engine_rawTexture = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.rawTexture.js"() { init_internalTexture(); init_logger(); init_thinEngine(); init_tools_functions(); ThinEngine.prototype.updateRawTexture = function(texture, data, format, invertY, compression = null, type = 0, useSRGBBuffer = false) { if (!texture) { return; } const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer); const internalFormat = this._getInternalFormat(format); const textureType = this._getWebGLTextureType(type); this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); this._unpackFlipY(invertY === void 0 ? 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); texture.isReady = true; }; ThinEngine.prototype.createRawTexture = function(data, width, height, format, generateMipMaps, invertY, samplingMode, compression = null, type = 0, creationFlags = 0, useSRGBBuffer = false) { const texture = new InternalTexture( this, 3 /* 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; texture._useSRGBBuffer = this._getUseSRGBBuffer(useSRGBBuffer, !generateMipMaps); if (!this._doNotHandleContextLost) { texture._bufferView = data; } this.updateRawTexture(texture, data, format, invertY, compression, type, texture._useSRGBBuffer); this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true); const 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.prototype.createRawCubeTexture = function(data, size, format, type, generateMipMaps, invertY, samplingMode, compression = null) { const gl = this._gl; const texture = new InternalTexture( this, 8 /* InternalTextureSource.CubeRaw */ ); texture.isCube = true; texture.format = format; texture.type = type; if (!this._doNotHandleContextLost) { texture._bufferViewArray = data; } const textureType = this._getWebGLTextureType(type); let internalFormat = this._getInternalFormat(format); if (internalFormat === gl.RGB) { internalFormat = gl.RGBA; } if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) { generateMipMaps = false; samplingMode = 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 = 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; 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; Logger.Warn("Render to half float textures is not supported. Mipmap generation forced to false."); } const width = size; const height = width; texture.width = width; texture.height = height; texture.invertY = invertY; texture._compression = compression; const isPot = !this.needPOTTextures || IsExponentOfTwo(texture.width) && IsExponentOfTwo(texture.height); if (!isPot) { generateMipMaps = false; } if (data) { this.updateRawCubeTexture(texture, data, format, type, invertY, compression); } else { const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type); const level = 0; this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); for (let faceIndex = 0; faceIndex < 6; faceIndex++) { if (compression) { gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, void 0); } else { gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, null); } } this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null); } this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true); if (data && generateMipMaps) { this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP); } const 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; texture.samplingMode = samplingMode; texture.isReady = true; return texture; }; ThinEngine.prototype.updateRawCubeTexture = function(texture, data, format, type, invertY, compression = null, level = 0) { texture._bufferViewArray = data; texture.format = format; texture.type = type; texture.invertY = invertY; texture._compression = compression; const gl = this._gl; const textureType = this._getWebGLTextureType(type); let internalFormat = this._getInternalFormat(format); const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type); let needConversion = false; if (internalFormat === gl.RGB) { internalFormat = gl.RGBA; needConversion = true; } this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); this._unpackFlipY(invertY === void 0 ? true : invertY ? true : false); if (texture.width % 4 !== 0) { gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); } for (let faceIndex = 0; faceIndex < 6; faceIndex++) { let 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); } } const isPot = !this.needPOTTextures || IsExponentOfTwo(texture.width) && 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); texture.isReady = true; }; ThinEngine.prototype.createRawCubeTextureFromUrl = function(url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad = null, onError = null, samplingMode = 3, invertY = false) { const gl = this._gl; const texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode, null); scene?.addPendingData(texture); texture.url = url; texture.isReady = false; this._internalTexturesCache.push(texture); const onerror = /* @__PURE__ */ __name((request, exception) => { scene?.removePendingData(texture); if (onError && request) { onError(request.status + " " + request.statusText, exception); } }, "onerror"); const internalCallbackAsync = /* @__PURE__ */ __name(async (data) => { if (!texture._hardwareTexture) { return; } const faceDataArraysResult = callback(data); if (!faceDataArraysResult) { return; } const faceDataArrays = faceDataArraysResult instanceof Promise ? await faceDataArraysResult : faceDataArraysResult; const width = texture.width; if (mipmapGenerator) { const textureType = this._getWebGLTextureType(type); let internalFormat = this._getInternalFormat(format); const internalSizedFomat = this._getRGBABufferInternalSizedFormat(type); let needConversion = false; if (internalFormat === gl.RGB) { internalFormat = gl.RGBA; needConversion = true; } this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); this._unpackFlipY(false); const mipData = mipmapGenerator(faceDataArrays); for (let level = 0; level < mipData.length; level++) { const mipSize = width >> level; for (let faceIndex = 0; faceIndex < 6; faceIndex++) { let 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; scene?.removePendingData(texture); texture.onLoadedObservable.notifyObservers(texture); texture.onLoadedObservable.clear(); if (onLoad) { onLoad(); } }, "internalCallbackAsync"); this._loadFile(url, (data) => { internalCallbackAsync(data).catch((err) => { onerror(void 0, err); }); }, void 0, scene?.offlineProvider, true, onerror); return texture; }; __name(ConvertRGBtoRGBATextureData, "ConvertRGBtoRGBATextureData"); __name(MakeCreateRawTextureFunction, "MakeCreateRawTextureFunction"); ThinEngine.prototype.createRawTexture2DArray = MakeCreateRawTextureFunction(false); ThinEngine.prototype.createRawTexture3D = MakeCreateRawTextureFunction(true); __name(MakeUpdateRawTextureFunction, "MakeUpdateRawTextureFunction"); ThinEngine.prototype.updateRawTexture2DArray = MakeUpdateRawTextureFunction(false); ThinEngine.prototype.updateRawTexture3D = MakeUpdateRawTextureFunction(true); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.readTexture.js var init_engine_readTexture = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.readTexture.js"() { init_thinEngine(); init_abstractEngine_functions(); ThinEngine.prototype._readTexturePixelsSync = function(texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) { const gl = this._gl; if (!gl) { throw new Error("Engine does not have gl rendering context."); } if (!this._dummyFramebuffer) { const 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._hardwareTexture?.underlyingResource, level); } else { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._hardwareTexture?.underlyingResource, level); } let readType = texture.type !== void 0 ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE; if (!noDataConversion) { 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; } } else if (!buffer) { buffer = allocateAndCopyTypedBuffer(texture.type, 4 * width * height); } if (flushRenderer) { this.flushFramebuffer(); } gl.readPixels(x, y, width, height, gl.RGBA, readType, buffer); gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer); return buffer; }; ThinEngine.prototype._readTexturePixels = function(texture, width, height, faceIndex = -1, level = 0, buffer = null, flushRenderer = true, noDataConversion = false, x = 0, y = 0) { return Promise.resolve(this._readTexturePixelsSync(texture, width, height, faceIndex, level, buffer, flushRenderer, noDataConversion, x, y)); }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.dynamicBuffer.js var init_engine_dynamicBuffer = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.dynamicBuffer.js"() { init_thinEngine(); ThinEngine.prototype.updateDynamicIndexBuffer = function(indexBuffer, indices, offset = 0) { this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null; this.bindIndexBuffer(indexBuffer); let view; if (indexBuffer.is32Bits) { view = indices instanceof Uint32Array ? indices : new Uint32Array(indices); } else { view = indices instanceof Uint16Array ? indices : new Uint16Array(indices); } this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, view, this._gl.DYNAMIC_DRAW); this._resetIndexBufferBinding(); }; ThinEngine.prototype.updateDynamicVertexBuffer = function(vertexBuffer, data, byteOffset, byteLength) { this.bindArrayBuffer(vertexBuffer); if (byteOffset === void 0) { byteOffset = 0; } const dataLength = data.byteLength || data.length; if (byteLength === void 0 || 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, byteOffset, new Float32Array(data).subarray(0, byteLength / 4)); } else { if (data instanceof ArrayBuffer) { data = new Uint8Array(data, 0, byteLength); } else { data = new Uint8Array(data.buffer, data.byteOffset, byteLength); } this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data); } } this._resetVertexBufferBinding(); }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.cubeTexture.js var init_engine_cubeTexture = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.cubeTexture.js"() { init_thinEngine(); init_internalTexture(); init_logger(); init_tools_functions(); ThinEngine.prototype._createDepthStencilCubeTexture = function(size, options) { const internalTexture = new InternalTexture( this, 12 /* InternalTextureSource.DepthStencil */ ); internalTexture.isCube = true; if (this.webGLVersion === 1) { Logger.Error("Depth cube texture is not supported by WebGL 1."); return internalTexture; } const internalOptions = { bilinearFiltering: false, comparisonFunction: 0, generateStencil: false, ...options }; const gl = this._gl; this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true); this._setupDepthStencilTexture(internalTexture, size, internalOptions.bilinearFiltering, internalOptions.comparisonFunction); for (let 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); this._internalTexturesCache.push(internalTexture); return internalTexture; }; ThinEngine.prototype._setCubeMapTextureParams = function(texture, loadMipmap, maxLevel) { const 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); texture.samplingMode = loadMipmap ? 3 : 2; if (loadMipmap && this.getCaps().textureMaxLevel && maxLevel !== void 0 && maxLevel > 0) { gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAX_LEVEL, maxLevel); texture._maxLodLevel = maxLevel; } this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); }; ThinEngine.prototype.createCubeTexture = function(rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, loaderOptions, useSRGBBuffer = false, buffer = null) { const gl = this._gl; return this.createCubeTextureBase(rootUrl, scene, files, !!noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback, (texture) => this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true), (texture, imgs) => { const width = this.needPOTTextures ? GetExponentOfTwo(imgs[0].width, this._caps.maxCubemapTextureSize) : imgs[0].width; const height = width; const 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); const internalFormat = format ? this._getInternalFormat(format, texture._useSRGBBuffer) : texture._useSRGBBuffer ? this._glSRGBExtensionValues.SRGB8_ALPHA8 : gl.RGBA; let texelFormat = format ? this._getInternalFormat(format) : gl.RGBA; if (texture._useSRGBBuffer && this.webGLVersion === 1) { texelFormat = internalFormat; } for (let index = 0; index < faces.length; index++) { if (imgs[index].width !== width || imgs[index].height !== height) { this._prepareWorkingCanvas(); if (!this._workingCanvas || !this._workingContext) { 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, texelFormat, gl.UNSIGNED_BYTE, this._workingCanvas); } else { gl.texImage2D(faces[index], 0, internalFormat, texelFormat, gl.UNSIGNED_BYTE, imgs[index]); } } if (!noMipmap) { gl.generateMipmap(gl.TEXTURE_CUBE_MAP); } this._setCubeMapTextureParams(texture, !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(); } }, !!useSRGBBuffer, buffer); }; ThinEngine.prototype.generateMipMapsForCubemap = function(texture, unbind = true) { if (texture.generateMipMaps) { const 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); } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/renderTargetWrapper.js var RenderTargetWrapper; var init_renderTargetWrapper = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/renderTargetWrapper.js"() { init_textureHelper_functions(); RenderTargetWrapper = class { static { __name(this, "RenderTargetWrapper"); } /** * Gets the depth/stencil texture */ get depthStencilTexture() { return this._depthStencilTexture; } /** * Sets the depth/stencil texture * @param texture The depth/stencil texture to set * @param disposeExisting True to dispose the existing depth/stencil texture (if any) before replacing it (default: true) */ setDepthStencilTexture(texture, disposeExisting = true) { if (disposeExisting && this._depthStencilTexture) { this._depthStencilTexture.dispose(); } this._depthStencilTexture = texture; this._generateDepthBuffer = this._generateStencilBuffer = this._depthStencilTextureWithStencil = false; if (texture) { this._generateDepthBuffer = true; this._generateStencilBuffer = this._depthStencilTextureWithStencil = HasStencilAspect(texture.format); } } /** * Indicates if the depth/stencil texture has a stencil aspect */ get depthStencilTextureWithStencil() { return this._depthStencilTextureWithStencil; } /** * Defines if the render target wrapper is for a cube texture or if false a 2d texture */ get isCube() { return this._isCube; } /** * Defines if the render target wrapper is for a single or multi target render wrapper */ get isMulti() { return this._isMulti; } /** * Defines if the render target wrapper is for a single or an array of textures */ get is2DArray() { return this.layers > 0; } /** * Defines if the render target wrapper is for a 3D texture */ get is3D() { return this.depth > 0; } /** * Gets the size of the render target wrapper (used for cubes, as width=height in this case) */ get size() { return this.width; } /** * Gets the width of the render target wrapper */ get width() { return this._size.width ?? this._size; } /** * Gets the height of the render target wrapper */ get height() { return this._size.height ?? this._size; } /** * Gets the number of layers of the render target wrapper (only used if is2DArray is true and wrapper is not a multi render target) */ get layers() { return this._size.layers || 0; } /** * Gets the depth of the render target wrapper (only used if is3D is true and wrapper is not a multi render target) */ get depth() { return this._size.depth || 0; } /** * Gets the render texture. If this is a multi render target, gets the first texture */ get texture() { return this._textures?.[0] ?? null; } /** * Gets the list of render textures. If we are not in a multi render target, the list will be null (use the texture getter instead) */ get textures() { return this._textures; } /** * Gets the face indices that correspond to the list of render textures. If we are not in a multi render target, the list will be null */ get faceIndices() { return this._faceIndices; } /** * Gets the layer indices that correspond to the list of render textures. If we are not in a multi render target, the list will be null */ get layerIndices() { return this._layerIndices; } /** * Gets the base array layer of a texture in the textures array * This is an number that is calculated based on the layer and face indices set for this texture at that index * @param index The index of the texture in the textures array to get the base array layer for * @returns the base array layer of the texture at the given index */ getBaseArrayLayer(index) { if (!this._textures) { return -1; } const texture = this._textures[index]; const layerIndex = this._layerIndices?.[index] ?? 0; const faceIndex = this._faceIndices?.[index] ?? 0; return texture.isCube ? layerIndex * 6 + faceIndex : texture.is3D ? 0 : layerIndex; } /** * Gets the sample count of the render target */ get samples() { return this._samples; } /** * Sets the sample count of the render target * @param value sample count * @param initializeBuffers If set to true, the engine will make an initializing call to drawBuffers (only used when isMulti=true). * @param force true to force calling the update sample count engine function even if the current sample count is equal to value * @returns the sample count that has been set */ setSamples(value, initializeBuffers = true, force = false) { if (this.samples === value && !force) { return value; } const result = this._isMulti ? this._engine.updateMultipleRenderTargetTextureSampleCount(this, value, initializeBuffers) : this._engine.updateRenderTargetTextureSampleCount(this, value); this._samples = value; return result; } /** * Resolves the MSAA textures into their non-MSAA version. * Note that if samples equals 1 (no MSAA), no resolve is performed. */ resolveMSAATextures() { if (this.isMulti) { this._engine.resolveMultiFramebuffer(this); } else { this._engine.resolveFramebuffer(this); } } /** * Generates mipmaps for each texture of the render target */ generateMipMaps() { if (this._engine._currentRenderTarget === this) { this._engine.unBindFramebuffer(this, true); } if (this.isMulti) { this._engine.generateMipMapsMultiFramebuffer(this); } else { this._engine.generateMipMapsFramebuffer(this); } } /** * Initializes the render target wrapper * @param isMulti true if the wrapper is a multi render target * @param isCube true if the wrapper should render to a cube texture * @param size size of the render target (width/height/layers) * @param engine engine used to create the render target * @param label defines the label to use for the wrapper (for debugging purpose only) */ constructor(isMulti, isCube, size, engine, label) { this._textures = null; this._faceIndices = null; this._layerIndices = null; this._samples = 1; this._attachments = null; this._generateStencilBuffer = false; this._generateDepthBuffer = false; this._depthStencilTextureWithStencil = false; this.disableAutomaticMSAAResolve = false; this.resolveMSAAColors = true; this.resolveMSAADepth = false; this.resolveMSAAStencil = false; this.depthReadOnly = false; this.stencilReadOnly = false; this._isMulti = isMulti; this._isCube = isCube; this._size = size; this._engine = engine; this._depthStencilTexture = null; this.label = label; } /** * Sets the render target texture(s) * @param textures texture(s) to set */ setTextures(textures) { if (Array.isArray(textures)) { this._textures = textures; } else if (textures) { this._textures = [textures]; } else { this._textures = null; } } /** * Set a texture in the textures array * @param texture The texture to set * @param index The index in the textures array to set * @param disposePrevious If this function should dispose the previous texture */ setTexture(texture, index = 0, disposePrevious = true) { if (!this._textures) { this._textures = []; } if (this._textures[index] === texture) { return; } if (this._textures[index] && disposePrevious) { this._textures[index].dispose(); } this._textures[index] = texture; } /** * Sets the layer and face indices of every render target texture bound to each color attachment * @param layers The layers of each texture to be set * @param faces The faces of each texture to be set */ setLayerAndFaceIndices(layers, faces) { this._layerIndices = layers; this._faceIndices = faces; } /** * Sets the layer and face indices of a texture in the textures array that should be bound to each color attachment * @param index The index of the texture in the textures array to modify * @param layer The layer of the texture to be set * @param face The face of the texture to be set */ setLayerAndFaceIndex(index = 0, layer, face) { if (!this._layerIndices) { this._layerIndices = []; } if (!this._faceIndices) { this._faceIndices = []; } if (layer !== void 0 && layer >= 0) { this._layerIndices[index] = layer; } if (face !== void 0 && face >= 0) { this._faceIndices[index] = face; } } /** * Creates the depth/stencil texture * @param comparisonFunction Comparison function to use for the texture * @param bilinearFiltering true if bilinear filtering should be used when sampling the texture * @param generateStencil Not used anymore. "format" will be used to determine if stencil should be created * @param samples sample count to use when creating the texture (default: 1) * @param format format of the depth texture (default: 14) * @param label defines the label to use for the texture (for debugging purpose only) * @returns the depth/stencil created texture */ createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14, label) { this._depthStencilTexture?.dispose(); this._depthStencilTextureWithStencil = generateStencil; this._depthStencilTextureLabel = label; this._depthStencilTexture = this._engine.createDepthStencilTexture(this._size, { bilinearFiltering, comparisonFunction, generateStencil, isCube: this._isCube, samples, depthTextureFormat: format, label }, this); return this._depthStencilTexture; } /** * @deprecated Use shareDepth instead * @param renderTarget Destination renderTarget */ _shareDepth(renderTarget) { this.shareDepth(renderTarget); } /** * Shares the depth buffer of this render target with another render target. * @param renderTarget Destination renderTarget */ shareDepth(renderTarget) { if (this._depthStencilTexture) { if (renderTarget._depthStencilTexture) { renderTarget._depthStencilTexture.dispose(); } renderTarget._depthStencilTexture = this._depthStencilTexture; renderTarget._depthStencilTextureWithStencil = this._depthStencilTextureWithStencil; this._depthStencilTexture.incrementReferences(); } } /** * @internal */ _swapAndDie(target) { if (this.texture) { this.texture._swapAndDie(target); } this._textures = null; this.dispose(true); } _cloneRenderTargetWrapper() { let rtw = null; if (this._isMulti) { const textureArray = this.textures; if (textureArray && textureArray.length > 0) { let generateDepthTexture = false; let textureCount = textureArray.length; let depthTextureFormat = -1; const lastTextureSource = textureArray[textureArray.length - 1]._source; if (lastTextureSource === 14 || lastTextureSource === 12) { generateDepthTexture = true; depthTextureFormat = textureArray[textureArray.length - 1].format; textureCount--; } const samplingModes = []; const types = []; const formats = []; const targetTypes = []; const faceIndex = []; const layerIndex = []; const layerCounts = []; const internalTexture2Index = {}; for (let i = 0; i < textureCount; ++i) { const texture = textureArray[i]; samplingModes.push(texture.samplingMode); types.push(texture.type); formats.push(texture.format); const index = internalTexture2Index[texture.uniqueId]; if (index !== void 0) { targetTypes.push(-1); layerCounts.push(0); } else { internalTexture2Index[texture.uniqueId] = i; if (texture.is2DArray) { targetTypes.push(35866); layerCounts.push(texture.depth); } else if (texture.isCube) { targetTypes.push(34067); layerCounts.push(0); } else if (texture.is3D) { targetTypes.push(32879); layerCounts.push(texture.depth); } else { targetTypes.push(3553); layerCounts.push(0); } } if (this._faceIndices) { faceIndex.push(this._faceIndices[i] ?? 0); } if (this._layerIndices) { layerIndex.push(this._layerIndices[i] ?? 0); } } const optionsMRT = { samplingModes, generateMipMaps: textureArray[0].generateMipMaps, generateDepthBuffer: this._generateDepthBuffer, generateStencilBuffer: this._generateStencilBuffer, generateDepthTexture, depthTextureFormat, types, formats, textureCount, targetTypes, faceIndex, layerIndex, layerCounts, label: this.label }; const size = { width: this.width, height: this.height, depth: this.depth }; rtw = this._engine.createMultipleRenderTarget(size, optionsMRT); for (let i = 0; i < textureCount; ++i) { if (targetTypes[i] !== -1) { continue; } const index = internalTexture2Index[textureArray[i].uniqueId]; rtw.setTexture(rtw.textures[index], i); } } } else { const options = {}; options.generateDepthBuffer = this._generateDepthBuffer; options.generateMipMaps = this.texture?.generateMipMaps ?? false; options.generateStencilBuffer = this._generateStencilBuffer; options.samplingMode = this.texture?.samplingMode; options.type = this.texture?.type; options.format = this.texture?.format; options.noColorAttachment = !this._textures; options.label = this.label; if (this.isCube) { rtw = this._engine.createRenderTargetCubeTexture(this.width, options); } else { const size = { width: this.width, height: this.height, layers: this.is2DArray || this.is3D ? this.texture?.depth : void 0 }; rtw = this._engine.createRenderTargetTexture(size, options); } if (rtw.texture) { rtw.texture.isReady = true; } } return rtw; } _swapRenderTargetWrapper(target) { if (this._textures && target._textures) { for (let i = 0; i < this._textures.length; ++i) { this._textures[i]._swapAndDie(target._textures[i], false); target._textures[i].isReady = true; } } if (this._depthStencilTexture && target._depthStencilTexture) { this._depthStencilTexture._swapAndDie(target._depthStencilTexture); target._depthStencilTexture.isReady = true; } this._textures = null; this._depthStencilTexture = null; } /** @internal */ _rebuild() { const rtw = this._cloneRenderTargetWrapper(); if (!rtw) { return; } if (this._depthStencilTexture) { const samplingMode = this._depthStencilTexture.samplingMode; const format = this._depthStencilTexture.format; const bilinear = samplingMode === 2 || samplingMode === 3 || samplingMode === 11; rtw.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction, bilinear, this._depthStencilTextureWithStencil, this._depthStencilTexture.samples, format, this._depthStencilTextureLabel); } if (this.samples > 1) { rtw.setSamples(this.samples); } rtw._swapRenderTargetWrapper(this); rtw.dispose(); } /** * Releases the internal render textures */ releaseTextures() { if (this._textures) { for (let i = 0; i < this._textures.length; ++i) { this._textures[i].dispose(); } } this._textures = null; } /** * Disposes the whole render target wrapper * @param disposeOnlyFramebuffers true if only the frame buffers should be released (used for the WebGL engine). If false, all the textures will also be released */ dispose(disposeOnlyFramebuffers = false) { if (!disposeOnlyFramebuffers) { this._depthStencilTexture?.dispose(); this._depthStencilTexture = null; this.releaseTextures(); } this._engine._releaseRenderTargetWrapper(this); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLRenderTargetWrapper.js var WebGLRenderTargetWrapper; var init_webGLRenderTargetWrapper = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/WebGL/webGLRenderTargetWrapper.js"() { init_renderTargetWrapper(); init_textureHelper_functions(); WebGLRenderTargetWrapper = class extends RenderTargetWrapper { static { __name(this, "WebGLRenderTargetWrapper"); } setDepthStencilTexture(texture, disposeExisting = true) { super.setDepthStencilTexture(texture, disposeExisting); if (!texture) { return; } const engine = this._engine; const gl = this._context; const hardwareTexture = texture._hardwareTexture; if (hardwareTexture && texture._autoMSAAManagement && this._MSAAFramebuffer) { const currentFb = engine._currentFramebuffer; engine._bindUnboundFramebuffer(this._MSAAFramebuffer); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, HasStencilAspect(texture.format) ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, hardwareTexture.getMSAARenderBuffer()); engine._bindUnboundFramebuffer(currentFb); } } constructor(isMulti, isCube, size, engine, context) { super(isMulti, isCube, size, engine); this._framebuffer = null; this._depthStencilBuffer = null; this._MSAAFramebuffer = null; this._colorTextureArray = null; this._depthStencilTextureArray = null; this._disposeOnlyFramebuffers = false; this._currentLOD = 0; this._context = context; } _cloneRenderTargetWrapper() { let rtw = null; if (this._colorTextureArray && this._depthStencilTextureArray) { rtw = this._engine.createMultiviewRenderTargetTexture(this.width, this.height); rtw.texture.isReady = true; } else { rtw = super._cloneRenderTargetWrapper(); } return rtw; } _swapRenderTargetWrapper(target) { super._swapRenderTargetWrapper(target); target._framebuffer = this._framebuffer; target._depthStencilBuffer = this._depthStencilBuffer; target._MSAAFramebuffer = this._MSAAFramebuffer; target._colorTextureArray = this._colorTextureArray; target._depthStencilTextureArray = this._depthStencilTextureArray; this._framebuffer = this._depthStencilBuffer = this._MSAAFramebuffer = this._colorTextureArray = this._depthStencilTextureArray = null; } /** * Creates the depth/stencil texture * @param comparisonFunction Comparison function to use for the texture * @param bilinearFiltering true if bilinear filtering should be used when sampling the texture * @param generateStencil true if the stencil aspect should also be created * @param samples sample count to use when creating the texture * @param format format of the depth texture * @param label defines the label to use for the texture (for debugging purpose only) * @returns the depth/stencil created texture */ createDepthStencilTexture(comparisonFunction = 0, bilinearFiltering = true, generateStencil = false, samples = 1, format = 14, label) { if (this._depthStencilBuffer) { const engine = this._engine; const currentFrameBuffer = engine._currentFramebuffer; const gl = this._context; engine._bindUnboundFramebuffer(this._framebuffer); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, null); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, null); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, null); engine._bindUnboundFramebuffer(currentFrameBuffer); gl.deleteRenderbuffer(this._depthStencilBuffer); this._depthStencilBuffer = null; } return super.createDepthStencilTexture(comparisonFunction, bilinearFiltering, generateStencil, samples, format, label); } /** * Shares the depth buffer of this render target with another render target. * @param renderTarget Destination renderTarget */ shareDepth(renderTarget) { super.shareDepth(renderTarget); const gl = this._context; const depthbuffer = this._depthStencilBuffer; const framebuffer = renderTarget._MSAAFramebuffer || renderTarget._framebuffer; const engine = this._engine; if (renderTarget._depthStencilBuffer && renderTarget._depthStencilBuffer !== depthbuffer) { gl.deleteRenderbuffer(renderTarget._depthStencilBuffer); } renderTarget._depthStencilBuffer = depthbuffer; const attachment = renderTarget._generateStencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT; engine._bindUnboundFramebuffer(framebuffer); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, depthbuffer); engine._bindUnboundFramebuffer(null); } /** * Binds a texture to this render target on a specific attachment * @param texture The texture to bind to the framebuffer * @param attachmentIndex Index of the attachment * @param faceIndexOrLayer The face or layer of the texture to render to in case of cube texture or array texture * @param lodLevel defines the lod level to bind to the frame buffer */ _bindTextureRenderTarget(texture, attachmentIndex = 0, faceIndexOrLayer, lodLevel = 0) { const hardwareTexture = texture._hardwareTexture; if (!hardwareTexture) { return; } const framebuffer = this._framebuffer; const engine = this._engine; const currentFb = engine._currentFramebuffer; engine._bindUnboundFramebuffer(framebuffer); let attachment; if (engine.webGLVersion > 1) { const gl = this._context; attachment = gl["COLOR_ATTACHMENT" + attachmentIndex]; if (texture.is2DArray || texture.is3D) { faceIndexOrLayer = faceIndexOrLayer ?? this.layerIndices?.[attachmentIndex] ?? 0; gl.framebufferTextureLayer(gl.FRAMEBUFFER, attachment, hardwareTexture.underlyingResource, lodLevel, faceIndexOrLayer); } else if (texture.isCube) { faceIndexOrLayer = faceIndexOrLayer ?? this.faceIndices?.[attachmentIndex] ?? 0; gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndexOrLayer, hardwareTexture.underlyingResource, lodLevel); } else { gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, hardwareTexture.underlyingResource, lodLevel); } } else { const gl = this._context; attachment = gl["COLOR_ATTACHMENT" + attachmentIndex + "_WEBGL"]; const target = faceIndexOrLayer !== void 0 ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndexOrLayer : gl.TEXTURE_2D; gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, target, hardwareTexture.underlyingResource, lodLevel); } if (texture._autoMSAAManagement && this._MSAAFramebuffer) { const gl = this._context; engine._bindUnboundFramebuffer(this._MSAAFramebuffer); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, hardwareTexture.getMSAARenderBuffer()); } engine._bindUnboundFramebuffer(currentFb); } /** * Set a texture in the textures array * @param texture the texture to set * @param index the index in the textures array to set * @param disposePrevious If this function should dispose the previous texture */ setTexture(texture, index = 0, disposePrevious = true) { super.setTexture(texture, index, disposePrevious); this._bindTextureRenderTarget(texture, index); } /** * Sets the layer and face indices of every render target texture * @param layers The layer of the texture to be set (make negative to not modify) * @param faces The face of the texture to be set (make negative to not modify) */ setLayerAndFaceIndices(layers, faces) { super.setLayerAndFaceIndices(layers, faces); if (!this.textures || !this.layerIndices || !this.faceIndices) { return; } const textureCount = this._attachments?.length ?? this.textures.length; for (let index = 0; index < textureCount; index++) { const texture = this.textures[index]; if (!texture) { continue; } if (texture.is2DArray || texture.is3D) { this._bindTextureRenderTarget(texture, index, this.layerIndices[index]); } else if (texture.isCube) { this._bindTextureRenderTarget(texture, index, this.faceIndices[index]); } else { this._bindTextureRenderTarget(texture, index); } } } /** * Set the face and layer indices of a texture in the textures array * @param index The index of the texture in the textures array to modify * @param layer The layer of the texture to be set * @param face The face of the texture to be set */ setLayerAndFaceIndex(index = 0, layer, face) { super.setLayerAndFaceIndex(index, layer, face); if (!this.textures || !this.layerIndices || !this.faceIndices) { return; } const texture = this.textures[index]; if (texture.is2DArray || texture.is3D) { this._bindTextureRenderTarget(this.textures[index], index, this.layerIndices[index]); } else if (texture.isCube) { this._bindTextureRenderTarget(this.textures[index], index, this.faceIndices[index]); } } resolveMSAATextures() { const engine = this._engine; const currentFramebuffer = engine._currentFramebuffer; engine._bindUnboundFramebuffer(this._MSAAFramebuffer); super.resolveMSAATextures(); engine._bindUnboundFramebuffer(currentFramebuffer); } dispose(disposeOnlyFramebuffers = this._disposeOnlyFramebuffers) { const gl = this._context; if (!disposeOnlyFramebuffers) { if (this._colorTextureArray) { this._context.deleteTexture(this._colorTextureArray); this._colorTextureArray = null; } if (this._depthStencilTextureArray) { this._context.deleteTexture(this._depthStencilTextureArray); this._depthStencilTextureArray = null; } } if (this._framebuffer) { gl.deleteFramebuffer(this._framebuffer); this._framebuffer = null; } if (this._depthStencilBuffer) { gl.deleteRenderbuffer(this._depthStencilBuffer); this._depthStencilBuffer = null; } if (this._MSAAFramebuffer) { gl.deleteFramebuffer(this._MSAAFramebuffer); this._MSAAFramebuffer = null; } super.dispose(disposeOnlyFramebuffers); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.texture.js var init_abstractEngine_texture = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.texture.js"() { init_abstractEngine(); AbstractEngine.prototype.createDepthStencilTexture = function(size, options, rtWrapper) { if (options.isCube) { const width = size.width || size; return this._createDepthStencilCubeTexture(width, options); } else { return this._createDepthStencilTexture(size, options, rtWrapper); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.renderTarget.js var init_engine_renderTarget = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.renderTarget.js"() { init_internalTexture(); init_logger(); init_thinEngine(); init_webGLRenderTargetWrapper(); init_textureHelper_functions(); init_abstractEngine_texture(); ThinEngine.prototype._createHardwareRenderTargetWrapper = function(isMulti, isCube, size) { const rtWrapper = new WebGLRenderTargetWrapper(isMulti, isCube, size, this, this._gl); this._renderTargetWrapperCache.push(rtWrapper); return rtWrapper; }; ThinEngine.prototype.createRenderTargetTexture = function(size, options) { const rtWrapper = this._createHardwareRenderTargetWrapper(false, false, size); let generateDepthBuffer = true; let generateStencilBuffer = false; let noColorAttachment = false; let colorAttachment = void 0; let samples = 1; let label = void 0; if (options !== void 0 && typeof options === "object") { generateDepthBuffer = options.generateDepthBuffer ?? true; generateStencilBuffer = !!options.generateStencilBuffer; noColorAttachment = !!options.noColorAttachment; colorAttachment = options.colorAttachment; samples = options.samples ?? 1; label = options.label; } const texture = colorAttachment || (noColorAttachment ? null : this._createInternalTexture( size, options, true, 5 /* InternalTextureSource.RenderTarget */ )); const width = size.width || size; const height = size.height || size; const currentFrameBuffer = this._currentFramebuffer; const gl = this._gl; const framebuffer = gl.createFramebuffer(); this._bindUnboundFramebuffer(framebuffer); rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height); if (texture && !texture.is2DArray && !texture.is3D) { gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._hardwareTexture.underlyingResource, 0); } this._bindUnboundFramebuffer(currentFrameBuffer); rtWrapper.label = label ?? "RenderTargetWrapper"; rtWrapper._framebuffer = framebuffer; rtWrapper._generateDepthBuffer = generateDepthBuffer; rtWrapper._generateStencilBuffer = generateStencilBuffer; rtWrapper.setTextures(texture); if (!colorAttachment) { this.updateRenderTargetTextureSampleCount(rtWrapper, samples); } else { rtWrapper._samples = colorAttachment.samples; if (colorAttachment.samples > 1) { const msaaRenderBuffer = colorAttachment._hardwareTexture.getMSAARenderBuffer(0); rtWrapper._MSAAFramebuffer = gl.createFramebuffer(); this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderBuffer); this._bindUnboundFramebuffer(null); } } return rtWrapper; }; ThinEngine.prototype._createDepthStencilTexture = function(size, options, rtWrapper) { const gl = this._gl; const layers = size.layers || 0; const depth = size.depth || 0; let target = gl.TEXTURE_2D; if (layers !== 0) { target = gl.TEXTURE_2D_ARRAY; } else if (depth !== 0) { target = gl.TEXTURE_3D; } const internalTexture = new InternalTexture( this, 12 /* InternalTextureSource.DepthStencil */ ); internalTexture.label = options.label; if (!this._caps.depthTextureExtension) { Logger.Error("Depth texture is not supported by your browser or hardware."); return internalTexture; } const internalOptions = { bilinearFiltering: false, comparisonFunction: 0, generateStencil: false, ...options }; this._bindTextureDirectly(target, internalTexture, true); this._setupDepthStencilTexture(internalTexture, size, internalOptions.comparisonFunction === 0 ? false : internalOptions.bilinearFiltering, internalOptions.comparisonFunction, internalOptions.samples); if (internalOptions.depthTextureFormat !== void 0) { if (internalOptions.depthTextureFormat !== 15 && internalOptions.depthTextureFormat !== 16 && internalOptions.depthTextureFormat !== 17 && internalOptions.depthTextureFormat !== 13 && internalOptions.depthTextureFormat !== 14 && internalOptions.depthTextureFormat !== 18) { Logger.Error(`Depth texture ${internalOptions.depthTextureFormat} format is not supported.`); return internalTexture; } internalTexture.format = internalOptions.depthTextureFormat; } else { internalTexture.format = internalOptions.generateStencil ? 13 : 16; } const hasStencil = HasStencilAspect(internalTexture.format); const type = this._getWebGLTextureTypeFromDepthTextureFormat(internalTexture.format); const format = hasStencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT; const internalFormat = this._getInternalFormatFromDepthTextureFormat(internalTexture.format, true, hasStencil); if (internalTexture.is2DArray) { gl.texImage3D(target, 0, internalFormat, internalTexture.width, internalTexture.height, layers, 0, format, type, null); } else if (internalTexture.is3D) { gl.texImage3D(target, 0, internalFormat, internalTexture.width, internalTexture.height, depth, 0, format, type, null); } else { gl.texImage2D(target, 0, internalFormat, internalTexture.width, internalTexture.height, 0, format, type, null); } this._bindTextureDirectly(target, null); this._internalTexturesCache.push(internalTexture); if (rtWrapper._depthStencilBuffer) { gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer); rtWrapper._depthStencilBuffer = null; } this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer ?? rtWrapper._framebuffer); rtWrapper._generateStencilBuffer = hasStencil; rtWrapper._depthStencilTextureWithStencil = hasStencil; rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.width, rtWrapper.height, rtWrapper.samples, internalTexture.format); this._bindUnboundFramebuffer(null); return internalTexture; }; ThinEngine.prototype.updateRenderTargetTextureSampleCount = function(rtWrapper, samples) { if (this.webGLVersion < 2 || !rtWrapper) { return 1; } if (rtWrapper.samples === samples) { return samples; } const gl = this._gl; samples = Math.min(samples, this.getCaps().maxMSAASamples); if (rtWrapper._depthStencilBuffer) { gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer); rtWrapper._depthStencilBuffer = null; } if (rtWrapper._MSAAFramebuffer) { gl.deleteFramebuffer(rtWrapper._MSAAFramebuffer); rtWrapper._MSAAFramebuffer = null; } const hardwareTexture = rtWrapper.texture?._hardwareTexture; hardwareTexture?.releaseMSAARenderBuffers(); if (rtWrapper.texture && samples > 1 && typeof gl.renderbufferStorageMultisample === "function") { const framebuffer = gl.createFramebuffer(); if (!framebuffer) { throw new Error("Unable to create multi sampled framebuffer"); } rtWrapper._MSAAFramebuffer = framebuffer; this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer); const colorRenderbuffer = this._createRenderBuffer(rtWrapper.texture.width, rtWrapper.texture.height, samples, -1, this._getRGBABufferInternalSizedFormat(rtWrapper.texture.type, rtWrapper.texture.format, rtWrapper.texture._useSRGBBuffer), gl.COLOR_ATTACHMENT0, false); if (!colorRenderbuffer) { throw new Error("Unable to create multi sampled framebuffer"); } hardwareTexture?.addMSAARenderBuffer(colorRenderbuffer); } this._bindUnboundFramebuffer(rtWrapper._MSAAFramebuffer ?? rtWrapper._framebuffer); if (rtWrapper.texture) { rtWrapper.texture.samples = samples; } rtWrapper._samples = samples; const depthFormat = rtWrapper._depthStencilTexture ? rtWrapper._depthStencilTexture.format : void 0; rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.width, rtWrapper.height, samples, depthFormat); this._bindUnboundFramebuffer(null); return samples; }; ThinEngine.prototype._setupDepthStencilTexture = function(internalTexture, size, bilinearFiltering, comparisonFunction, samples = 1) { const width = size.width ?? size; const height = size.height ?? size; const layers = size.layers || 0; const depth = size.depth || 0; internalTexture.baseWidth = width; internalTexture.baseHeight = height; internalTexture.width = width; internalTexture.height = height; internalTexture.is2DArray = layers > 0; internalTexture.depth = layers || depth; internalTexture.isReady = true; internalTexture.samples = samples; internalTexture.generateMipMaps = false; internalTexture.samplingMode = bilinearFiltering ? 2 : 1; internalTexture.type = 0; internalTexture._comparisonFunction = comparisonFunction; const gl = this._gl; const target = this._getTextureTarget(internalTexture); const 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 (this.webGLVersion > 1) { if (comparisonFunction === 0) { gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, 515); 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); } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.renderTargetTexture.js var init_engine_renderTargetTexture = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.renderTargetTexture.js"() { init_thinEngine(); ThinEngine.prototype.setDepthStencilTexture = function(channel, uniform, texture, name260) { if (channel === void 0) { return; } if (uniform) { this._boundUniforms[channel] = uniform; } if (!texture || !texture.depthStencilTexture) { this._setTexture(channel, null, void 0, void 0, name260); } else { this._setTexture(channel, texture, false, true, name260); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.renderTargetCube.js var init_engine_renderTargetCube = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.renderTargetCube.js"() { init_internalTexture(); init_logger(); init_thinEngine(); ThinEngine.prototype.createRenderTargetCubeTexture = function(size, options) { const rtWrapper = this._createHardwareRenderTargetWrapper(false, true, size); const fullOptions = { generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: 0, samplingMode: 3, format: 5, ...options }; fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer; if (fullOptions.type === 1 && !this._caps.textureFloatLinearFiltering) { fullOptions.samplingMode = 1; } else if (fullOptions.type === 2 && !this._caps.textureHalfFloatLinearFiltering) { fullOptions.samplingMode = 1; } const gl = this._gl; const texture = new InternalTexture( this, 5 /* InternalTextureSource.RenderTarget */ ); this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true); const filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps); if (fullOptions.type === 1 && !this._caps.textureFloat) { fullOptions.type = 0; 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 (let 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); } const framebuffer = gl.createFramebuffer(); this._bindUnboundFramebuffer(framebuffer); rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size); if (fullOptions.generateMipMaps) { gl.generateMipmap(gl.TEXTURE_CUBE_MAP); } this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); this._bindUnboundFramebuffer(null); rtWrapper._framebuffer = framebuffer; rtWrapper._generateDepthBuffer = fullOptions.generateDepthBuffer; rtWrapper._generateStencilBuffer = fullOptions.generateStencilBuffer; 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; this._internalTexturesCache.push(texture); rtWrapper.setTextures(texture); return rtWrapper; }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.prefilteredCubeTexture.js var init_engine_prefilteredCubeTexture = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.prefilteredCubeTexture.js"() { init_thinEngine(); init_internalTexture(); init_logger(); init_sphericalPolynomial(); init_baseTexture(); ThinEngine.prototype.createPrefilteredCubeTexture = function(rootUrl, scene, lodScale, lodOffset, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = true) { const callbackAsync = /* @__PURE__ */ __name(async (loadData) => { if (!loadData) { if (onLoad) { onLoad(null); } return; } const texture = loadData.texture; if (!createPolynomials) { texture._sphericalPolynomial = new SphericalPolynomial(); } else if (loadData.info.sphericalPolynomial) { texture._sphericalPolynomial = loadData.info.sphericalPolynomial; } texture._source = 9; if (this.getCaps().textureLOD) { if (onLoad) { onLoad(texture); } return; } const mipSlices = 3; const gl = this._gl; const width = loadData.width; if (!width) { return; } const { DDSTools: DDSTools2 } = await Promise.resolve().then(() => (init_dds(), dds_exports)); const textures = []; for (let i = 0; i < mipSlices; i++) { const smoothness = i / (mipSlices - 1); const roughness = 1 - smoothness; const minLODIndex = lodOffset; const maxLODIndex = Math.log2(width) * lodScale + lodOffset; const lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness; const mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex)); const glTextureFromLod = new InternalTexture( this, 2 /* InternalTextureSource.Temp */ ); glTextureFromLod.type = texture.type; glTextureFromLod.format = texture.format; glTextureFromLod.width = Math.pow(2, Math.max(Math.log2(width) - mipmapIndex, 0)); glTextureFromLod.height = glTextureFromLod.width; glTextureFromLod.isCube = true; glTextureFromLod._cachedWrapU = 0; glTextureFromLod._cachedWrapV = 0; this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true); glTextureFromLod.samplingMode = 2; gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, 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); if (loadData.isDDS) { const info = loadData.info; const data = loadData.data; this._unpackFlipY(info.isCompressed); DDSTools2.UploadDDSLevels(this, glTextureFromLod, data, info, true, 6, mipmapIndex); } else { Logger.Warn("DDS is the only prefiltered cube map supported so far."); } this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null); const lodTexture = new BaseTexture(scene); lodTexture._isCube = true; lodTexture._texture = glTextureFromLod; glTextureFromLod.isReady = true; textures.push(lodTexture); } texture._lodTextureHigh = textures[2]; texture._lodTextureMid = textures[1]; texture._lodTextureLow = textures[0]; if (onLoad) { onLoad(texture); } }, "callbackAsync"); return this.createCubeTexture(rootUrl, scene, null, false, callbackAsync, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset); }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.uniformBuffer.js var init_engine_uniformBuffer = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.uniformBuffer.js"() { init_thinEngine(); init_webGLDataBuffer(); ThinEngine.prototype.createUniformBuffer = function(elements, _label) { const ubo = this._gl.createBuffer(); if (!ubo) { throw new Error("Unable to create uniform buffer"); } const result = new 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; }; ThinEngine.prototype.createDynamicUniformBuffer = function(elements, _label) { const ubo = this._gl.createBuffer(); if (!ubo) { throw new Error("Unable to create dynamic uniform buffer"); } const result = new 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; }; ThinEngine.prototype.updateUniformBuffer = function(uniformBuffer, elements, offset, count) { this.bindUniformBuffer(uniformBuffer); if (offset === void 0) { offset = 0; } if (count === void 0) { 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); }; ThinEngine.prototype.bindUniformBuffer = function(buffer) { this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer ? buffer.underlyingResource : null); }; ThinEngine.prototype.bindUniformBufferBase = function(buffer, location2, name260) { this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location2, buffer ? buffer.underlyingResource : null); }; ThinEngine.prototype.bindUniformBlock = function(pipelineContext, blockName, index) { const program = pipelineContext.program; const uniformLocation = this._gl.getUniformBlockIndex(program, blockName); if (uniformLocation !== 4294967295) { this._gl.uniformBlockBinding(program, uniformLocation, index); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.loadingScreen.js var init_abstractEngine_loadingScreen = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.loadingScreen.js"() { init_domManagement(); init_abstractEngine(); AbstractEngine.prototype.displayLoadingUI = function() { if (!IsWindowObjectExist()) { return; } const loadingScreen = this.loadingScreen; if (loadingScreen) { loadingScreen.displayLoadingUI(); } }; AbstractEngine.prototype.hideLoadingUI = function() { if (!IsWindowObjectExist()) { return; } const loadingScreen = this._loadingScreen; if (loadingScreen) { loadingScreen.hideLoadingUI(); } }; Object.defineProperty(AbstractEngine.prototype, "loadingScreen", { get: /* @__PURE__ */ __name(function() { if (!this._loadingScreen && this._renderingCanvas) { this._loadingScreen = AbstractEngine.DefaultLoadingScreenFactory(this._renderingCanvas); } return this._loadingScreen; }, "get"), set: /* @__PURE__ */ __name(function(value) { this._loadingScreen = value; }, "set"), enumerable: true, configurable: true }); Object.defineProperty(AbstractEngine.prototype, "loadingUIText", { set: /* @__PURE__ */ __name(function(value) { this.loadingScreen.loadingUIText = value; }, "set"), enumerable: true, configurable: true }); Object.defineProperty(AbstractEngine.prototype, "loadingUIBackgroundColor", { set: /* @__PURE__ */ __name(function(value) { this.loadingScreen.loadingUIBackgroundColor = value; }, "set"), enumerable: true, configurable: true }); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.dom.js var init_abstractEngine_dom = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.dom.js"() { init_abstractEngine(); AbstractEngine.prototype.getInputElement = function() { return this._renderingCanvas; }; AbstractEngine.prototype.getRenderingCanvasClientRect = function() { if (!this._renderingCanvas) { return null; } return this._renderingCanvas.getBoundingClientRect(); }; AbstractEngine.prototype.getInputElementClientRect = function() { if (!this._renderingCanvas) { return null; } return this.getInputElement().getBoundingClientRect(); }; AbstractEngine.prototype.getAspectRatio = function(viewportOwner, useScreen = false) { const viewport = viewportOwner.viewport; return this.getRenderWidth(useScreen) * viewport.width / (this.getRenderHeight(useScreen) * viewport.height); }; AbstractEngine.prototype.getScreenAspectRatio = function() { return this.getRenderWidth(true) / this.getRenderHeight(true); }; AbstractEngine.prototype._verifyPointerLock = function() { this._onPointerLockChange?.(); }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.alpha.js var init_abstractEngine_alpha = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.alpha.js"() { init_abstractEngine(); AbstractEngine.prototype.setAlphaEquation = function(equation, targetIndex = 0) { if (this._alphaEquation[targetIndex] === equation) { return; } switch (equation) { case 0: this._alphaState.setAlphaEquationParameters(32774, 32774, targetIndex); break; case 1: this._alphaState.setAlphaEquationParameters(32778, 32778, targetIndex); break; case 2: this._alphaState.setAlphaEquationParameters(32779, 32779, targetIndex); break; case 3: this._alphaState.setAlphaEquationParameters(32776, 32776, targetIndex); break; case 4: this._alphaState.setAlphaEquationParameters(32775, 32775, targetIndex); break; case 5: this._alphaState.setAlphaEquationParameters(32775, 32774, targetIndex); break; } this._alphaEquation[targetIndex] = equation; }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.states.js var init_abstractEngine_states = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.states.js"() { init_abstractEngine(); init_abstractEngine_alpha(); AbstractEngine.prototype.getInputElement = function() { return this._renderingCanvas; }; AbstractEngine.prototype.getDepthFunction = function() { return this._depthCullingState.depthFunc; }; AbstractEngine.prototype.setDepthFunction = function(depthFunc) { this._depthCullingState.depthFunc = depthFunc; }; AbstractEngine.prototype.setDepthFunctionToGreater = function() { this.setDepthFunction(516); }; AbstractEngine.prototype.setDepthFunctionToGreaterOrEqual = function() { this.setDepthFunction(518); }; AbstractEngine.prototype.setDepthFunctionToLess = function() { this.setDepthFunction(513); }; AbstractEngine.prototype.setDepthFunctionToLessOrEqual = function() { this.setDepthFunction(515); }; AbstractEngine.prototype.getDepthWrite = function() { return this._depthCullingState.depthMask; }; AbstractEngine.prototype.setDepthWrite = function(enable) { this._depthCullingState.depthMask = enable; }; AbstractEngine.prototype.setAlphaConstants = function(r, g, b, a) { this._alphaState.setAlphaBlendConstants(r, g, b, a); }; AbstractEngine.prototype.getAlphaMode = function(targetIndex = 0) { return this._alphaMode[targetIndex]; }; AbstractEngine.prototype.getAlphaEquation = function(targetIndex = 0) { return this._alphaEquation[targetIndex]; }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.stencil.js var init_abstractEngine_stencil = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.stencil.js"() { init_abstractEngine(); init_abstractEngine_alpha(); AbstractEngine.prototype.getStencilBuffer = function() { return this._stencilState.stencilTest; }; AbstractEngine.prototype.setStencilBuffer = function(enable) { this._stencilState.stencilTest = enable; }; AbstractEngine.prototype.getStencilMask = function() { return this._stencilState.stencilMask; }; AbstractEngine.prototype.setStencilMask = function(mask) { this._stencilState.stencilMask = mask; }; AbstractEngine.prototype.getStencilFunction = function() { return this._stencilState.stencilFunc; }; AbstractEngine.prototype.getStencilBackFunction = function() { return this._stencilState.stencilBackFunc; }; AbstractEngine.prototype.getStencilFunctionReference = function() { return this._stencilState.stencilFuncRef; }; AbstractEngine.prototype.getStencilFunctionMask = function() { return this._stencilState.stencilFuncMask; }; AbstractEngine.prototype.setStencilFunction = function(stencilFunc) { this._stencilState.stencilFunc = stencilFunc; }; AbstractEngine.prototype.setStencilBackFunction = function(stencilFunc) { this._stencilState.stencilBackFunc = stencilFunc; }; AbstractEngine.prototype.setStencilFunctionReference = function(reference) { this._stencilState.stencilFuncRef = reference; }; AbstractEngine.prototype.setStencilFunctionMask = function(mask) { this._stencilState.stencilFuncMask = mask; }; AbstractEngine.prototype.getStencilOperationFail = function() { return this._stencilState.stencilOpStencilFail; }; AbstractEngine.prototype.getStencilBackOperationFail = function() { return this._stencilState.stencilBackOpStencilFail; }; AbstractEngine.prototype.getStencilOperationDepthFail = function() { return this._stencilState.stencilOpDepthFail; }; AbstractEngine.prototype.getStencilBackOperationDepthFail = function() { return this._stencilState.stencilBackOpDepthFail; }; AbstractEngine.prototype.getStencilOperationPass = function() { return this._stencilState.stencilOpStencilDepthPass; }; AbstractEngine.prototype.getStencilBackOperationPass = function() { return this._stencilState.stencilBackOpStencilDepthPass; }; AbstractEngine.prototype.setStencilOperationFail = function(operation) { this._stencilState.stencilOpStencilFail = operation; }; AbstractEngine.prototype.setStencilBackOperationFail = function(operation) { this._stencilState.stencilBackOpStencilFail = operation; }; AbstractEngine.prototype.setStencilOperationDepthFail = function(operation) { this._stencilState.stencilOpDepthFail = operation; }; AbstractEngine.prototype.setStencilBackOperationDepthFail = function(operation) { this._stencilState.stencilBackOpDepthFail = operation; }; AbstractEngine.prototype.setStencilOperationPass = function(operation) { this._stencilState.stencilOpStencilDepthPass = operation; }; AbstractEngine.prototype.setStencilBackOperationPass = function(operation) { this._stencilState.stencilBackOpStencilDepthPass = operation; }; AbstractEngine.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(); }; AbstractEngine.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); }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.renderPass.js var init_abstractEngine_renderPass = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.renderPass.js"() { init_abstractEngine(); AbstractEngine.prototype.getRenderPassNames = function() { return this._renderPassNames; }; AbstractEngine.prototype.getCurrentRenderPassName = function() { return this._renderPassNames[this.currentRenderPassId]; }; AbstractEngine.prototype.createRenderPassId = function(name260) { const id = ++AbstractEngine._RenderPassIdCounter; this._renderPassNames[id] = name260 ?? "NONAME"; return id; }; AbstractEngine.prototype.releaseRenderPassId = function(id) { this._renderPassNames[id] = void 0; for (let s = 0; s < this.scenes.length; ++s) { const scene = this.scenes[s]; for (let m = 0; m < scene.meshes.length; ++m) { const mesh = scene.meshes[m]; if (mesh.subMeshes) { for (let b = 0; b < mesh.subMeshes.length; ++b) { const subMesh = mesh.subMeshes[b]; subMesh._removeDrawWrapper(id); } } } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/engine.common.js function DisableTouchAction(canvas) { if (!canvas || !canvas.setAttribute) { return; } canvas.setAttribute("touch-action", "none"); canvas.style.touchAction = "none"; canvas.style.webkitTapHighlightColor = "transparent"; } function _CommonInit(commonEngine, canvas, creationOptions) { commonEngine._onCanvasFocus = () => { commonEngine.onCanvasFocusObservable.notifyObservers(commonEngine); }; commonEngine._onCanvasBlur = () => { commonEngine.onCanvasBlurObservable.notifyObservers(commonEngine); }; commonEngine._onCanvasContextMenu = (evt) => { if (commonEngine.disableContextMenu) { evt.preventDefault(); } }; canvas.addEventListener("focus", commonEngine._onCanvasFocus); canvas.addEventListener("blur", commonEngine._onCanvasBlur); canvas.addEventListener("contextmenu", commonEngine._onCanvasContextMenu); commonEngine._onBlur = () => { if (commonEngine.disablePerformanceMonitorInBackground) { commonEngine.performanceMonitor.disable(); } commonEngine._windowIsBackground = true; }; commonEngine._onFocus = () => { if (commonEngine.disablePerformanceMonitorInBackground) { commonEngine.performanceMonitor.enable(); } commonEngine._windowIsBackground = false; }; commonEngine._onCanvasPointerOut = (ev) => { if (document.elementFromPoint(ev.clientX, ev.clientY) !== canvas) { commonEngine.onCanvasPointerOutObservable.notifyObservers(ev); } }; const hostWindow = commonEngine.getHostWindow(); if (hostWindow && typeof hostWindow.addEventListener === "function") { hostWindow.addEventListener("blur", commonEngine._onBlur); hostWindow.addEventListener("focus", commonEngine._onFocus); } canvas.addEventListener("pointerout", commonEngine._onCanvasPointerOut); if (!creationOptions.doNotHandleTouchAction) { DisableTouchAction(canvas); } if (!AbstractEngine.audioEngine && creationOptions.audioEngine && AbstractEngine.AudioEngineFactory) { AbstractEngine.audioEngine = AbstractEngine.AudioEngineFactory(commonEngine.getRenderingCanvas(), commonEngine.getAudioContext(), commonEngine.getAudioDestination()); } if (IsDocumentAvailable()) { commonEngine._onFullscreenChange = () => { commonEngine.isFullscreen = !!document.fullscreenElement; if (commonEngine.isFullscreen && commonEngine._pointerLockRequested && canvas) { RequestPointerlock(canvas); } }; document.addEventListener("fullscreenchange", commonEngine._onFullscreenChange, false); document.addEventListener("webkitfullscreenchange", commonEngine._onFullscreenChange, false); commonEngine._onPointerLockChange = () => { commonEngine.isPointerLock = document.pointerLockElement === canvas; }; document.addEventListener("pointerlockchange", commonEngine._onPointerLockChange, false); document.addEventListener("webkitpointerlockchange", commonEngine._onPointerLockChange, false); } commonEngine.enableOfflineSupport = AbstractEngine.OfflineProviderFactory !== void 0; commonEngine._deterministicLockstep = !!creationOptions.deterministicLockstep; commonEngine._lockstepMaxSteps = creationOptions.lockstepMaxSteps || 0; commonEngine._timeStep = creationOptions.timeStep || 1 / 60; } function _CommonDispose(commonEngine, canvas) { if (EngineStore.Instances.length === 1 && AbstractEngine.audioEngine) { AbstractEngine.audioEngine.dispose(); AbstractEngine.audioEngine = null; } const hostWindow = commonEngine.getHostWindow(); if (hostWindow && typeof hostWindow.removeEventListener === "function") { hostWindow.removeEventListener("blur", commonEngine._onBlur); hostWindow.removeEventListener("focus", commonEngine._onFocus); } if (canvas) { canvas.removeEventListener("focus", commonEngine._onCanvasFocus); canvas.removeEventListener("blur", commonEngine._onCanvasBlur); canvas.removeEventListener("pointerout", commonEngine._onCanvasPointerOut); canvas.removeEventListener("contextmenu", commonEngine._onCanvasContextMenu); } if (IsDocumentAvailable()) { document.removeEventListener("fullscreenchange", commonEngine._onFullscreenChange); document.removeEventListener("mozfullscreenchange", commonEngine._onFullscreenChange); document.removeEventListener("webkitfullscreenchange", commonEngine._onFullscreenChange); document.removeEventListener("msfullscreenchange", commonEngine._onFullscreenChange); document.removeEventListener("pointerlockchange", commonEngine._onPointerLockChange); document.removeEventListener("mspointerlockchange", commonEngine._onPointerLockChange); document.removeEventListener("mozpointerlockchange", commonEngine._onPointerLockChange); document.removeEventListener("webkitpointerlockchange", commonEngine._onPointerLockChange); } } function GetFontOffset(font) { const text = document.createElement("span"); text.textContent = "Hg"; text.style.font = font; const block = document.createElement("div"); block.style.display = "inline-block"; block.style.width = "1px"; block.style.height = "0px"; block.style.verticalAlign = "bottom"; const div = document.createElement("div"); div.style.whiteSpace = "nowrap"; div.appendChild(text); div.appendChild(block); document.body.appendChild(div); let fontAscent = 0; let fontHeight = 0; try { fontHeight = block.getBoundingClientRect().top - text.getBoundingClientRect().top; block.style.verticalAlign = "baseline"; fontAscent = block.getBoundingClientRect().top - text.getBoundingClientRect().top; } finally { document.body.removeChild(div); } return { ascent: fontAscent, height: fontHeight, descent: fontHeight - fontAscent }; } async function CreateImageBitmapFromSource(engine, imageSource, options) { return await new Promise((resolve, reject) => { const image = new Image(); image.onload = () => { image.decode().then(() => { engine.createImageBitmap(image, options).then((imageBitmap) => { resolve(imageBitmap); }); }); }; image.onerror = () => { reject(`Error loading image ${image.src}`); }; image.src = imageSource; }); } function ResizeImageBitmap(engine, image, bufferWidth, bufferHeight) { const canvas = engine.createCanvas(bufferWidth, bufferHeight); const context = canvas.getContext("2d"); if (!context) { throw new Error("Unable to get 2d context for resizeImageBitmap"); } context.drawImage(image, 0, 0); const buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data; return buffer; } function RequestFullscreen(element) { const requestFunction = element.requestFullscreen || element.webkitRequestFullscreen; if (!requestFunction) { return; } requestFunction.call(element); } function ExitFullscreen() { const anyDoc = document; if (document.exitFullscreen) { document.exitFullscreen(); } else if (anyDoc.webkitCancelFullScreen) { anyDoc.webkitCancelFullScreen(); } } function RequestPointerlock(element) { if (element.requestPointerLock) { const promise = element.requestPointerLock(); if (promise instanceof Promise) { promise.then(() => { element.focus(); }).catch(() => { }); } else { element.focus(); } } } function ExitPointerlock() { if (document.exitPointerLock) { document.exitPointerLock(); } } var init_engine_common = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/engine.common.js"() { init_domManagement(); init_abstractEngine(); init_engineStore(); __name(DisableTouchAction, "DisableTouchAction"); __name(_CommonInit, "_CommonInit"); __name(_CommonDispose, "_CommonDispose"); __name(GetFontOffset, "GetFontOffset"); __name(CreateImageBitmapFromSource, "CreateImageBitmapFromSource"); __name(ResizeImageBitmap, "ResizeImageBitmap"); __name(RequestFullscreen, "RequestFullscreen"); __name(ExitFullscreen, "ExitFullscreen"); __name(RequestPointerlock, "RequestPointerlock"); __name(ExitPointerlock, "ExitPointerlock"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/perfCounter.js var PerfCounter; var init_perfCounter = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/perfCounter.js"() { init_precisionDate(); PerfCounter = class _PerfCounter { static { __name(this, "PerfCounter"); } /** * Returns the smallest value ever */ get min() { return this._min; } /** * Returns the biggest value ever */ get max() { return this._max; } /** * Returns the average value since the performance counter is running */ get average() { return this._average; } /** * Returns the average value of the last second the counter was monitored */ get lastSecAverage() { return this._lastSecAverage; } /** * Returns the current value */ get current() { return this._current; } /** * Gets the accumulated total */ get total() { return this._totalAccumulated; } /** * Gets the total value count */ get count() { return this._totalValueCount; } /** * Creates a new counter */ constructor() { this._startMonitoringTime = 0; this._min = 0; this._max = 0; this._average = 0; this._lastSecAverage = 0; this._current = 0; this._totalValueCount = 0; this._totalAccumulated = 0; this._lastSecAccumulated = 0; this._lastSecTime = 0; this._lastSecValueCount = 0; } /** * Call this method to start monitoring a new frame. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count. */ fetchNewFrame() { this._totalValueCount++; this._current = 0; this._lastSecValueCount++; } /** * Call this method to monitor a count of something (e.g. mesh drawn in viewport count) * @param newCount the count value to add to the monitored count * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics. */ addCount(newCount, fetchResult) { if (!_PerfCounter.Enabled) { return; } this._current += newCount; if (fetchResult) { this._fetchResult(); } } /** * Start monitoring this performance counter */ beginMonitoring() { if (!_PerfCounter.Enabled) { return; } this._startMonitoringTime = PrecisionDate.Now; } /** * Compute the time lapsed since the previous beginMonitoring() call. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter */ endMonitoring(newFrame = true) { if (!_PerfCounter.Enabled) { return; } if (newFrame) { this.fetchNewFrame(); } const currentTime = PrecisionDate.Now; this._current = currentTime - this._startMonitoringTime; if (newFrame) { this._fetchResult(); } } /** * Call this method to end the monitoring of a frame. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the end of the frame, after beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count. */ endFrame() { this._fetchResult(); } /** @internal */ _fetchResult() { this._totalAccumulated += this._current; this._lastSecAccumulated += this._current; this._min = Math.min(this._min, this._current); this._max = Math.max(this._max, this._current); this._average = this._totalAccumulated / this._totalValueCount; const now = PrecisionDate.Now; if (now - this._lastSecTime > 1e3) { this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount; this._lastSecTime = now; this._lastSecAccumulated = 0; this._lastSecValueCount = 0; } } }; PerfCounter.Enabled = true; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/engine.js var Engine; var init_engine = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/engine.js"() { init_internalTexture(); init_engineStore(); init_thinEngine(); init_performanceMonitor(); init_webGLDataBuffer(); init_logger(); init_webGLHardwareTexture(); init_engine_alpha(); init_engine_rawTexture(); init_engine_readTexture(); init_engine_dynamicBuffer(); init_engine_cubeTexture(); init_engine_renderTarget(); init_engine_renderTargetTexture(); init_engine_renderTargetCube(); init_engine_prefilteredCubeTexture(); init_engine_uniformBuffer(); init_abstractEngine_loadingScreen(); init_abstractEngine_dom(); init_abstractEngine_states(); init_abstractEngine_stencil(); init_abstractEngine_renderPass(); init_abstractEngine_texture(); init_abstractEngine(); init_engine_common(); init_perfCounter(); init_timingTools(); Engine = class _Engine extends ThinEngine { static { __name(this, "Engine"); } /** * Returns the current npm package of the sdk */ // Not mixed with Version for tooling purpose. static get NpmPackage() { return AbstractEngine.NpmPackage; } /** * Returns the current version of the framework */ static get Version() { return AbstractEngine.Version; } /** Gets the list of created engines */ static get Instances() { return EngineStore.Instances; } /** * Gets the latest created engine */ static get LastCreatedEngine() { return EngineStore.LastCreatedEngine; } /** * Gets the latest created scene */ static get LastCreatedScene() { return EngineStore.LastCreatedScene; } /** @internal */ // eslint-disable-next-line jsdoc/require-returns-check /** * Method called to create the default loading screen. * This can be overridden in your own app. * @param canvas The rendering canvas element * @returns The loading screen */ // eslint-disable-next-line @typescript-eslint/no-unused-vars static DefaultLoadingScreenFactory(canvas) { return AbstractEngine.DefaultLoadingScreenFactory(canvas); } get _supportsHardwareTextureRescaling() { return !!_Engine._RescalePostProcessFactory; } _measureFps() { this._performanceMonitor.sampleFrame(); this._fps = this._performanceMonitor.averageFPS; this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0; } /** * Gets the performance monitor attached to this engine * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#engineinstrumentation */ get performanceMonitor() { return this._performanceMonitor; } // Events /** * 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 already 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) */ constructor(canvasOrContext, antialias, options, adaptToDeviceRatio = false) { super(canvasOrContext, antialias, options, adaptToDeviceRatio); this.customAnimationFrameRequester = null; this._performanceMonitor = new PerformanceMonitor(); this._drawCalls = new PerfCounter(); if (!canvasOrContext) { return; } this._features.supportRenderPasses = true; options = this._creationOptions; } _initGLContext() { super._initGLContext(); this._rescalePostProcess = null; } /** * Shared initialization across engines types. * @param canvas The canvas associated with this instance of the engine. */ _sharedInit(canvas) { super._sharedInit(canvas); _CommonInit(this, canvas, this._creationOptions); } /** * Resize an image and returns the image data as an uint8array * @param image image to resize * @param bufferWidth destination buffer width * @param bufferHeight destination buffer height * @returns an uint8array containing RGBA values of bufferWidth * bufferHeight size */ resizeImageBitmap(image, bufferWidth, bufferHeight) { return ResizeImageBitmap(this, image, bufferWidth, bufferHeight); } /** * Engine abstraction for loading and creating an image bitmap from a given source string. * @param imageSource source to load the image from. * @param options An object that sets options for the image's extraction. * @returns ImageBitmap */ // eslint-disable-next-line @typescript-eslint/naming-convention async _createImageBitmapFromSource(imageSource, options) { return await CreateImageBitmapFromSource(this, imageSource, options); } /** * Toggle full screen mode * @param requestPointerLock defines if a pointer lock should be requested from the user */ switchFullscreen(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 */ enterFullscreen(requestPointerLock) { if (!this.isFullscreen) { this._pointerLockRequested = requestPointerLock; if (this._renderingCanvas) { RequestFullscreen(this._renderingCanvas); } } } /** * Exits full screen mode */ exitFullscreen() { if (this.isFullscreen) { ExitFullscreen(); } } /** States */ /** * Sets a boolean indicating if the dithering state is enabled or disabled * @param value defines the dithering state */ setDitheringState(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 */ setRasterizerState(value) { if (value) { this._gl.disable(this._gl.RASTERIZER_DISCARD); } else { this._gl.enable(this._gl.RASTERIZER_DISCARD); } } /** * 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) * @returns 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 */ setDirectViewport(x, y, width, height) { const 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 bottom 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 */ scissorClear(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 bottom 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 */ enableScissor(x, y, width, height) { const gl = this._gl; gl.enable(gl.SCISSOR_TEST); gl.scissor(x, y, width, height); } /** * Disable previously set scissor test rectangle */ disableScissor() { const gl = this._gl; gl.disable(gl.SCISSOR_TEST); } /** * @internal */ async _loadFileAsync(url, offlineProvider, useArrayBuffer) { return await new Promise((resolve, reject) => { this._loadFile(url, (data) => { resolve(data); }, void 0, offlineProvider, useArrayBuffer, (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 */ getVertexShaderSource(program) { const 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 */ getFragmentShaderSource(program) { const shaders = this._gl.getAttachedShaders(program); if (!shaders) { return null; } return this._gl.getShaderSource(shaders[1]); } /** * 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 framebufferDimensionsObject(dimensions) { this._framebufferDimensionsObject = dimensions; if (this._framebufferDimensionsObject) { this.onResizeObservable.notifyObservers(this); } } _rebuildBuffers() { for (const scene of this.scenes) { scene.resetCachedMaterial(); scene._rebuildGeometries(); } for (const scene of this._virtualScenes) { scene.resetCachedMaterial(); scene._rebuildGeometries(); } super._rebuildBuffers(); } /** * Get Font size information * @param font font name * @returns an object containing ascent, height and descent */ getFontOffset(font) { return GetFontOffset(font); } _cancelFrame() { if (this.customAnimationFrameRequester) { if (this._frameHandler !== 0) { this._frameHandler = 0; const { cancelAnimationFrame: cancelAnimationFrame2 } = this.customAnimationFrameRequester; if (cancelAnimationFrame2) { cancelAnimationFrame2(this.customAnimationFrameRequester.requestID); } } } else { super._cancelFrame(); } } _renderLoop(timestamp) { this._processFrame(timestamp); if (this._activeRenderLoops.length > 0 && this._frameHandler === 0) { if (this.customAnimationFrameRequester) { this.customAnimationFrameRequester.requestID = this._queueNewFrame(this.customAnimationFrameRequester.renderFunction || this._boundRenderFunction, this.customAnimationFrameRequester); this._frameHandler = this.customAnimationFrameRequester.requestID; } else { this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow()); } } } /** * Enters Pointerlock mode */ enterPointerlock() { if (this._renderingCanvas) { RequestPointerlock(this._renderingCanvas); } } /** * Exits Pointerlock mode */ exitPointerlock() { ExitPointerlock(); } /** * Begin a new frame */ beginFrame() { this._measureFps(); super.beginFrame(); } _deletePipelineContext(pipelineContext) { const webGLPipelineContext = pipelineContext; if (webGLPipelineContext && webGLPipelineContext.program) { if (webGLPipelineContext.transformFeedback) { this.deleteTransformFeedback(webGLPipelineContext.transformFeedback); webGLPipelineContext.transformFeedback = null; } } super._deletePipelineContext(pipelineContext); } createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings = null) { context = context || this._gl; this.onBeforeShaderCompilationObservable.notifyObservers(this); const program = super.createShaderProgram(pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings); this.onAfterShaderCompilationObservable.notifyObservers(this); return program; } _createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings = null) { const 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) { const 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; } /** * @internal */ _releaseTexture(texture) { super._releaseTexture(texture); } /** * @internal */ _releaseRenderTargetWrapper(rtWrapper) { super._releaseRenderTargetWrapper(rtWrapper); for (const scene of this.scenes) { for (const postProcess of scene.postProcesses) { if (postProcess._outputTexture === rtWrapper) { postProcess._outputTexture = null; } } for (const camera of scene.cameras) { for (const postProcess of camera._postProcesses) { if (postProcess) { if (postProcess._outputTexture === rtWrapper) { postProcess._outputTexture = null; } } } } } } /** * @internal * Rescales a texture * @param source input texture * @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 */ _rescaleTexture(source, destination, scene, internalFormat, onComplete) { 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); const rtt = this.createRenderTargetTexture({ width: destination.width, height: destination.height }, { generateMipMaps: false, type: 0, samplingMode: 2, generateDepthBuffer: false, generateStencilBuffer: false }); if (!this._rescalePostProcess && _Engine._RescalePostProcessFactory) { this._rescalePostProcess = _Engine._RescalePostProcessFactory(this); } if (this._rescalePostProcess) { this._rescalePostProcess.externalTextureSamplerBinding = true; const onCompiled = /* @__PURE__ */ __name(() => { this._rescalePostProcess.onApply = function(effect2) { effect2._bindTexture("textureSampler", source); }; let 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); rtt.dispose(); if (onComplete) { onComplete(); } }, "onCompiled"); const effect = this._rescalePostProcess.getEffect(); if (effect) { effect.executeWhenCompiled(onCompiled); } else { this._rescalePostProcess.onEffectCreatedObservable.addOnce((effect2) => { effect2.executeWhenCompiled(onCompiled); }); } } } /** * Wraps an external web gl texture in a Babylon texture. * @param texture defines the external texture * @param hasMipMaps defines whether the external texture has mip maps (default: false) * @param samplingMode defines the sampling mode for the external texture (default: 3) * @param width defines the width for the external texture (default: 0) * @param height defines the height for the external texture (default: 0) * @returns the babylon internal texture */ wrapWebGLTexture(texture, hasMipMaps = false, samplingMode = 3, width = 0, height = 0) { const hardwareTexture = new WebGLHardwareTexture(texture, this._gl); const internalTexture = new InternalTexture(this, 0, true); internalTexture._hardwareTexture = hardwareTexture; internalTexture.baseWidth = width; internalTexture.baseHeight = height; internalTexture.width = width; internalTexture.height = height; internalTexture.isReady = true; internalTexture.useMipMaps = hasMipMaps; this.updateTextureSamplingMode(samplingMode, internalTexture); return internalTexture; } /** * @internal */ _uploadImageToTexture(texture, image, faceIndex = 0, lod = 0) { const gl = this._gl; const textureType = this._getWebGLTextureType(texture.type); const format = this._getInternalFormat(texture.format); const internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format); const bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D; this._bindTextureDirectly(bindTarget, texture, true); this._unpackFlipY(texture.invertY); let 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 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 */ updateTextureComparisonFunction(texture, comparisonFunction) { if (this.webGLVersion === 1) { Logger.Error("WebGL 1 does not support texture comparison."); return; } const 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, 515); 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, 515); 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 instantiation * @param capacity defines the size of the buffer * @returns the webGL buffer */ createInstancesBuffer(capacity) { const buffer = this._gl.createBuffer(); if (!buffer) { throw new Error("Unable to create instance buffer"); } const result = new WebGLDataBuffer(buffer); result.capacity = capacity; this.bindArrayBuffer(result); this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW); result.references = 1; return result; } /** * Delete a webGL buffer used with instantiation * @param buffer defines the webGL buffer to delete */ deleteInstancesBuffer(buffer) { this._gl.deleteBuffer(buffer); } async _clientWaitAsync(sync, flags = 0, intervalms = 10) { const gl = this._gl; return await new Promise((resolve, reject) => { _RetryWithInterval(() => { const res = gl.clientWaitSync(sync, flags, 0); if (res == gl.WAIT_FAILED) { throw new Error("clientWaitSync failed"); } if (res == gl.TIMEOUT_EXPIRED) { return false; } return true; }, resolve, reject, intervalms); }); } /** * This function might return null synchronously, so it is technically not async. * @internal */ // eslint-disable-next-line no-restricted-syntax _readPixelsAsync(x, y, w, h, format, type, outputBuffer) { if (this._webGLVersion < 2) { throw new Error("_readPixelsAsync only work on WebGL2+"); } const gl = this._gl; const 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); const sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0); if (!sync) { return null; } gl.flush(); return this._clientWaitAsync(sync, 0, 10).then(() => { 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; }); } dispose() { this.hideLoadingUI(); if (this._rescalePostProcess) { this._rescalePostProcess.dispose(); } _CommonDispose(this, this._renderingCanvas); super.dispose(); } }; Engine.ALPHA_DISABLE = 0; Engine.ALPHA_ADD = 1; Engine.ALPHA_COMBINE = 2; Engine.ALPHA_SUBTRACT = 3; Engine.ALPHA_MULTIPLY = 4; Engine.ALPHA_MAXIMIZED = 5; Engine.ALPHA_ONEONE = 6; Engine.ALPHA_PREMULTIPLIED = 7; Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8; Engine.ALPHA_INTERPOLATE = 9; Engine.ALPHA_SCREENMODE = 10; Engine.DELAYLOADSTATE_NONE = 0; Engine.DELAYLOADSTATE_LOADED = 1; Engine.DELAYLOADSTATE_LOADING = 2; Engine.DELAYLOADSTATE_NOTLOADED = 4; Engine.NEVER = 512; Engine.ALWAYS = 519; Engine.LESS = 513; Engine.EQUAL = 514; Engine.LEQUAL = 515; Engine.GREATER = 516; Engine.GEQUAL = 518; Engine.NOTEQUAL = 517; Engine.KEEP = 7680; Engine.REPLACE = 7681; Engine.INCR = 7682; Engine.DECR = 7683; Engine.INVERT = 5386; Engine.INCR_WRAP = 34055; Engine.DECR_WRAP = 34056; Engine.TEXTURE_CLAMP_ADDRESSMODE = 0; Engine.TEXTURE_WRAP_ADDRESSMODE = 1; Engine.TEXTURE_MIRROR_ADDRESSMODE = 2; Engine.TEXTUREFORMAT_ALPHA = 0; Engine.TEXTUREFORMAT_LUMINANCE = 1; Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2; Engine.TEXTUREFORMAT_RGB = 4; Engine.TEXTUREFORMAT_RGBA = 5; Engine.TEXTUREFORMAT_RED = 6; Engine.TEXTUREFORMAT_R = 6; Engine.TEXTUREFORMAT_R16_UNORM = 33322; Engine.TEXTUREFORMAT_RG16_UNORM = 33324; Engine.TEXTUREFORMAT_RGB16_UNORM = 32852; Engine.TEXTUREFORMAT_RGBA16_UNORM = 32859; Engine.TEXTUREFORMAT_R16_SNORM = 36760; Engine.TEXTUREFORMAT_RG16_SNORM = 36761; Engine.TEXTUREFORMAT_RGB16_SNORM = 36762; Engine.TEXTUREFORMAT_RGBA16_SNORM = 36763; Engine.TEXTUREFORMAT_RG = 7; Engine.TEXTUREFORMAT_RED_INTEGER = 8; Engine.TEXTUREFORMAT_R_INTEGER = 8; Engine.TEXTUREFORMAT_RG_INTEGER = 9; Engine.TEXTUREFORMAT_RGB_INTEGER = 10; Engine.TEXTUREFORMAT_RGBA_INTEGER = 11; Engine.TEXTURETYPE_UNSIGNED_BYTE = 0; Engine.TEXTURETYPE_UNSIGNED_INT = 0; Engine.TEXTURETYPE_FLOAT = 1; Engine.TEXTURETYPE_HALF_FLOAT = 2; Engine.TEXTURETYPE_BYTE = 3; Engine.TEXTURETYPE_SHORT = 4; Engine.TEXTURETYPE_UNSIGNED_SHORT = 5; Engine.TEXTURETYPE_INT = 6; Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7; Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8; Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9; Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10; Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11; Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12; Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13; Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14; Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15; Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1; Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2; Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3; Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8; Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11; Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3; Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4; Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5; Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6; Engine.TEXTURE_NEAREST_LINEAR = 7; Engine.TEXTURE_NEAREST_NEAREST = 1; Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9; Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10; Engine.TEXTURE_LINEAR_LINEAR = 2; Engine.TEXTURE_LINEAR_NEAREST = 12; Engine.TEXTURE_EXPLICIT_MODE = 0; Engine.TEXTURE_SPHERICAL_MODE = 1; Engine.TEXTURE_PLANAR_MODE = 2; Engine.TEXTURE_CUBIC_MODE = 3; Engine.TEXTURE_PROJECTION_MODE = 4; Engine.TEXTURE_SKYBOX_MODE = 5; Engine.TEXTURE_INVCUBIC_MODE = 6; Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7; Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8; Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9; Engine.SCALEMODE_FLOOR = 1; Engine.SCALEMODE_NEAREST = 2; Engine.SCALEMODE_CEILING = 3; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinPassPostProcess.js var ThinPassPostProcess, ThinPassCubePostProcess; var init_thinPassPostProcess = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinPassPostProcess.js"() { init_effectRenderer(); init_engine(); ThinPassPostProcess = class _ThinPassPostProcess extends EffectWrapper { static { __name(this, "ThinPassPostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.all([Promise.resolve().then(() => (init_pass_fragment2(), pass_fragment_exports2))])); } else { list.push(Promise.all([Promise.resolve().then(() => (init_pass_fragment(), pass_fragment_exports))])); } super._gatherImports(useWebGPU, list); } /** * Constructs a new pass post process * @param name Name of the effect * @param engine Engine to use to render the effect. If not provided, the last created engine will be used * @param options Options to configure the effect */ constructor(name260, engine = null, options) { const localOptions = { name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinPassPostProcess.FragmentUrl, ...options }; if (!localOptions.engine) { localOptions.engine = Engine.LastCreatedEngine; } super(localOptions); } }; ThinPassPostProcess.FragmentUrl = "pass"; ThinPassCubePostProcess = class _ThinPassCubePostProcess extends EffectWrapper { static { __name(this, "ThinPassCubePostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.all([Promise.resolve().then(() => (init_passCube_fragment(), passCube_fragment_exports))])); } else { list.push(Promise.all([Promise.resolve().then(() => (init_passCube_fragment2(), passCube_fragment_exports2))])); } super._gatherImports(useWebGPU, list); } /** * Creates the PassCubePostProcess * @param name Name of the effect * @param engine Engine to use to render the effect. If not provided, the last created engine will be used * @param options Options to configure the effect */ constructor(name260, engine = null, options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinPassCubePostProcess.FragmentUrl, defines: "#define POSITIVEX" }); this._face = 0; } /** * Gets or sets the cube face to display. * * 0 is +X * * 1 is -X * * 2 is +Y * * 3 is -Y * * 4 is +Z * * 5 is -Z */ get face() { return this._face; } set face(value) { if (value < 0 || value > 5) { return; } this._face = value; switch (this._face) { case 0: this.updateEffect("#define POSITIVEX"); break; case 1: this.updateEffect("#define NEGATIVEX"); break; case 2: this.updateEffect("#define POSITIVEY"); break; case 3: this.updateEffect("#define NEGATIVEY"); break; case 4: this.updateEffect("#define POSITIVEZ"); break; case 5: this.updateEffect("#define NEGATIVEZ"); break; } } }; ThinPassCubePostProcess.FragmentUrl = "passCube"; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/passPostProcess.js var PassPostProcess, PassCubePostProcess; var init_passPostProcess = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/passPostProcess.js"() { init_tslib_es6(); init_postProcess(); init_abstractEngine(); init_typeStore(); init_decorators_serialization(); init_thinPassPostProcess(); init_decorators(); PassPostProcess = class _PassPostProcess extends PostProcess { static { __name(this, "PassPostProcess"); } /** * Gets a string identifying the name of the class * @returns "PassPostProcess" string */ getClassName() { return "PassPostProcess"; } /** * Creates the PassPostProcess * @param name The name of the effect. * @param options The required width/height ratio to downsize to before computing the render pass. * @param camera The camera to apply the render pass to. * @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 The type of texture to be used when performing the post processing. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ constructor(name260, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { const localOptions = { size: typeof options === "number" ? options : void 0, camera, samplingMode, engine, reusable, textureType, blockCompilation, ...options }; super(name260, ThinPassPostProcess.FragmentUrl, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinPassPostProcess(name260, engine, localOptions) : void 0, ...localOptions }); } /** * @internal */ static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { return SerializationHelper.Parse(() => { return new _PassPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable); }, parsedPostProcess, scene, rootUrl); } }; RegisterClass("BABYLON.PassPostProcess", PassPostProcess); PassCubePostProcess = class _PassCubePostProcess extends PostProcess { static { __name(this, "PassCubePostProcess"); } /** * Gets or sets the cube face to display. * * 0 is +X * * 1 is -X * * 2 is +Y * * 3 is -Y * * 4 is +Z * * 5 is -Z */ get face() { return this._effectWrapper.face; } set face(value) { this._effectWrapper.face = value; } /** * Gets a string identifying the name of the class * @returns "PassCubePostProcess" string */ getClassName() { return "PassCubePostProcess"; } /** * Creates the PassCubePostProcess * @param name The name of the effect. * @param options The required width/height ratio to downsize to before computing the render pass. * @param camera The camera to apply the render pass to. * @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 The type of texture to be used when performing the post processing. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ constructor(name260, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { const localOptions = { size: typeof options === "number" ? options : void 0, camera, samplingMode, engine, reusable, textureType, blockCompilation, ...options }; super(name260, ThinPassPostProcess.FragmentUrl, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinPassCubePostProcess(name260, engine, localOptions) : void 0, ...localOptions }); } /** * @internal */ static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { return SerializationHelper.Parse(() => { return new _PassCubePostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, parsedPostProcess._engine, parsedPostProcess.reusable); }, parsedPostProcess, scene, rootUrl); } }; __decorate([ serialize() ], PassCubePostProcess.prototype, "face", null); AbstractEngine._RescalePostProcessFactory = (engine) => { return new PassPostProcess("rescale", 1, null, 2, engine, false, 0); }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/textureTools.js function CreateResizedCopy(texture, width, height, useBilinearMode = true) { const scene = texture.getScene(); const engine = scene.getEngine(); const rtt = new RenderTargetTexture("resized" + texture.name, { width, height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture.samplingMode, false); rtt.wrapU = texture.wrapU; rtt.wrapV = texture.wrapV; rtt.uOffset = texture.uOffset; rtt.vOffset = texture.vOffset; rtt.uScale = texture.uScale; rtt.vScale = texture.vScale; rtt.uAng = texture.uAng; rtt.vAng = texture.vAng; rtt.wAng = texture.wAng; rtt.coordinatesIndex = texture.coordinatesIndex; rtt.level = texture.level; rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel; rtt._texture.isReady = false; texture.wrapU = Texture.CLAMP_ADDRESSMODE; texture.wrapV = Texture.CLAMP_ADDRESSMODE; const passPostProcess = new PassPostProcess("pass", 1, null, useBilinearMode ? Texture.BILINEAR_SAMPLINGMODE : Texture.NEAREST_SAMPLINGMODE, engine, false, 0); passPostProcess.externalTextureSamplerBinding = true; passPostProcess.onEffectCreatedObservable.addOnce((e) => { e.executeWhenCompiled(() => { passPostProcess.onApply = function(effect) { effect.setTexture("textureSampler", texture); }; const internalTexture = rtt.renderTarget; if (internalTexture) { scene.postProcessManager.directRender([passPostProcess], internalTexture); engine.unBindFramebuffer(internalTexture); rtt.disposeFramebufferObjects(); passPostProcess.dispose(); rtt.getInternalTexture().isReady = true; } }); }); return rtt; } function ApplyPostProcess(postProcessName, internalTexture, scene, type, samplingMode, format, width, height) { const engine = internalTexture.getEngine(); internalTexture.isReady = false; samplingMode = samplingMode ?? internalTexture.samplingMode; type = type ?? internalTexture.type; format = format ?? internalTexture.format; width = width ?? internalTexture.width; height = height ?? internalTexture.height; if (type === -1) { type = 0; } return new Promise((resolve) => { const postProcess = new PostProcess("postprocess", postProcessName, null, null, 1, null, samplingMode, engine, false, void 0, type, void 0, null, false, format); postProcess.externalTextureSamplerBinding = true; const encodedTexture = engine.createRenderTargetTexture({ width, height }, { generateDepthBuffer: false, generateMipMaps: false, generateStencilBuffer: false, samplingMode, type, format }); postProcess.onEffectCreatedObservable.addOnce((e) => { e.executeWhenCompiled(() => { postProcess.onApply = (effect) => { effect._bindTexture("textureSampler", internalTexture); effect.setFloat2("scale", 1, 1); }; scene.postProcessManager.directRender([postProcess], encodedTexture, true); engine.restoreDefaultFramebuffer(); engine._releaseTexture(internalTexture); if (postProcess) { postProcess.dispose(); } encodedTexture._swapAndDie(internalTexture); internalTexture.type = type; internalTexture.format = 5; internalTexture.isReady = true; resolve(internalTexture); }); }); }); } function ToHalfFloat(value) { if (!floatView) { floatView = new Float32Array(1); int32View = new Int32Array(floatView.buffer); } floatView[0] = value; const x = int32View[0]; let bits = x >> 16 & 32768; let m = x >> 12 & 2047; const e = x >> 23 & 255; if (e < 103) { return bits; } if (e > 142) { bits |= 31744; bits |= (e == 255 ? 0 : 1) && x & 8388607; return bits; } if (e < 113) { m |= 2048; bits |= (m >> 114 - e) + (m >> 113 - e & 1); return bits; } bits |= e - 112 << 10 | m >> 1; bits += m & 1; return bits; } function FromHalfFloat(value) { const s = (value & 32768) >> 15; const e = (value & 31744) >> 10; const f = value & 1023; if (e === 0) { return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10)); } else if (e == 31) { return f ? NaN : (s ? -1 : 1) * Infinity; } return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + f / Math.pow(2, 10)); } function IsCompressedTextureFormat(format) { switch (format) { case 36492: case 36493: case 36495: case 36494: case 33779: case 35919: case 33778: case 35918: case 33777: case 33776: case 35917: case 35916: case 37808: case 37840: case 36196: case 37492: case 37493: case 37494: case 37495: case 37496: case 37497: return true; default: return false; } } async function WhenTextureReadyAsync(texture) { if (texture.isReady()) { return; } if (texture.loadingError) { throw new Error(texture.errorObject?.message || `Texture ${texture.name} errored while loading.`); } const onLoadObservable = texture.onLoadObservable; if (onLoadObservable) { return await new Promise((res) => onLoadObservable.addOnce(() => res())); } const onLoadedObservable = texture._texture?.onLoadedObservable; if (onLoadedObservable) { return await new Promise((res) => onLoadedObservable.addOnce(() => res())); } throw new Error(`Cannot determine readiness of texture ${texture.name}.`); } async function ReadPixelsUsingRTT(texture, width, height, face, lod) { const scene = texture.getScene(); const engine = scene.getEngine(); if (!engine.isWebGPU) { if (texture.isCube) { await Promise.resolve().then(() => (init_lodCube_fragment(), lodCube_fragment_exports)); } else { await Promise.resolve().then(() => (init_lod_fragment(), lod_fragment_exports)); } } else { if (texture.isCube) { await Promise.resolve().then(() => (init_lodCube_fragment2(), lodCube_fragment_exports2)); } else { await Promise.resolve().then(() => (init_lod_fragment2(), lod_fragment_exports2)); } } let lodPostProcess; if (!texture.isCube) { lodPostProcess = new PostProcess("lod", "lod", { uniforms: ["lod", "gamma"], samplingMode: Texture.NEAREST_NEAREST_MIPNEAREST, engine, shaderLanguage: engine.isWebGPU ? 1 : 0 }); } else { const faceDefines = ["#define POSITIVEX", "#define NEGATIVEX", "#define POSITIVEY", "#define NEGATIVEY", "#define POSITIVEZ", "#define NEGATIVEZ"]; lodPostProcess = new PostProcess("lodCube", "lodCube", { uniforms: ["lod", "gamma"], samplingMode: Texture.NEAREST_NEAREST_MIPNEAREST, engine, defines: faceDefines[face], shaderLanguage: engine.isWebGPU ? 1 : 0 }); } await new Promise((resolve) => { lodPostProcess.onEffectCreatedObservable.addOnce((e) => { e.executeWhenCompiled(() => { resolve(0); }); }); }); const rtt = new RenderTargetTexture("temp", { width, height }, scene, false); lodPostProcess.onApply = function(effect) { effect.setTexture("textureSampler", texture); effect.setFloat("lod", lod); effect.setInt("gamma", texture.gammaSpace ? 1 : 0); }; const internalTexture = texture.getInternalTexture(); try { if (rtt.renderTarget && internalTexture) { const samplingMode = internalTexture.samplingMode; if (lod !== 0) { texture.updateSamplingMode(Texture.NEAREST_NEAREST_MIPNEAREST); } else { texture.updateSamplingMode(Texture.NEAREST_NEAREST); } scene.postProcessManager.directRender([lodPostProcess], rtt.renderTarget, true); texture.updateSamplingMode(samplingMode); const bufferView = await engine.readPixels(0, 0, width, height); const data = new Uint8Array(bufferView.buffer, 0, bufferView.byteLength); engine.unBindFramebuffer(rtt.renderTarget); return data; } else { throw Error("Render to texture failed."); } } finally { rtt.dispose(); lodPostProcess.dispose(); } } async function GetTextureDataAsync(texture, width, height, face = 0, lod = 0) { await WhenTextureReadyAsync(texture); const { width: textureWidth, height: textureHeight } = texture.getSize(); const targetWidth = width ?? textureWidth; const targetHeight = height ?? textureHeight; if (IsCompressedTextureFormat(texture.textureFormat) || targetWidth !== textureWidth || targetHeight !== textureHeight) { return await ReadPixelsUsingRTT(texture, targetWidth, targetHeight, face, lod); } let data = await texture.readPixels(face, lod); if (!data) { throw new Error(`Failed to read pixels from texture ${texture.name}.`); } if (data instanceof Float32Array) { const data2 = new Uint8Array(data.length); let n = data.length; while (n--) { const v = data[n]; data2[n] = Math.round(Clamp(v) * 255); } data = data2; } return data; } var floatView, int32View, TextureTools; var init_textureTools = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/textureTools.js"() { init_texture(); init_renderTargetTexture(); init_passPostProcess(); init_postProcess(); init_math_scalar_functions(); __name(CreateResizedCopy, "CreateResizedCopy"); __name(ApplyPostProcess, "ApplyPostProcess"); __name(ToHalfFloat, "ToHalfFloat"); __name(FromHalfFloat, "FromHalfFloat"); __name(IsCompressedTextureFormat, "IsCompressedTextureFormat"); __name(WhenTextureReadyAsync, "WhenTextureReadyAsync"); __name(ReadPixelsUsingRTT, "ReadPixelsUsingRTT"); __name(GetTextureDataAsync, "GetTextureDataAsync"); TextureTools = { /** * Uses the GPU to create a copy texture rescaled at a given size * @param texture Texture to copy from * @param width defines the desired width * @param height defines the desired height * @param useBilinearMode defines if bilinear mode has to be used * @returns the generated texture */ CreateResizedCopy, /** * Apply a post process to a texture * @param postProcessName name of the fragment post process * @param internalTexture the texture to encode * @param scene the scene hosting the texture * @param type type of the output texture. If not provided, use the one from internalTexture * @param samplingMode sampling mode to use to sample the source texture. If not provided, use the one from internalTexture * @param format format of the output texture. If not provided, use the one from internalTexture * @returns a promise with the internalTexture having its texture replaced by the result of the processing */ ApplyPostProcess, /** * Converts a number to half float * @param value number to convert * @returns converted number */ ToHalfFloat, /** * Converts a half float to a number * @param value half float to convert * @returns converted half float */ FromHalfFloat, /** * Gets the data of the specified texture by rendering it to an intermediate RGBA texture and retrieving the bytes from it. * This is convienent to get 8-bit RGBA values for a texture in a GPU compressed format. * @param texture the source texture * @param width the width of the result, which does not have to match the source texture width * @param height the height of the result, which does not have to match the source texture height * @param face if the texture has multiple faces, the face index to use for the source * @param lod if the texture has multiple LODs, the lod index to use for the source * @returns the 8-bit texture data */ GetTextureDataAsync }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/urlTools.js function GetExtensionFromUrl(url) { const urlWithoutUriParams = url.split("?")[0]; const lastDot = urlWithoutUriParams.lastIndexOf("."); const extension = lastDot > -1 ? urlWithoutUriParams.substring(lastDot).toLowerCase() : ""; return extension; } var init_urlTools = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/urlTools.js"() { __name(GetExtensionFromUrl, "GetExtensionFromUrl"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.cubeTexture.js var init_abstractEngine_cubeTexture = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/AbstractEngine/abstractEngine.cubeTexture.js"() { init_internalTexture(); init_logger(); init_fileTools(); init_guid(); init_abstractEngine(); init_textureLoaderManager(); init_urlTools(); AbstractEngine.prototype._partialLoadFile = function(url, index, loadedFiles, onfinish, onErrorCallBack = null) { const onload = /* @__PURE__ */ __name((data) => { loadedFiles[index] = data; loadedFiles._internalCount++; if (loadedFiles._internalCount === 6) { onfinish(loadedFiles); } }, "onload"); const onerror = /* @__PURE__ */ __name((request, exception) => { if (onErrorCallBack && request) { onErrorCallBack(request.status + " " + request.statusText, exception); } }, "onerror"); this._loadFile(url, onload, void 0, void 0, true, onerror); }; AbstractEngine.prototype._cascadeLoadFiles = function(scene, onfinish, files, onError = null) { const loadedFiles = []; loadedFiles._internalCount = 0; for (let index = 0; index < 6; index++) { this._partialLoadFile(files[index], index, loadedFiles, onfinish, onError); } }; AbstractEngine.prototype._cascadeLoadImgs = function(scene, texture, onfinish, files, onError = null, mimeType) { const loadedImages = []; loadedImages._internalCount = 0; for (let index = 0; index < 6; index++) { this._partialLoadImg(files[index], index, loadedImages, scene, texture, onfinish, onError, mimeType); } }; AbstractEngine.prototype._partialLoadImg = function(url, index, loadedImages, scene, texture, onfinish, onErrorCallBack = null, mimeType) { const tokenPendingData = RandomGUID(); const onload = /* @__PURE__ */ __name((img) => { loadedImages[index] = img; loadedImages._internalCount++; if (scene) { scene.removePendingData(tokenPendingData); } if (loadedImages._internalCount === 6 && onfinish) { onfinish(texture, loadedImages); } }, "onload"); const onerror = /* @__PURE__ */ __name((message, exception) => { if (scene) { scene.removePendingData(tokenPendingData); } if (onErrorCallBack) { onErrorCallBack(message, exception); } }, "onerror"); LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null, mimeType); if (scene) { scene.addPendingData(tokenPendingData); } }; AbstractEngine.prototype.createCubeTextureBase = function(rootUrl, scene, files, noMipmap, onLoad = null, onError = null, format, forcedExtension = null, createPolynomials = false, lodScale = 0, lodOffset = 0, fallback = null, beforeLoadCubeDataCallback = null, imageHandler = null, useSRGBBuffer = false, buffer = null) { const texture = fallback ? fallback : new InternalTexture( this, 7 /* InternalTextureSource.Cube */ ); texture.isCube = true; texture.url = rootUrl; texture.generateMipMaps = !noMipmap; texture._lodGenerationScale = lodScale; texture._lodGenerationOffset = lodOffset; texture._useSRGBBuffer = !!useSRGBBuffer && this._caps.supportSRGBBuffers && (this.version > 1 || this.isWebGPU || !!noMipmap); if (texture !== fallback) { texture.label = rootUrl.substring(0, 60); } if (!this._doNotHandleContextLost) { texture._extension = forcedExtension; texture._files = files; texture._buffer = buffer; } const originalRootUrl = rootUrl; if (this._transformTextureUrl && !fallback) { rootUrl = this._transformTextureUrl(rootUrl); } const extension = forcedExtension ?? GetExtensionFromUrl(rootUrl); const loaderPromise = _GetCompatibleTextureLoader(extension); const localOnError = /* @__PURE__ */ __name((message, exception) => { texture.dispose(); if (onError) { onError(message, exception); } else if (message) { Logger.Warn(message); } }, "localOnError"); const onInternalError = /* @__PURE__ */ __name((request, exception) => { if (rootUrl === originalRootUrl) { if (request) { localOnError(request.status + " " + request.statusText, exception); } } else { Logger.Warn(`Failed to load ${rootUrl}, falling back to the ${originalRootUrl}`); this.createCubeTextureBase(originalRootUrl, scene, files, !!noMipmap, onLoad, localOnError, format, forcedExtension, createPolynomials, lodScale, lodOffset, texture, beforeLoadCubeDataCallback, imageHandler, useSRGBBuffer, buffer); } }, "onInternalError"); if (loaderPromise) { loaderPromise.then((loader) => { const onLoadData = /* @__PURE__ */ __name((data) => { if (beforeLoadCubeDataCallback) { beforeLoadCubeDataCallback(texture, data); } loader.loadCubeData(data, texture, createPolynomials, onLoad, (message, exception) => { localOnError(message, exception); }); }, "onLoadData"); if (buffer) { onLoadData(buffer); } else if (files && files.length === 6) { if (loader.supportCascades) { this._cascadeLoadFiles(scene, (images) => onLoadData(images.map((image) => new Uint8Array(image))), files, localOnError); } else { localOnError("Textures type does not support cascades."); } } else { this._loadFile(rootUrl, (data) => onLoadData(new Uint8Array(data)), void 0, scene ? scene.offlineProvider || null : void 0, true, onInternalError); } }); } else { if (!files || files.length === 0) { throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found."); } this._cascadeLoadImgs(scene, texture, (texture2, imgs) => { if (imageHandler) { imageHandler(texture2, imgs); } }, files, localOnError); } this._internalTexturesCache.push(texture); return texture; }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/dds.js var dds_exports = {}; __export(dds_exports, { DDSTools: () => DDSTools }); function FourCCToInt32(value) { return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24); } function Int32ToFourCC(value) { return String.fromCharCode(value & 255, value >> 8 & 255, value >> 16 & 255, value >> 24 & 255); } var DDS_MAGIC, DDSD_MIPMAPCOUNT, DDSCAPS2_CUBEMAP, DDPF_FOURCC, DDPF_RGB, DDPF_LUMINANCE, FOURCC_DXT1, FOURCC_DXT3, FOURCC_DXT5, FOURCC_DX10, FOURCC_D3DFMT_R16G16B16A16F, FOURCC_D3DFMT_R32G32B32A32F, DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_B8G8R8X8_UNORM, headerLengthInt, off_magic, off_size, off_flags, off_height, off_width, off_mipmapCount, off_pfFlags, off_pfFourCC, off_RGBbpp, off_RMask, off_GMask, off_BMask, off_AMask, off_caps2, off_dxgiFormat, DDSTools; var init_dds = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/dds.js"() { init_math_scalar_functions(); init_logger(); init_cubemapToSphericalPolynomial(); init_textureTools(); init_abstractEngine_cubeTexture(); DDS_MAGIC = 542327876; DDSD_MIPMAPCOUNT = 131072; DDSCAPS2_CUBEMAP = 512; DDPF_FOURCC = 4, DDPF_RGB = 64, DDPF_LUMINANCE = 131072; __name(FourCCToInt32, "FourCCToInt32"); __name(Int32ToFourCC, "Int32ToFourCC"); FOURCC_DXT1 = FourCCToInt32("DXT1"); FOURCC_DXT3 = FourCCToInt32("DXT3"); FOURCC_DXT5 = FourCCToInt32("DXT5"); FOURCC_DX10 = FourCCToInt32("DX10"); FOURCC_D3DFMT_R16G16B16A16F = 113; FOURCC_D3DFMT_R32G32B32A32F = 116; DXGI_FORMAT_R32G32B32A32_FLOAT = 2; DXGI_FORMAT_R16G16B16A16_FLOAT = 10; DXGI_FORMAT_B8G8R8X8_UNORM = 88; headerLengthInt = 31; off_magic = 0; off_size = 1; off_flags = 2; off_height = 3; off_width = 4; off_mipmapCount = 7; off_pfFlags = 20; off_pfFourCC = 21; off_RGBbpp = 22; off_RMask = 23; off_GMask = 24; off_BMask = 25; off_AMask = 26; off_caps2 = 28; off_dxgiFormat = 32; DDSTools = class _DDSTools { static { __name(this, "DDSTools"); } /** * Gets DDS information from an array buffer * @param data defines the array buffer view to read data from * @returns the DDS information */ static GetDDSInfo(data) { const header = new Int32Array(data.buffer, data.byteOffset, headerLengthInt); const extendedHeader = new Int32Array(data.buffer, data.byteOffset, headerLengthInt + 4); let mipmapCount = 1; if (header[off_flags] & DDSD_MIPMAPCOUNT) { mipmapCount = Math.max(1, header[off_mipmapCount]); } const fourCC = header[off_pfFourCC]; const dxgiFormat = fourCC === FOURCC_DX10 ? extendedHeader[off_dxgiFormat] : 0; let textureType = 0; switch (fourCC) { case FOURCC_D3DFMT_R16G16B16A16F: textureType = 2; break; case FOURCC_D3DFMT_R32G32B32A32F: textureType = 1; break; case FOURCC_DX10: if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) { textureType = 2; break; } if (dxgiFormat === DXGI_FORMAT_R32G32B32A32_FLOAT) { textureType = 1; break; } } return { width: header[off_width], height: header[off_height], mipmapCount, isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC, isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB, isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE, isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP, isCompressed: fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5, dxgiFormat, textureType }; } static _GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { const destArray = new Float32Array(dataLength); const srcData = new Uint16Array(arrayBuffer, dataOffset); let index = 0; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const srcPos = (x + y * width) * 4; destArray[index] = FromHalfFloat(srcData[srcPos]); destArray[index + 1] = FromHalfFloat(srcData[srcPos + 1]); destArray[index + 2] = FromHalfFloat(srcData[srcPos + 2]); if (_DDSTools.StoreLODInAlphaChannel) { destArray[index + 3] = lod; } else { destArray[index + 3] = FromHalfFloat(srcData[srcPos + 3]); } index += 4; } } return destArray; } static _GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { if (_DDSTools.StoreLODInAlphaChannel) { const destArray = new Uint16Array(dataLength); const srcData = new Uint16Array(arrayBuffer, dataOffset); let index = 0; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const srcPos = (x + y * width) * 4; destArray[index] = srcData[srcPos]; destArray[index + 1] = srcData[srcPos + 1]; destArray[index + 2] = srcData[srcPos + 2]; destArray[index + 3] = ToHalfFloat(lod); index += 4; } } return destArray; } return new Uint16Array(arrayBuffer, dataOffset, dataLength); } static _GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { if (_DDSTools.StoreLODInAlphaChannel) { const destArray = new Float32Array(dataLength); const srcData = new Float32Array(arrayBuffer, dataOffset); let index = 0; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const srcPos = (x + y * width) * 4; destArray[index] = srcData[srcPos]; destArray[index + 1] = srcData[srcPos + 1]; destArray[index + 2] = srcData[srcPos + 2]; destArray[index + 3] = lod; index += 4; } } return destArray; } return new Float32Array(arrayBuffer, dataOffset, dataLength); } static _GetFloatAsHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { const destArray = new Uint16Array(dataLength); const srcData = new Float32Array(arrayBuffer, dataOffset); let index = 0; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { destArray[index] = ToHalfFloat(srcData[index]); destArray[index + 1] = ToHalfFloat(srcData[index + 1]); destArray[index + 2] = ToHalfFloat(srcData[index + 2]); if (_DDSTools.StoreLODInAlphaChannel) { destArray[index + 3] = ToHalfFloat(lod); } else { destArray[index + 3] = ToHalfFloat(srcData[index + 3]); } index += 4; } } return destArray; } static _GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { const destArray = new Uint8Array(dataLength); const srcData = new Float32Array(arrayBuffer, dataOffset); let index = 0; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const srcPos = (x + y * width) * 4; destArray[index] = Clamp(srcData[srcPos]) * 255; destArray[index + 1] = Clamp(srcData[srcPos + 1]) * 255; destArray[index + 2] = Clamp(srcData[srcPos + 2]) * 255; if (_DDSTools.StoreLODInAlphaChannel) { destArray[index + 3] = lod; } else { destArray[index + 3] = Clamp(srcData[srcPos + 3]) * 255; } index += 4; } } return destArray; } static _GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, lod) { const destArray = new Uint8Array(dataLength); const srcData = new Uint16Array(arrayBuffer, dataOffset); let index = 0; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const srcPos = (x + y * width) * 4; destArray[index] = Clamp(FromHalfFloat(srcData[srcPos])) * 255; destArray[index + 1] = Clamp(FromHalfFloat(srcData[srcPos + 1])) * 255; destArray[index + 2] = Clamp(FromHalfFloat(srcData[srcPos + 2])) * 255; if (_DDSTools.StoreLODInAlphaChannel) { destArray[index + 3] = lod; } else { destArray[index + 3] = Clamp(FromHalfFloat(srcData[srcPos + 3])) * 255; } index += 4; } } return destArray; } static _GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) { const byteArray = new Uint8Array(dataLength); const srcData = new Uint8Array(arrayBuffer, dataOffset); let index = 0; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const srcPos = (x + y * width) * 4; byteArray[index] = srcData[srcPos + rOffset]; byteArray[index + 1] = srcData[srcPos + gOffset]; byteArray[index + 2] = srcData[srcPos + bOffset]; byteArray[index + 3] = srcData[srcPos + aOffset]; index += 4; } } return byteArray; } static _ExtractLongWordOrder(value) { if (value === 0 || value === 255 || value === -16777216) { return 0; } return 1 + _DDSTools._ExtractLongWordOrder(value >> 8); } static _GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) { const byteArray = new Uint8Array(dataLength); const srcData = new Uint8Array(arrayBuffer, dataOffset); let index = 0; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const srcPos = (x + y * width) * 3; byteArray[index] = srcData[srcPos + rOffset]; byteArray[index + 1] = srcData[srcPos + gOffset]; byteArray[index + 2] = srcData[srcPos + bOffset]; index += 3; } } return byteArray; } static _GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer) { const byteArray = new Uint8Array(dataLength); const srcData = new Uint8Array(arrayBuffer, dataOffset); let index = 0; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const srcPos = x + y * width; byteArray[index] = srcData[srcPos]; index++; } } return byteArray; } /** * Uploads DDS Levels to a Babylon Texture * @internal */ static UploadDDSLevels(engine, texture, data, info, loadMipmaps, faces, lodIndex = -1, currentFace, destTypeMustBeFilterable = true) { let sphericalPolynomialFaces = null; if (info.sphericalPolynomial) { sphericalPolynomialFaces = []; } const ext = !!engine.getCaps().s3tc; texture.generateMipMaps = loadMipmaps; const header = new Int32Array(data.buffer, data.byteOffset, headerLengthInt); let fourCC, width, height, dataLength = 0, dataOffset; let byteArray, mipmapCount, mip; let internalCompressedFormat = 0; let blockBytes = 1; if (header[off_magic] !== DDS_MAGIC) { Logger.Error("Invalid magic number in DDS header"); return; } if (!info.isFourCC && !info.isRGB && !info.isLuminance) { Logger.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code"); return; } if (info.isCompressed && !ext) { Logger.Error("Compressed textures are not supported on this platform."); return; } let bpp = header[off_RGBbpp]; dataOffset = header[off_size] + 4; let computeFormats = false; if (info.isFourCC) { fourCC = header[off_pfFourCC]; switch (fourCC) { case FOURCC_DXT1: blockBytes = 8; internalCompressedFormat = 33777; break; case FOURCC_DXT3: blockBytes = 16; internalCompressedFormat = 33778; break; case FOURCC_DXT5: blockBytes = 16; internalCompressedFormat = 33779; break; case FOURCC_D3DFMT_R16G16B16A16F: computeFormats = true; bpp = 64; break; case FOURCC_D3DFMT_R32G32B32A32F: computeFormats = true; bpp = 128; break; case FOURCC_DX10: { dataOffset += 5 * 4; let supported = false; switch (info.dxgiFormat) { case DXGI_FORMAT_R16G16B16A16_FLOAT: computeFormats = true; bpp = 64; supported = true; break; case DXGI_FORMAT_R32G32B32A32_FLOAT: computeFormats = true; bpp = 128; supported = true; break; case DXGI_FORMAT_B8G8R8X8_UNORM: info.isRGB = true; info.isFourCC = false; bpp = 32; supported = true; break; } if (supported) { break; } } // eslint-disable-next-line no-fallthrough default: Logger.Error(["Unsupported FourCC code:", Int32ToFourCC(fourCC)]); return; } } const rOffset = _DDSTools._ExtractLongWordOrder(header[off_RMask]); const gOffset = _DDSTools._ExtractLongWordOrder(header[off_GMask]); const bOffset = _DDSTools._ExtractLongWordOrder(header[off_BMask]); const aOffset = _DDSTools._ExtractLongWordOrder(header[off_AMask]); if (computeFormats) { internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType); } mipmapCount = 1; if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) { mipmapCount = Math.max(1, header[off_mipmapCount]); } const startFace = currentFace || 0; const caps = engine.getCaps(); for (let face = startFace; face < faces; face++) { width = header[off_width]; height = header[off_height]; for (mip = 0; mip < mipmapCount; ++mip) { if (lodIndex === -1 || lodIndex === mip) { const i = lodIndex === -1 ? mip : 0; if (!info.isCompressed && info.isFourCC) { texture.format = 5; dataLength = width * height * 4; let floatArray = null; if (engine._badOS || engine._badDesktopOS || !caps.textureHalfFloat && !caps.textureFloat) { if (bpp === 128) { floatArray = _DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i); if (sphericalPolynomialFaces && i == 0) { sphericalPolynomialFaces.push(_DDSTools._GetFloatRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i)); } } else if (bpp === 64) { floatArray = _DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i); if (sphericalPolynomialFaces && i == 0) { sphericalPolynomialFaces.push(_DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i)); } } texture.type = 0; } else { const floatAvailable = caps.textureFloat && (destTypeMustBeFilterable && caps.textureFloatLinearFiltering || !destTypeMustBeFilterable); const halfFloatAvailable = caps.textureHalfFloat && (destTypeMustBeFilterable && caps.textureHalfFloatLinearFiltering || !destTypeMustBeFilterable); const destType = (bpp === 128 || bpp === 64 && !halfFloatAvailable) && floatAvailable ? 1 : (bpp === 64 || bpp === 128 && !floatAvailable) && halfFloatAvailable ? 2 : 0; let dataGetter; let dataGetterPolynomial = null; switch (bpp) { case 128: { switch (destType) { case 1: dataGetter = _DDSTools._GetFloatRGBAArrayBuffer; dataGetterPolynomial = null; break; case 2: dataGetter = _DDSTools._GetFloatAsHalfFloatRGBAArrayBuffer; dataGetterPolynomial = _DDSTools._GetFloatRGBAArrayBuffer; break; case 0: dataGetter = _DDSTools._GetFloatAsUIntRGBAArrayBuffer; dataGetterPolynomial = _DDSTools._GetFloatRGBAArrayBuffer; break; } break; } default: { switch (destType) { case 1: dataGetter = _DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer; dataGetterPolynomial = null; break; case 2: dataGetter = _DDSTools._GetHalfFloatRGBAArrayBuffer; dataGetterPolynomial = _DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer; break; case 0: dataGetter = _DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer; dataGetterPolynomial = _DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer; break; } break; } } texture.type = destType; floatArray = dataGetter(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i); if (sphericalPolynomialFaces && i == 0) { sphericalPolynomialFaces.push(dataGetterPolynomial ? dataGetterPolynomial(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, i) : floatArray); } } if (floatArray) { engine._uploadDataToTextureDirectly(texture, floatArray, face, i); } } else if (info.isRGB) { texture.type = 0; if (bpp === 24) { texture.format = 4; dataLength = width * height * 3; byteArray = _DDSTools._GetRGBArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, rOffset, gOffset, bOffset); engine._uploadDataToTextureDirectly(texture, byteArray, face, i); } else { texture.format = 5; dataLength = width * height * 4; byteArray = _DDSTools._GetRGBAArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer, rOffset, gOffset, bOffset, aOffset); engine._uploadDataToTextureDirectly(texture, byteArray, face, i); } } else if (info.isLuminance) { const unpackAlignment = engine._getUnpackAlignement(); const unpaddedRowSize = width; const paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment; dataLength = paddedRowSize * (height - 1) + unpaddedRowSize; byteArray = _DDSTools._GetLuminanceArrayBuffer(width, height, data.byteOffset + dataOffset, dataLength, data.buffer); texture.format = 1; texture.type = 0; engine._uploadDataToTextureDirectly(texture, byteArray, face, i); } else { dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes; byteArray = new Uint8Array(data.buffer, data.byteOffset + dataOffset, dataLength); texture.type = 0; engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i); } } dataOffset += bpp ? width * height * (bpp / 8) : dataLength; width *= 0.5; height *= 0.5; width = Math.max(1, width); height = Math.max(1, height); } if (currentFace !== void 0) { break; } } if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) { info.sphericalPolynomial = CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({ size: header[off_width], right: sphericalPolynomialFaces[0], left: sphericalPolynomialFaces[1], up: sphericalPolynomialFaces[2], down: sphericalPolynomialFaces[3], front: sphericalPolynomialFaces[4], back: sphericalPolynomialFaces[5], format: 5, type: 1, gammaSpace: false }); } else { info.sphericalPolynomial = void 0; } } }; DDSTools.StoreLODInAlphaChannel = false; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader.js var ddsTextureLoader_exports = {}; __export(ddsTextureLoader_exports, { _DDSTextureLoader: () => _DDSTextureLoader }); var _DDSTextureLoader; var init_ddsTextureLoader = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/ddsTextureLoader.js"() { init_sphericalPolynomial(); init_dds(); _DDSTextureLoader = class { static { __name(this, "_DDSTextureLoader"); } constructor() { this.supportCascades = true; } /** * Uploads the cube texture data to the WebGL texture. It has already been bound. * @param imgs contains the cube maps * @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 */ loadCubeData(imgs, texture, createPolynomials, onLoad) { const engine = texture.getEngine(); let info; let loadMipmap = false; let maxLevel = 1e3; if (Array.isArray(imgs)) { for (let index = 0; index < imgs.length; index++) { const data = imgs[index]; info = DDSTools.GetDDSInfo(data); texture.width = info.width; texture.height = info.height; loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps; engine._unpackFlipY(info.isCompressed); DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6, -1, index); if (!info.isFourCC && info.mipmapCount === 1) { engine.generateMipMapsForCubemap(texture); } else { maxLevel = info.mipmapCount - 1; } } } else { const data = imgs; info = DDSTools.GetDDSInfo(data); texture.width = info.width; texture.height = info.height; if (createPolynomials) { info.sphericalPolynomial = new SphericalPolynomial(); } loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps; engine._unpackFlipY(info.isCompressed); DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6); if (!info.isFourCC && info.mipmapCount === 1) { engine.generateMipMapsForCubemap(texture, false); } else { maxLevel = info.mipmapCount - 1; } } engine._setCubeMapTextureParams(texture, loadMipmap, maxLevel); texture.isReady = true; texture.onLoadedObservable.notifyObservers(texture); texture.onLoadedObservable.clear(); if (onLoad) { onLoad({ isDDS: true, width: texture.width, info, data: imgs, 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 */ loadData(data, texture, callback) { const info = DDSTools.GetDDSInfo(data); const loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && Math.max(info.width, info.height) >> info.mipmapCount - 1 === 1; callback(info.width, info.height, loadMipmap, info.isFourCC, () => { DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1); }); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/basisWorker.js function workerFunction() { const _BASIS_FORMAT = { cTFETC1: 0, cTFETC2: 1, cTFBC1: 2, cTFBC3: 3, cTFBC4: 4, cTFBC5: 5, cTFBC7: 6, cTFPVRTC1_4_RGB: 8, cTFPVRTC1_4_RGBA: 9, cTFASTC_4x4: 10, cTFATC_RGB: 11, cTFATC_RGBA_INTERPOLATED_ALPHA: 12, cTFRGBA32: 13, cTFRGB565: 14, cTFBGR565: 15, cTFRGBA4444: 16, cTFFXT1_RGB: 17, cTFPVRTC2_4_RGB: 18, cTFPVRTC2_4_RGBA: 19, cTFETC2_EAC_R11: 20, cTFETC2_EAC_RG11: 21 }; let transcoderModulePromise = null; onmessage = /* @__PURE__ */ __name((event) => { if (event.data.action === "init") { if (event.data.url) { try { importScripts(event.data.url); } catch (e) { postMessage({ action: "error", error: e }); } } if (!transcoderModulePromise) { transcoderModulePromise = BASIS({ // Override wasm binary wasmBinary: event.data.wasmBinary }); } if (transcoderModulePromise !== null) { transcoderModulePromise.then((m) => { BASIS = m; m.initializeBasis(); postMessage({ action: "init" }); }); } } else if (event.data.action === "transcode") { const config = event.data.config; const imgData = event.data.imageData; const loadedFile = new BASIS.BasisFile(imgData); const fileInfo = GetFileInfo2(loadedFile); let format = event.data.ignoreSupportedFormats ? null : GetSupportedTranscodeFormat(event.data.config, fileInfo); let needsConversion = false; if (format === null) { needsConversion = true; format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFBC3 : _BASIS_FORMAT.cTFBC1; } let success = true; if (!loadedFile.startTranscoding()) { success = false; } const buffers = []; for (let imageIndex = 0; imageIndex < fileInfo.images.length; imageIndex++) { if (!success) { break; } const image = fileInfo.images[imageIndex]; if (config.loadSingleImage === void 0 || config.loadSingleImage === imageIndex) { let mipCount = image.levels.length; if (config.loadMipmapLevels === false) { mipCount = 1; } for (let levelIndex = 0; levelIndex < mipCount; levelIndex++) { const levelInfo = image.levels[levelIndex]; const pixels = TranscodeLevel(loadedFile, imageIndex, levelIndex, format, needsConversion); if (!pixels) { success = false; break; } levelInfo.transcodedPixels = pixels; buffers.push(levelInfo.transcodedPixels.buffer); } } } loadedFile.close(); loadedFile.delete(); if (needsConversion) { format = -1; } if (!success) { postMessage({ action: "transcode", success, id: event.data.id }); } else { postMessage({ action: "transcode", success, id: event.data.id, fileInfo, format }, buffers); } } }, "onmessage"); function GetSupportedTranscodeFormat(config, fileInfo) { let format = null; if (config.supportedCompressionFormats) { if (config.supportedCompressionFormats.astc) { format = _BASIS_FORMAT.cTFASTC_4x4; } else if (config.supportedCompressionFormats.bc7) { format = _BASIS_FORMAT.cTFBC7; } else if (config.supportedCompressionFormats.s3tc) { format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFBC3 : _BASIS_FORMAT.cTFBC1; } else if (config.supportedCompressionFormats.pvrtc) { format = fileInfo.hasAlpha ? _BASIS_FORMAT.cTFPVRTC1_4_RGBA : _BASIS_FORMAT.cTFPVRTC1_4_RGB; } else if (config.supportedCompressionFormats.etc2) { format = _BASIS_FORMAT.cTFETC2; } else if (config.supportedCompressionFormats.etc1) { format = _BASIS_FORMAT.cTFETC1; } else { format = _BASIS_FORMAT.cTFRGB565; } } return format; } __name(GetSupportedTranscodeFormat, "GetSupportedTranscodeFormat"); function GetFileInfo2(basisFile) { const hasAlpha = basisFile.getHasAlpha(); const imageCount = basisFile.getNumImages(); const images = []; for (let i = 0; i < imageCount; i++) { const imageInfo = { levels: [] }; const levelCount = basisFile.getNumLevels(i); for (let level = 0; level < levelCount; level++) { const levelInfo = { width: basisFile.getImageWidth(i, level), height: basisFile.getImageHeight(i, level) }; imageInfo.levels.push(levelInfo); } images.push(imageInfo); } const info = { hasAlpha, images }; return info; } __name(GetFileInfo2, "GetFileInfo"); function TranscodeLevel(loadedFile, imageIndex, levelIndex, format, convertToRgb565) { const dstSize = loadedFile.getImageTranscodedSizeInBytes(imageIndex, levelIndex, format); let dst = new Uint8Array(dstSize); if (!loadedFile.transcodeImage(dst, imageIndex, levelIndex, format, 1, 0)) { return null; } if (convertToRgb565) { const alignedWidth = loadedFile.getImageWidth(imageIndex, levelIndex) + 3 & ~3; const alignedHeight = loadedFile.getImageHeight(imageIndex, levelIndex) + 3 & ~3; dst = ConvertDxtToRgb565(dst, 0, alignedWidth, alignedHeight); } return dst; } __name(TranscodeLevel, "TranscodeLevel"); function ConvertDxtToRgb565(src, srcByteOffset, width, height) { const c = new Uint16Array(4); const dst = new Uint16Array(width * height); const blockWidth = width / 4; const blockHeight = height / 4; for (let blockY = 0; blockY < blockHeight; blockY++) { for (let blockX = 0; blockX < blockWidth; blockX++) { const i = srcByteOffset + 8 * (blockY * blockWidth + blockX); c[0] = src[i] | src[i + 1] << 8; c[1] = src[i + 2] | src[i + 3] << 8; c[2] = (2 * (c[0] & 31) + 1 * (c[1] & 31)) / 3 | (2 * (c[0] & 2016) + 1 * (c[1] & 2016)) / 3 & 2016 | (2 * (c[0] & 63488) + 1 * (c[1] & 63488)) / 3 & 63488; c[3] = (2 * (c[1] & 31) + 1 * (c[0] & 31)) / 3 | (2 * (c[1] & 2016) + 1 * (c[0] & 2016)) / 3 & 2016 | (2 * (c[1] & 63488) + 1 * (c[0] & 63488)) / 3 & 63488; for (let row = 0; row < 4; row++) { const m = src[i + 4 + row]; let dstI = (blockY * 4 + row) * width + blockX * 4; dst[dstI++] = c[m & 3]; dst[dstI++] = c[m >> 2 & 3]; dst[dstI++] = c[m >> 4 & 3]; dst[dstI++] = c[m >> 6 & 3]; } } } return dst; } __name(ConvertDxtToRgb565, "ConvertDxtToRgb565"); } async function initializeWebWorker(worker, wasmBinary, moduleUrl) { return await new Promise((res, reject) => { const initHandler = /* @__PURE__ */ __name((msg) => { if (msg.data.action === "init") { worker.removeEventListener("message", initHandler); res(worker); } else if (msg.data.action === "error") { reject(msg.data.error || "error initializing worker"); } }, "initHandler"); worker.addEventListener("message", initHandler); worker.postMessage({ action: "init", url: moduleUrl ? Tools.GetBabylonScriptURL(moduleUrl) : void 0, wasmBinary }, [wasmBinary]); }); } var init_basisWorker = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/basisWorker.js"() { init_tools(); __name(workerFunction, "workerFunction"); __name(initializeWebWorker, "initializeWebWorker"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/basis.js var BasisFileInfo, TranscodeResult, BasisTranscodeConfiguration, BASIS_FORMATS, BasisToolsOptions, GetInternalFormatFromBasisFormat, WorkerPromise, LocalWorker, ActionId, IgnoreSupportedFormats, CreateWorkerAsync, SetBasisTranscoderWorker, TranscodeAsync, BindTexture, LoadTextureFromTranscodeResult, BasisTools; var init_basis = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/basis.js"() { init_tools(); init_texture(); init_internalTexture(); init_basisWorker(); BasisFileInfo = class { static { __name(this, "BasisFileInfo"); } }; TranscodeResult = class { static { __name(this, "TranscodeResult"); } }; BasisTranscodeConfiguration = class { static { __name(this, "BasisTranscodeConfiguration"); } }; (function(BASIS_FORMATS2) { BASIS_FORMATS2[BASIS_FORMATS2["cTFETC1"] = 0] = "cTFETC1"; BASIS_FORMATS2[BASIS_FORMATS2["cTFETC2"] = 1] = "cTFETC2"; BASIS_FORMATS2[BASIS_FORMATS2["cTFBC1"] = 2] = "cTFBC1"; BASIS_FORMATS2[BASIS_FORMATS2["cTFBC3"] = 3] = "cTFBC3"; BASIS_FORMATS2[BASIS_FORMATS2["cTFBC4"] = 4] = "cTFBC4"; BASIS_FORMATS2[BASIS_FORMATS2["cTFBC5"] = 5] = "cTFBC5"; BASIS_FORMATS2[BASIS_FORMATS2["cTFBC7"] = 6] = "cTFBC7"; BASIS_FORMATS2[BASIS_FORMATS2["cTFPVRTC1_4_RGB"] = 8] = "cTFPVRTC1_4_RGB"; BASIS_FORMATS2[BASIS_FORMATS2["cTFPVRTC1_4_RGBA"] = 9] = "cTFPVRTC1_4_RGBA"; BASIS_FORMATS2[BASIS_FORMATS2["cTFASTC_4x4"] = 10] = "cTFASTC_4x4"; BASIS_FORMATS2[BASIS_FORMATS2["cTFATC_RGB"] = 11] = "cTFATC_RGB"; BASIS_FORMATS2[BASIS_FORMATS2["cTFATC_RGBA_INTERPOLATED_ALPHA"] = 12] = "cTFATC_RGBA_INTERPOLATED_ALPHA"; BASIS_FORMATS2[BASIS_FORMATS2["cTFRGBA32"] = 13] = "cTFRGBA32"; BASIS_FORMATS2[BASIS_FORMATS2["cTFRGB565"] = 14] = "cTFRGB565"; BASIS_FORMATS2[BASIS_FORMATS2["cTFBGR565"] = 15] = "cTFBGR565"; BASIS_FORMATS2[BASIS_FORMATS2["cTFRGBA4444"] = 16] = "cTFRGBA4444"; BASIS_FORMATS2[BASIS_FORMATS2["cTFFXT1_RGB"] = 17] = "cTFFXT1_RGB"; BASIS_FORMATS2[BASIS_FORMATS2["cTFPVRTC2_4_RGB"] = 18] = "cTFPVRTC2_4_RGB"; BASIS_FORMATS2[BASIS_FORMATS2["cTFPVRTC2_4_RGBA"] = 19] = "cTFPVRTC2_4_RGBA"; BASIS_FORMATS2[BASIS_FORMATS2["cTFETC2_EAC_R11"] = 20] = "cTFETC2_EAC_R11"; BASIS_FORMATS2[BASIS_FORMATS2["cTFETC2_EAC_RG11"] = 21] = "cTFETC2_EAC_RG11"; })(BASIS_FORMATS || (BASIS_FORMATS = {})); BasisToolsOptions = { /** * URL to use when loading the basis transcoder */ JSModuleURL: `${Tools._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.js`, /** * URL to use when loading the wasm module for the transcoder */ WasmModuleURL: `${Tools._DefaultCdnUrl}/basisTranscoder/1/basis_transcoder.wasm` }; GetInternalFormatFromBasisFormat = /* @__PURE__ */ __name((basisFormat, engine) => { let format; switch (basisFormat) { case BASIS_FORMATS.cTFETC1: format = 36196; break; case BASIS_FORMATS.cTFBC1: format = 33776; break; case BASIS_FORMATS.cTFBC4: format = 33779; break; case BASIS_FORMATS.cTFASTC_4x4: format = 37808; break; case BASIS_FORMATS.cTFETC2: format = 37496; break; case BASIS_FORMATS.cTFBC7: format = 36492; break; } if (format === void 0) { throw "The chosen Basis transcoder format is not currently supported"; } return format; }, "GetInternalFormatFromBasisFormat"); WorkerPromise = null; LocalWorker = null; ActionId = 0; IgnoreSupportedFormats = false; CreateWorkerAsync = /* @__PURE__ */ __name(async () => { if (!WorkerPromise) { WorkerPromise = new Promise((res, reject) => { if (LocalWorker) { res(LocalWorker); } else { Tools.LoadFileAsync(Tools.GetBabylonScriptURL(BasisToolsOptions.WasmModuleURL)).then((wasmBinary) => { if (typeof URL !== "function") { return reject("Basis transcoder requires an environment with a URL constructor"); } const workerBlobUrl = URL.createObjectURL(new Blob([`(${workerFunction})()`], { type: "application/javascript" })); LocalWorker = new Worker(workerBlobUrl); initializeWebWorker(LocalWorker, wasmBinary, BasisToolsOptions.JSModuleURL).then(res, reject); }).catch(reject); } }); } return await WorkerPromise; }, "CreateWorkerAsync"); SetBasisTranscoderWorker = /* @__PURE__ */ __name((worker) => { LocalWorker = worker; }, "SetBasisTranscoderWorker"); TranscodeAsync = /* @__PURE__ */ __name(async (data, config) => { const dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data; return await new Promise((res, rej) => { CreateWorkerAsync().then(() => { const actionId = ActionId++; const messageHandler = /* @__PURE__ */ __name((msg) => { if (msg.data.action === "transcode" && msg.data.id === actionId) { LocalWorker.removeEventListener("message", messageHandler); if (!msg.data.success) { rej("Transcode is not supported on this device"); } else { res(msg.data); } } }, "messageHandler"); LocalWorker.addEventListener("message", messageHandler); const dataViewCopy = new Uint8Array(dataView.byteLength); dataViewCopy.set(new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength)); LocalWorker.postMessage({ action: "transcode", id: actionId, imageData: dataViewCopy, config, ignoreSupportedFormats: IgnoreSupportedFormats }, [ dataViewCopy.buffer ]); }, (error) => { rej(error); }); }); }, "TranscodeAsync"); BindTexture = /* @__PURE__ */ __name((texture, engine) => { let target = engine._gl?.TEXTURE_2D; if (texture.isCube) { target = engine._gl?.TEXTURE_CUBE_MAP; } engine._bindTextureDirectly(target, texture, true); }, "BindTexture"); LoadTextureFromTranscodeResult = /* @__PURE__ */ __name((texture, transcodeResult) => { const engine = texture.getEngine(); for (let i = 0; i < transcodeResult.fileInfo.images.length; i++) { const rootImage = transcodeResult.fileInfo.images[i].levels[0]; texture._invertVScale = texture.invertY; if (transcodeResult.format === -1 || transcodeResult.format === BASIS_FORMATS.cTFRGB565) { texture.type = 10; texture.format = 4; if (engine._features.basisNeedsPOT && (Math.log2(rootImage.width) % 1 !== 0 || Math.log2(rootImage.height) % 1 !== 0)) { const source = new InternalTexture( engine, 2 /* InternalTextureSource.Temp */ ); texture._invertVScale = texture.invertY; source.type = 10; source.format = 4; source.width = rootImage.width + 3 & ~3; source.height = rootImage.height + 3 & ~3; BindTexture(source, engine); engine._uploadDataToTextureDirectly(source, new Uint16Array(rootImage.transcodedPixels.buffer), i, 0, 4, true); engine._rescaleTexture(source, texture, engine.scenes[0], engine._getInternalFormat(4), () => { engine._releaseTexture(source); BindTexture(texture, engine); }); } else { texture._invertVScale = !texture.invertY; texture.width = rootImage.width + 3 & ~3; texture.height = rootImage.height + 3 & ~3; texture.samplingMode = 2; BindTexture(texture, engine); engine._uploadDataToTextureDirectly(texture, new Uint16Array(rootImage.transcodedPixels.buffer), i, 0, 4, true); } } else { texture.width = rootImage.width; texture.height = rootImage.height; texture.generateMipMaps = transcodeResult.fileInfo.images[i].levels.length > 1; const format = BasisTools.GetInternalFormatFromBasisFormat(transcodeResult.format, engine); texture.format = format; BindTexture(texture, engine); const levels = transcodeResult.fileInfo.images[i].levels; for (let index = 0; index < levels.length; index++) { const level = levels[index]; engine._uploadCompressedDataToTextureDirectly(texture, format, level.width, level.height, level.transcodedPixels, i, index); } if (engine._features.basisNeedsPOT && (Math.log2(texture.width) % 1 !== 0 || Math.log2(texture.height) % 1 !== 0)) { Tools.Warn("Loaded .basis texture width and height are not a power of two. Texture wrapping will be set to Texture.CLAMP_ADDRESSMODE as other modes are not supported with non power of two dimensions in webGL 1."); texture._cachedWrapU = Texture.CLAMP_ADDRESSMODE; texture._cachedWrapV = Texture.CLAMP_ADDRESSMODE; } } } }, "LoadTextureFromTranscodeResult"); BasisTools = { /** * URL to use when loading the basis transcoder */ JSModuleURL: BasisToolsOptions.JSModuleURL, /** * URL to use when loading the wasm module for the transcoder */ WasmModuleURL: BasisToolsOptions.WasmModuleURL, /** * Get the internal format to be passed to texImage2D corresponding to the .basis format value * @param basisFormat format chosen from GetSupportedTranscodeFormat * @returns internal format corresponding to the Basis format */ GetInternalFormatFromBasisFormat, /** * Transcodes a loaded image file to compressed pixel data * @param data image data to transcode * @param config configuration options for the transcoding * @returns a promise resulting in the transcoded image */ TranscodeAsync, /** * Loads a texture from the transcode result * @param texture texture load to * @param transcodeResult the result of transcoding the basis file to load from */ LoadTextureFromTranscodeResult }; Object.defineProperty(BasisTools, "JSModuleURL", { get: /* @__PURE__ */ __name(function() { return BasisToolsOptions.JSModuleURL; }, "get"), set: /* @__PURE__ */ __name(function(value) { BasisToolsOptions.JSModuleURL = value; }, "set") }); Object.defineProperty(BasisTools, "WasmModuleURL", { get: /* @__PURE__ */ __name(function() { return BasisToolsOptions.WasmModuleURL; }, "get"), set: /* @__PURE__ */ __name(function(value) { BasisToolsOptions.WasmModuleURL = value; }, "set") }); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/basisTextureLoader.js var basisTextureLoader_exports = {}; __export(basisTextureLoader_exports, { _BasisTextureLoader: () => _BasisTextureLoader }); var _BasisTextureLoader; var init_basisTextureLoader = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/basisTextureLoader.js"() { init_basis(); init_tools(); _BasisTextureLoader = class { static { __name(this, "_BasisTextureLoader"); } constructor() { this.supportCascades = false; } /** * 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 */ loadCubeData(data, texture, createPolynomials, onLoad, onError) { if (Array.isArray(data)) { return; } const caps = texture.getEngine().getCaps(); const transcodeConfig = { supportedCompressionFormats: { etc1: caps.etc1 ? true : false, s3tc: caps.s3tc ? true : false, pvrtc: caps.pvrtc ? true : false, etc2: caps.etc2 ? true : false, astc: caps.astc ? true : false, bc7: caps.bptc ? true : false } }; TranscodeAsync(data, transcodeConfig).then((result) => { const hasMipmap = result.fileInfo.images[0].levels.length > 1 && texture.generateMipMaps; LoadTextureFromTranscodeResult(texture, result); texture.getEngine()._setCubeMapTextureParams(texture, hasMipmap); texture.isReady = true; texture.onLoadedObservable.notifyObservers(texture); texture.onLoadedObservable.clear(); if (onLoad) { onLoad(); } }).catch((err) => { const errorMessage = "Failed to transcode Basis file, transcoding may not be supported on this device"; Tools.Warn(errorMessage); texture.isReady = true; if (onError) { onError(err); } }); } /** * 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 */ loadData(data, texture, callback) { const caps = texture.getEngine().getCaps(); const transcodeConfig = { supportedCompressionFormats: { etc1: caps.etc1 ? true : false, s3tc: caps.s3tc ? true : false, pvrtc: caps.pvrtc ? true : false, etc2: caps.etc2 ? true : false, astc: caps.astc ? true : false, bc7: caps.bptc ? true : false } }; TranscodeAsync(data, transcodeConfig).then((result) => { const rootImage = result.fileInfo.images[0].levels[0]; const hasMipmap = result.fileInfo.images[0].levels.length > 1 && texture.generateMipMaps; callback(rootImage.width, rootImage.height, hasMipmap, result.format !== -1, () => { LoadTextureFromTranscodeResult(texture, result); }); }).catch((err) => { Tools.Warn("Failed to transcode Basis file, transcoding may not be supported on this device"); Tools.Warn(`Failed to transcode Basis file: ${err}`); callback(0, 0, false, false, () => { }, true); }); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/helperFunctions.js var name11, shader11, helperFunctionsWGSL; var init_helperFunctions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/helperFunctions.js"() { init_shaderStore(); name11 = "helperFunctions"; shader11 = `const PI: f32=3.1415926535897932384626433832795;const TWO_PI: f32=6.283185307179586;const HALF_PI: f32=1.5707963267948966;const RECIPROCAL_PI: f32=0.3183098861837907;const RECIPROCAL_PI2: f32=0.15915494309189535;const RECIPROCAL_PI4: f32=0.07957747154594767;const HALF_MIN: f32=5.96046448e-08; const LinearEncodePowerApprox: f32=2.2;const GammaEncodePowerApprox: f32=1.0/LinearEncodePowerApprox;const LuminanceEncodeApprox: vec3f=vec3f(0.2126,0.7152,0.0722);const Epsilon:f32=0.0000001;fn square(x: f32)->f32 {return x*x;} fn saturate(x: f32)->f32 {return clamp(x,0.0,1.0);} fn saturateVec3(x: vec3f)->vec3f {return clamp(x,vec3f(),vec3f(1.0));} fn saturateEps(x: f32)->f32 {return clamp(x,Epsilon,1.0);} fn maxEps(x: f32)->f32 {return max(x,Epsilon);} fn maxEpsVec3(x: vec3f)->vec3f {return max(x,vec3f(Epsilon));} fn absEps(x: f32)->f32 {return abs(x)+Epsilon;} fn transposeMat3(inMatrix: mat3x3f)->mat3x3f {let i0: vec3f=inMatrix[0];let i1: vec3f=inMatrix[1];let i2: vec3f=inMatrix[2];let outMatrix:mat3x3f=mat3x3f( vec3(i0.x,i1.x,i2.x), vec3(i0.y,i1.y,i2.y), vec3(i0.z,i1.z,i2.z) );return outMatrix;} fn inverseMat3(inMatrix: mat3x3f)->mat3x3f {let a00: f32=inMatrix[0][0];let a01: f32=inMatrix[0][1];let a02: f32=inMatrix[0][2];let a10: f32=inMatrix[1][0];let a11: f32=inMatrix[1][1];let a12: f32=inMatrix[1][2];let a20: f32=inMatrix[2][0];let a21: f32=inMatrix[2][1];let a22: f32=inMatrix[2][2];let b01: f32=a22*a11-a12*a21;let b11: f32=-a22*a10+a12*a20;let b21: f32=a21*a10-a11*a20;let det: f32=a00*b01+a01*b11+a02*b21;return mat3x3f(b01/det,(-a22*a01+a02*a21)/det,(a12*a01-a02*a11)/det, b11/det,(a22*a00-a02*a20)/det,(-a12*a00+a02*a10)/det, b21/det,(-a21*a00+a01*a20)/det,(a11*a00-a01*a10)/det);} #if USE_EXACT_SRGB_CONVERSIONS fn toLinearSpaceExact(color: vec3f)->vec3f {let nearZeroSection: vec3f=0.0773993808*color;let remainingSection: vec3f=pow(0.947867299*(color+vec3f(0.055)),vec3f(2.4));return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3f(0.04045)));} fn toGammaSpaceExact(color: vec3f)->vec3f {let nearZeroSection: vec3f=12.92*color;let remainingSection: vec3f=1.055*pow(color,vec3f(0.41666))-vec3f(0.055);return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3f(0.0031308)));} #endif fn toLinearSpace(color: f32)->f32 { #if USE_EXACT_SRGB_CONVERSIONS var nearZeroSection=0.0773993808*color;var remainingSection=pow(0.947867299*(color+0.055),2.4);return select(remainingSection,nearZeroSection,color<=0.04045); #else return pow(color,LinearEncodePowerApprox); #endif } fn toLinearSpaceVec3(color: vec3f)->vec3f { #if USE_EXACT_SRGB_CONVERSIONS return toLinearSpaceExact(color); #else return pow(color,vec3f(LinearEncodePowerApprox)); #endif } fn toLinearSpaceVec4(color: vec4)->vec4 { #if USE_EXACT_SRGB_CONVERSIONS return vec4f(toLinearSpaceExact(color.rgb),color.a); #else return vec4f(pow(color.rgb,vec3f(LinearEncodePowerApprox)),color.a); #endif } fn toGammaSpace(color: vec4)->vec4 { #if USE_EXACT_SRGB_CONVERSIONS return vec4(toGammaSpaceExact(color.rgb),color.a); #else return vec4(pow(color.rgb,vec3f(GammaEncodePowerApprox)),color.a); #endif } fn toGammaSpaceVec3(color: vec3f)->vec3f { #if USE_EXACT_SRGB_CONVERSIONS return toGammaSpaceExact(color); #else return pow(color,vec3f(GammaEncodePowerApprox)); #endif } fn squareVec3(value: vec3f)->vec3f {return value*value;} fn pow5(value: f32)->f32 {let sq: f32=value*value;return sq*sq*value;} fn getLuminance(color: vec3f)->f32 {return saturate(dot(color,LuminanceEncodeApprox));} fn getRand(seed: vec2)->f32 {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} fn dither(seed: vec2,varianceAmount: f32)->f32 {let rand: f32=getRand(seed);let normVariance: f32=varianceAmount/255.0;let dither: f32=mix(-normVariance,normVariance,rand);return dither;} const rgbdMaxRange: f32=255.0;fn toRGBD(color: vec3f)->vec4 {let maxRGB: f32=max(max(color.r,max(color.g,color.b)),Epsilon);var D: f32 =max(rgbdMaxRange/maxRGB,1.);D =clamp(floor(D)/255.0,0.,1.);var rgb: vec3f =color.rgb*D;rgb=toGammaSpaceVec3(rgb);return vec4(saturateVec3(rgb),D);} fn fromRGBD(rgbd: vec4)->vec3f {let rgb=toLinearSpaceVec3(rgbd.rgb);return rgb/rgbd.a;} fn parallaxCorrectNormal(vertexPos: vec3f,origVec: vec3f,cubeSize: vec3f,cubePos: vec3f)->vec3f {let invOrigVec: vec3f=vec3f(1.)/origVec;let halfSize: vec3f=cubeSize*0.5;let intersecAtMaxPlane: vec3f=(cubePos+halfSize-vertexPos)*invOrigVec;let intersecAtMinPlane: vec3f=(cubePos-halfSize-vertexPos)*invOrigVec;let largestIntersec: vec3f=max(intersecAtMaxPlane,intersecAtMinPlane);let distance: f32=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);let intersectPositionWS: vec3f=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} fn equirectangularToCubemapDirection(uv : vec2f)->vec3f {var longitude : f32=uv.x*TWO_PI-PI;var latitude : f32=HALF_PI-uv.y*PI;var direction : vec3f;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;} fn sqrtClamped(value: f32)->f32 {return sqrt(max(value,0.));} fn avg(value: vec3f)->f32 {return dot(value,vec3f(0.333333333));} `; if (!ShaderStore.IncludesShadersStoreWGSL[name11]) { ShaderStore.IncludesShadersStoreWGSL[name11] = shader11; } helperFunctionsWGSL = { name: name11, shader: shader11 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/rgbdDecode.fragment.js var rgbdDecode_fragment_exports = {}; __export(rgbdDecode_fragment_exports, { rgbdDecodePixelShaderWGSL: () => rgbdDecodePixelShaderWGSL }); var name12, shader12, rgbdDecodePixelShaderWGSL; var init_rgbdDecode_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/rgbdDecode.fragment.js"() { init_shaderStore(); init_helperFunctions(); name12 = "rgbdDecodePixelShader"; shader12 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(fromRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV)),1.0);}`; if (!ShaderStore.ShadersStoreWGSL[name12]) { ShaderStore.ShadersStoreWGSL[name12] = shader12; } rgbdDecodePixelShaderWGSL = { name: name12, shader: shader12 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/helperFunctions.js var name13, shader13, helperFunctions; var init_helperFunctions2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/helperFunctions.js"() { init_shaderStore(); name13 = "helperFunctions"; shader13 = `const float PI=3.1415926535897932384626433832795;const float TWO_PI=6.283185307179586;const float HALF_PI=1.5707963267948966;const float RECIPROCAL_PI=0.3183098861837907;const float RECIPROCAL_PI2=0.15915494309189535;const float RECIPROCAL_PI4=0.07957747154594767;const float HALF_MIN=5.96046448e-08; const float LinearEncodePowerApprox=2.2;const float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;const vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);const float Epsilon=0.0000001; #define saturate(x) clamp(x,0.0,1.0) #define absEps(x) abs(x)+Epsilon #define maxEps(x) max(x,Epsilon) #define saturateEps(x) clamp(x,Epsilon,1.0) mat3 transposeMat3(mat3 inMatrix) {vec3 i0=inMatrix[0];vec3 i1=inMatrix[1];vec3 i2=inMatrix[2];mat3 outMatrix=mat3( vec3(i0.x,i1.x,i2.x), vec3(i0.y,i1.y,i2.y), vec3(i0.z,i1.z,i2.z) );return outMatrix;} mat3 inverseMat3(mat3 inMatrix) {float a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];float a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];float a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];float b01=a22*a11-a12*a21;float b11=-a22*a10+a12*a20;float b21=a21*a10-a11*a20;float det=a00*b01+a01*b11+a02*b21;return mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11), b11,(a22*a00-a02*a20),(-a12*a00+a02*a10), b21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;} #if USE_EXACT_SRGB_CONVERSIONS vec3 toLinearSpaceExact(vec3 color) {vec3 nearZeroSection=0.0773993808*color;vec3 remainingSection=pow(0.947867299*(color+vec3(0.055)),vec3(2.4)); #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.04045))); #else return vec3( color.r<=0.04045 ? nearZeroSection.r : remainingSection.r, color.g<=0.04045 ? nearZeroSection.g : remainingSection.g, color.b<=0.04045 ? nearZeroSection.b : remainingSection.b); #endif } vec3 toGammaSpaceExact(vec3 color) {vec3 nearZeroSection=12.92*color;vec3 remainingSection=1.055*pow(color,vec3(0.41666))-vec3(0.055); #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) return mix(remainingSection,nearZeroSection,lessThanEqual(color,vec3(0.0031308))); #else return vec3( color.r<=0.0031308 ? nearZeroSection.r : remainingSection.r, color.g<=0.0031308 ? nearZeroSection.g : remainingSection.g, color.b<=0.0031308 ? nearZeroSection.b : remainingSection.b); #endif } #endif float toLinearSpace(float color) { #if USE_EXACT_SRGB_CONVERSIONS float nearZeroSection=0.0773993808*color;float remainingSection=pow(0.947867299*(color+0.055),2.4);return color<=0.04045 ? nearZeroSection : remainingSection; #else return pow(color,LinearEncodePowerApprox); #endif } vec3 toLinearSpace(vec3 color) { #if USE_EXACT_SRGB_CONVERSIONS return toLinearSpaceExact(color); #else return pow(color,vec3(LinearEncodePowerApprox)); #endif } vec4 toLinearSpace(vec4 color) { #if USE_EXACT_SRGB_CONVERSIONS return vec4(toLinearSpaceExact(color.rgb),color.a); #else return vec4(pow(color.rgb,vec3(LinearEncodePowerApprox)),color.a); #endif } float toGammaSpace(float color) { #if USE_EXACT_SRGB_CONVERSIONS float nearZeroSection=12.92*color;float remainingSection=1.055*pow(color,0.41666)-0.055;return color<=0.0031308 ? nearZeroSection : remainingSection; #else return pow(color,GammaEncodePowerApprox); #endif } vec3 toGammaSpace(vec3 color) { #if USE_EXACT_SRGB_CONVERSIONS return toGammaSpaceExact(color); #else return pow(color,vec3(GammaEncodePowerApprox)); #endif } vec4 toGammaSpace(vec4 color) { #if USE_EXACT_SRGB_CONVERSIONS return vec4(toGammaSpaceExact(color.rgb),color.a); #else return vec4(pow(color.rgb,vec3(GammaEncodePowerApprox)),color.a); #endif } float square(float value) {return value*value;} vec3 square(vec3 value) {return value*value;} float pow5(float value) {float sq=value*value;return sq*sq*value;} float getLuminance(vec3 color) {return saturate(dot(color,LuminanceEncodeApprox));} float getRand(vec2 seed) {return fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);} float dither(vec2 seed,float varianceAmount) {float rand=getRand(seed);float normVariance=varianceAmount/255.0;float dither=mix(-normVariance,normVariance,rand);return dither;} const float rgbdMaxRange=255.;vec4 toRGBD(vec3 color) {float maxRGB=maxEps(max(color.r,max(color.g,color.b)));float D =max(rgbdMaxRange/maxRGB,1.);D =saturate(floor(D)/255.);vec3 rgb=color.rgb*D;rgb=toGammaSpace(rgb);return vec4(saturate(rgb),D);} vec3 fromRGBD(vec4 rgbd) {rgbd.rgb=toLinearSpace(rgbd.rgb);return rgbd.rgb/rgbd.a;} vec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {vec3 invOrigVec=vec3(1.)/origVec;vec3 halfSize=cubeSize*0.5;vec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;vec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;vec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);float distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);vec3 intersectPositionWS=vertexPos+origVec*distance;return intersectPositionWS-cubePos;} vec3 equirectangularToCubemapDirection(vec2 uv) {float longitude=uv.x*TWO_PI-PI;float latitude=HALF_PI-uv.y*PI;vec3 direction;direction.x=cos(latitude)*sin(longitude);direction.y=sin(latitude);direction.z=cos(latitude)*cos(longitude);return direction;} float sqrtClamped(float value) {return sqrt(max(value,0.));} float avg(vec3 value) {return dot(value,vec3(0.333333333));} #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) uint extractBits(uint value,int offset,int width) {return (value>>offset) & ((1u<>23)-0x7f;} #endif `; if (!ShaderStore.IncludesShadersStore[name13]) { ShaderStore.IncludesShadersStore[name13] = shader13; } helperFunctions = { name: name13, shader: shader13 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/rgbdDecode.fragment.js var rgbdDecode_fragment_exports2 = {}; __export(rgbdDecode_fragment_exports2, { rgbdDecodePixelShader: () => rgbdDecodePixelShader }); var name14, shader14, rgbdDecodePixelShader; var init_rgbdDecode_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/rgbdDecode.fragment.js"() { init_shaderStore(); init_helperFunctions2(); name14 = "rgbdDecodePixelShader"; shader14 = `varying vec2 vUV;uniform sampler2D textureSampler; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);}`; if (!ShaderStore.ShadersStore[name14]) { ShaderStore.ShadersStore[name14] = shader14; } rgbdDecodePixelShader = { name: name14, shader: shader14 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/stringDictionary.js var StringDictionary; var init_stringDictionary = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/stringDictionary.js"() { StringDictionary = class { static { __name(this, "StringDictionary"); } constructor() { this._count = 0; this._data = {}; } /** * This will clear this dictionary and copy the content from the 'source' one. * If the T value is a custom object, it won't be copied/cloned, the same object will be used * @param source the dictionary to take the content from and copy to this dictionary */ copyFrom(source) { this.clear(); source.forEach((t, v) => this.add(t, v)); } /** * Get a value based from its key * @param key the given key to get the matching value from * @returns the value if found, otherwise undefined is returned */ get(key) { const val = this._data[key]; if (val !== void 0) { return val; } return void 0; } /** * Get a value from its key or add it if it doesn't exist. * This method will ensure you that a given key/data will be present in the dictionary. * @param key the given key to get the matching value from * @param factory the factory that will create the value if the key is not present in the dictionary. * The factory will only be invoked if there's no data for the given key. * @returns the value corresponding to the key. */ getOrAddWithFactory(key, factory) { let val = this.get(key); if (val !== void 0) { return val; } val = factory(key); if (val) { this.add(key, val); } return val; } /** * Get a value from its key if present in the dictionary otherwise add it * @param key the key to get the value from * @param val if there's no such key/value pair in the dictionary add it with this value * @returns the value corresponding to the key */ getOrAdd(key, val) { const curVal = this.get(key); if (curVal !== void 0) { return curVal; } this.add(key, val); return val; } /** * Check if there's a given key in the dictionary * @param key the key to check for * @returns true if the key is present, false otherwise */ contains(key) { return this._data[key] !== void 0; } /** * Add a new key and its corresponding value * @param key the key to add * @param value the value corresponding to the key * @returns true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary */ add(key, value) { if (this._data[key] !== void 0) { return false; } this._data[key] = value; ++this._count; return true; } /** * Update a specific value associated to a key * @param key defines the key to use * @param value defines the value to store * @returns true if the value was updated (or false if the key was not found) */ set(key, value) { if (this._data[key] === void 0) { return false; } this._data[key] = value; return true; } /** * Get the element of the given key and remove it from the dictionary * @param key defines the key to search * @returns the value associated with the key or null if not found */ getAndRemove(key) { const val = this.get(key); if (val !== void 0) { delete this._data[key]; --this._count; return val; } return null; } /** * Remove a key/value from the dictionary. * @param key the key to remove * @returns true if the item was successfully deleted, false if no item with such key exist in the dictionary */ remove(key) { if (this.contains(key)) { delete this._data[key]; --this._count; return true; } return false; } /** * Clear the whole content of the dictionary */ clear() { this._data = {}; this._count = 0; } /** * Gets the current count */ get count() { return this._count; } /** * Execute a callback on each key/val of the dictionary. * Note that you can remove any element in this dictionary in the callback implementation * @param callback the callback to execute on a given key/value pair */ forEach(callback) { for (const cur in this._data) { const val = this._data[cur]; callback(cur, val); } } /** * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object. * If the callback returns null or undefined the method will iterate to the next key/value pair * Note that you can remove any element in this dictionary in the callback implementation * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned * @returns the first item */ // eslint-disable-next-line @typescript-eslint/naming-convention first(callback) { for (const cur in this._data) { const val = this._data[cur]; const res = callback(cur, val); if (res) { return res; } } return null; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/colorCurves.functions.js function PrepareUniformsForColorCurves(uniformsList) { uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative"); } var init_colorCurves_functions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/colorCurves.functions.js"() { __name(PrepareUniformsForColorCurves, "PrepareUniformsForColorCurves"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/colorCurves.js var ColorCurves; var init_colorCurves = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/colorCurves.js"() { init_tslib_es6(); init_decorators(); init_math_color(); init_decorators_serialization(); init_colorCurves_functions(); ColorCurves = class _ColorCurves { static { __name(this, "ColorCurves"); } constructor() { this._dirty = true; this._tempColor = new Color4(0, 0, 0, 0); this._globalCurve = new Color4(0, 0, 0, 0); this._highlightsCurve = new Color4(0, 0, 0, 0); this._midtonesCurve = new Color4(0, 0, 0, 0); this._shadowsCurve = new Color4(0, 0, 0, 0); this._positiveCurve = new Color4(0, 0, 0, 0); this._negativeCurve = new Color4(0, 0, 0, 0); this._globalHue = 30; this._globalDensity = 0; this._globalSaturation = 0; this._globalExposure = 0; this._highlightsHue = 30; this._highlightsDensity = 0; this._highlightsSaturation = 0; this._highlightsExposure = 0; this._midtonesHue = 30; this._midtonesDensity = 0; this._midtonesSaturation = 0; this._midtonesExposure = 0; this._shadowsHue = 30; this._shadowsDensity = 0; this._shadowsSaturation = 0; this._shadowsExposure = 0; } /** * Gets the global Hue value. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ get globalHue() { return this._globalHue; } /** * Sets the global Hue value. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ set globalHue(value) { this._globalHue = value; this._dirty = true; } /** * Gets the global Density value. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. * Values less than zero provide a filter of opposite hue. */ get globalDensity() { return this._globalDensity; } /** * Sets the global Density value. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. * Values less than zero provide a filter of opposite hue. */ set globalDensity(value) { this._globalDensity = value; this._dirty = true; } /** * Gets the global Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ get globalSaturation() { return this._globalSaturation; } /** * Sets the global Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ set globalSaturation(value) { this._globalSaturation = value; this._dirty = true; } /** * Gets the global Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ get globalExposure() { return this._globalExposure; } /** * Sets the global Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ set globalExposure(value) { this._globalExposure = value; this._dirty = true; } /** * Gets the highlights Hue value. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ get highlightsHue() { return this._highlightsHue; } /** * Sets the highlights Hue value. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ set highlightsHue(value) { this._highlightsHue = value; this._dirty = true; } /** * Gets the highlights Density value. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. * Values less than zero provide a filter of opposite hue. */ get highlightsDensity() { return this._highlightsDensity; } /** * Sets the highlights Density value. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. * Values less than zero provide a filter of opposite hue. */ set highlightsDensity(value) { this._highlightsDensity = value; this._dirty = true; } /** * Gets the highlights Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ get highlightsSaturation() { return this._highlightsSaturation; } /** * Sets the highlights Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ set highlightsSaturation(value) { this._highlightsSaturation = value; this._dirty = true; } /** * Gets the highlights Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ get highlightsExposure() { return this._highlightsExposure; } /** * Sets the highlights Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ set highlightsExposure(value) { this._highlightsExposure = value; this._dirty = true; } /** * Gets the midtones Hue value. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ get midtonesHue() { return this._midtonesHue; } /** * Sets the midtones Hue value. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ set midtonesHue(value) { this._midtonesHue = value; this._dirty = true; } /** * Gets the midtones Density value. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. * Values less than zero provide a filter of opposite hue. */ get midtonesDensity() { return this._midtonesDensity; } /** * Sets the midtones Density value. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. * Values less than zero provide a filter of opposite hue. */ set midtonesDensity(value) { this._midtonesDensity = value; this._dirty = true; } /** * Gets the midtones Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ get midtonesSaturation() { return this._midtonesSaturation; } /** * Sets the midtones Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ set midtonesSaturation(value) { this._midtonesSaturation = value; this._dirty = true; } /** * Gets the midtones Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ get midtonesExposure() { return this._midtonesExposure; } /** * Sets the midtones Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ set midtonesExposure(value) { this._midtonesExposure = value; this._dirty = true; } /** * Gets the shadows Hue value. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ get shadowsHue() { return this._shadowsHue; } /** * Sets the shadows Hue value. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange). */ set shadowsHue(value) { this._shadowsHue = value; this._dirty = true; } /** * Gets the shadows Density value. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. * Values less than zero provide a filter of opposite hue. */ get shadowsDensity() { return this._shadowsDensity; } /** * Sets the shadows Density value. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect. * Values less than zero provide a filter of opposite hue. */ set shadowsDensity(value) { this._shadowsDensity = value; this._dirty = true; } /** * Gets the shadows Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ get shadowsSaturation() { return this._shadowsSaturation; } /** * Sets the shadows Saturation value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation. */ set shadowsSaturation(value) { this._shadowsSaturation = value; this._dirty = true; } /** * Gets the shadows Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ get shadowsExposure() { return this._shadowsExposure; } /** * Sets the shadows Exposure value. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure. */ set shadowsExposure(value) { this._shadowsExposure = value; this._dirty = true; } /** * Returns the class name * @returns The class name */ getClassName() { return "ColorCurves"; } /** * Binds the color curves to the shader. * @param colorCurves The color curve to bind * @param effect The effect to bind to * @param positiveUniform The positive uniform shader parameter * @param neutralUniform The neutral uniform shader parameter * @param negativeUniform The negative uniform shader parameter */ static Bind(colorCurves, effect, positiveUniform = "vCameraColorCurvePositive", neutralUniform = "vCameraColorCurveNeutral", negativeUniform = "vCameraColorCurveNegative") { if (colorCurves._dirty) { colorCurves._dirty = false; colorCurves._getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve); colorCurves._getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor); colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve); colorCurves._getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor); colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve); colorCurves._getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor); colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve); colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve); colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve); } if (effect) { effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a); effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a); effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a); } } /** * Returns color grading data based on a hue, density, saturation and exposure value. * @param hue * @param density * @param saturation The saturation. * @param exposure The exposure. * @param result The result data container. */ _getColorGradingDataToRef(hue, density, saturation, exposure, result) { if (hue == null) { return; } hue = _ColorCurves._Clamp(hue, 0, 360); density = _ColorCurves._Clamp(density, -100, 100); saturation = _ColorCurves._Clamp(saturation, -100, 100); exposure = _ColorCurves._Clamp(exposure, -100, 100); density = _ColorCurves._ApplyColorGradingSliderNonlinear(density); density *= 0.5; exposure = _ColorCurves._ApplyColorGradingSliderNonlinear(exposure); if (density < 0) { density *= -1; hue = (hue + 180) % 360; } _ColorCurves._FromHSBToRef(hue, density, 50 + 0.25 * exposure, result); result.scaleToRef(2, result); result.a = 1 + 0.01 * saturation; } /** * Takes an input slider value and returns an adjusted value that provides extra control near the centre. * @param value The input slider value in range [-100,100]. * @returns Adjusted value. */ static _ApplyColorGradingSliderNonlinear(value) { value /= 100; let x = Math.abs(value); x = Math.pow(x, 2); if (value < 0) { x *= -1; } x *= 100; return x; } /** * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV). * @param hue The hue (H) input. * @param saturation The saturation (S) input. * @param brightness The brightness (B) input. * @param result An RGBA color represented as Vector4. */ // eslint-disable-next-line @typescript-eslint/naming-convention static _FromHSBToRef(hue, saturation, brightness, result) { let h = _ColorCurves._Clamp(hue, 0, 360); const s = _ColorCurves._Clamp(saturation / 100, 0, 1); const v = _ColorCurves._Clamp(brightness / 100, 0, 1); if (s === 0) { result.r = v; result.g = v; result.b = v; } else { h /= 60; const i = Math.floor(h); const f = h - i; const p = v * (1 - s); const q = v * (1 - s * f); const t = v * (1 - s * (1 - f)); switch (i) { case 0: result.r = v; result.g = t; result.b = p; break; case 1: result.r = q; result.g = v; result.b = p; break; case 2: result.r = p; result.g = v; result.b = t; break; case 3: result.r = p; result.g = q; result.b = v; break; case 4: result.r = t; result.g = p; result.b = v; break; default: result.r = v; result.g = p; result.b = q; break; } } result.a = 1; } /** * Returns a value clamped between min and max * @param value The value to clamp * @param min The minimum of value * @param max The maximum of value * @returns The clamped value. */ static _Clamp(value, min, max) { return Math.min(Math.max(value, min), max); } /** * Clones the current color curve instance. * @returns The cloned curves */ clone() { return SerializationHelper.Clone(() => new _ColorCurves(), this); } /** * Serializes the current color curve instance to a json representation. * @returns a JSON representation */ serialize() { return SerializationHelper.Serialize(this); } /** * Parses the color curve from a json representation. * @param source the JSON source to parse * @returns The parsed curves */ static Parse(source) { return SerializationHelper.Parse(() => new _ColorCurves(), source, null, null); } }; ColorCurves.PrepareUniforms = PrepareUniformsForColorCurves; __decorate([ serialize() ], ColorCurves.prototype, "_globalHue", void 0); __decorate([ serialize() ], ColorCurves.prototype, "_globalDensity", void 0); __decorate([ serialize() ], ColorCurves.prototype, "_globalSaturation", void 0); __decorate([ serialize() ], ColorCurves.prototype, "_globalExposure", void 0); __decorate([ serialize() ], ColorCurves.prototype, "_highlightsHue", void 0); __decorate([ serialize() ], ColorCurves.prototype, "_highlightsDensity", void 0); __decorate([ serialize() ], ColorCurves.prototype, "_highlightsSaturation", void 0); __decorate([ serialize() ], ColorCurves.prototype, "_highlightsExposure", void 0); __decorate([ serialize() ], ColorCurves.prototype, "_midtonesHue", void 0); __decorate([ serialize() ], ColorCurves.prototype, "_midtonesDensity", void 0); __decorate([ serialize() ], ColorCurves.prototype, "_midtonesSaturation", void 0); __decorate([ serialize() ], ColorCurves.prototype, "_midtonesExposure", void 0); SerializationHelper._ColorCurvesParser = ColorCurves.Parse; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.functions.js function PrepareUniformsForImageProcessing(uniforms, defines) { if (defines.EXPOSURE) { uniforms.push("exposureLinear"); } if (defines.CONTRAST) { uniforms.push("contrast"); } if (defines.COLORGRADING) { uniforms.push("colorTransformSettings"); } if (defines.VIGNETTE || defines.DITHER) { uniforms.push("vInverseScreenSize"); } if (defines.VIGNETTE) { uniforms.push("vignetteSettings1"); uniforms.push("vignetteSettings2"); } if (defines.COLORCURVES) { PrepareUniformsForColorCurves(uniforms); } if (defines.DITHER) { uniforms.push("ditherIntensity"); } } function PrepareSamplersForImageProcessing(samplersList, defines) { if (defines.COLORGRADING) { samplersList.push("txColorTransform"); } } var init_imageProcessingConfiguration_functions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.functions.js"() { init_colorCurves_functions(); __name(PrepareUniformsForImageProcessing, "PrepareUniformsForImageProcessing"); __name(PrepareSamplersForImageProcessing, "PrepareSamplersForImageProcessing"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.js var ImageProcessingConfiguration; var init_imageProcessingConfiguration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.js"() { init_tslib_es6(); init_decorators(); init_observable(); init_math_color(); init_colorCurves(); init_tools_functions(); init_decorators_serialization(); init_imageProcessingConfiguration_functions(); init_typeStore(); ImageProcessingConfiguration = class _ImageProcessingConfiguration { static { __name(this, "ImageProcessingConfiguration"); } constructor() { this.colorCurves = new ColorCurves(); this._colorCurvesEnabled = false; this._colorGradingEnabled = false; this._colorGradingWithGreenDepth = true; this._colorGradingBGR = true; this._exposure = 1; this._toneMappingEnabled = false; this._toneMappingType = _ImageProcessingConfiguration.TONEMAPPING_STANDARD; this._contrast = 1; this.vignetteStretch = 0; this.vignetteCenterX = 0; this.vignetteCenterY = 0; this.vignetteWeight = 1.5; this.vignetteColor = new Color4(0, 0, 0, 0); this.vignetteCameraFov = 0.5; this._vignetteBlendMode = _ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY; this._vignetteEnabled = false; this._ditheringEnabled = false; this._ditheringIntensity = 1 / 255; this._skipFinalColorClamp = false; this._applyByPostProcess = false; this._isEnabled = true; this.outputTextureWidth = 0; this.outputTextureHeight = 0; this.onUpdateParameters = new Observable(); } /** * Gets whether the color curves effect is enabled. */ get colorCurvesEnabled() { return this._colorCurvesEnabled; } /** * Sets whether the color curves effect is enabled. */ set colorCurvesEnabled(value) { if (this._colorCurvesEnabled === value) { return; } this._colorCurvesEnabled = value; this._updateParameters(); } /** * Color grading LUT texture used in the effect if colorGradingEnabled is set to true */ get colorGradingTexture() { return this._colorGradingTexture; } /** * Color grading LUT texture used in the effect if colorGradingEnabled is set to true */ set colorGradingTexture(value) { if (this._colorGradingTexture === value) { return; } this._colorGradingTexture = value; this._updateParameters(); } /** * Gets whether the color grading effect is enabled. */ get colorGradingEnabled() { return this._colorGradingEnabled; } /** * Sets whether the color grading effect is enabled. */ set colorGradingEnabled(value) { if (this._colorGradingEnabled === value) { return; } this._colorGradingEnabled = value; this._updateParameters(); } /** * Gets whether the color grading effect is using a green depth for the 3d Texture. */ get colorGradingWithGreenDepth() { return this._colorGradingWithGreenDepth; } /** * Sets whether the color grading effect is using a green depth for the 3d Texture. */ set colorGradingWithGreenDepth(value) { if (this._colorGradingWithGreenDepth === value) { return; } this._colorGradingWithGreenDepth = value; this._updateParameters(); } /** * Gets whether the color grading texture contains BGR values. */ get colorGradingBGR() { return this._colorGradingBGR; } /** * Sets whether the color grading texture contains BGR values. */ set colorGradingBGR(value) { if (this._colorGradingBGR === value) { return; } this._colorGradingBGR = value; this._updateParameters(); } /** * Gets the Exposure used in the effect. */ get exposure() { return this._exposure; } /** * Sets the Exposure used in the effect. */ set exposure(value) { if (this._exposure === value) { return; } this._exposure = value; this._updateParameters(); } /** * Gets whether the tone mapping effect is enabled. */ get toneMappingEnabled() { return this._toneMappingEnabled; } /** * Sets whether the tone mapping effect is enabled. */ set toneMappingEnabled(value) { if (this._toneMappingEnabled === value) { return; } this._toneMappingEnabled = value; this._updateParameters(); } /** * Gets the type of tone mapping effect. */ get toneMappingType() { return this._toneMappingType; } /** * Sets the type of tone mapping effect used in BabylonJS. */ set toneMappingType(value) { if (this._toneMappingType === value) { return; } this._toneMappingType = value; this._updateParameters(); } /** * Gets the contrast used in the effect. */ get contrast() { return this._contrast; } /** * Sets the contrast used in the effect. */ set contrast(value) { if (this._contrast === value) { return; } this._contrast = value; this._updateParameters(); } /** * Back Compat: Vignette center Y Offset. * @deprecated use vignetteCenterY instead */ get vignetteCentreY() { return this.vignetteCenterY; } set vignetteCentreY(value) { this.vignetteCenterY = value; } /** * Back Compat: Vignette center X Offset. * @deprecated use vignetteCenterX instead */ get vignetteCentreX() { return this.vignetteCenterX; } set vignetteCentreX(value) { this.vignetteCenterX = value; } /** * Gets the vignette blend mode allowing different kind of effect. */ get vignetteBlendMode() { return this._vignetteBlendMode; } /** * Sets the vignette blend mode allowing different kind of effect. */ set vignetteBlendMode(value) { if (this._vignetteBlendMode === value) { return; } this._vignetteBlendMode = value; this._updateParameters(); } /** * Gets whether the vignette effect is enabled. */ get vignetteEnabled() { return this._vignetteEnabled; } /** * Sets whether the vignette effect is enabled. */ set vignetteEnabled(value) { if (this._vignetteEnabled === value) { return; } this._vignetteEnabled = value; this._updateParameters(); } /** * Gets whether the dithering effect is enabled. * The dithering effect can be used to reduce banding. */ get ditheringEnabled() { return this._ditheringEnabled; } /** * Sets whether the dithering effect is enabled. * The dithering effect can be used to reduce banding. */ set ditheringEnabled(value) { if (this._ditheringEnabled === value) { return; } this._ditheringEnabled = value; this._updateParameters(); } /** * Gets the dithering intensity. 0 is no dithering. Default is 1.0 / 255.0. */ get ditheringIntensity() { return this._ditheringIntensity; } /** * Sets the dithering intensity. 0 is no dithering. Default is 1.0 / 255.0. */ set ditheringIntensity(value) { if (this._ditheringIntensity === value) { return; } this._ditheringIntensity = value; this._updateParameters(); } /** * If apply by post process is set to true, setting this to true will skip the final color clamp step in the fragment shader * Applies to PBR materials. */ get skipFinalColorClamp() { return this._skipFinalColorClamp; } /** * If apply by post process is set to true, setting this to true will skip the final color clamp step in the fragment shader * Applies to PBR materials. */ set skipFinalColorClamp(value) { if (this._skipFinalColorClamp === value) { return; } this._skipFinalColorClamp = value; this._updateParameters(); } /** * Gets whether the image processing is applied through a post process or not. */ get applyByPostProcess() { return this._applyByPostProcess; } /** * Sets whether the image processing is applied through a post process or not. */ set applyByPostProcess(value) { if (this._applyByPostProcess === value) { return; } this._applyByPostProcess = value; this._updateParameters(); } /** * Gets whether the image processing is enabled or not. */ get isEnabled() { return this._isEnabled; } /** * Sets whether the image processing is enabled or not. */ set isEnabled(value) { if (this._isEnabled === value) { return; } this._isEnabled = value; this._updateParameters(); } /** * Method called each time the image processing information changes requires to recompile the effect. */ _updateParameters() { this.onUpdateParameters.notifyObservers(this); } /** * Gets the current class name. * @returns "ImageProcessingConfiguration" */ getClassName() { return "ImageProcessingConfiguration"; } /** * Prepare the list of defines associated to the shader. * @param defines the list of defines to complete * @param forPostProcess Define if we are currently in post process mode or not */ prepareDefines(defines, forPostProcess = false) { if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) { defines.VIGNETTE = false; defines.TONEMAPPING = 0; defines.CONTRAST = false; defines.EXPOSURE = false; defines.COLORCURVES = false; defines.COLORGRADING = false; defines.COLORGRADING3D = false; defines.DITHER = false; defines.IMAGEPROCESSING = false; defines.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp; defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled; return; } defines.VIGNETTE = this.vignetteEnabled; defines.VIGNETTEBLENDMODEMULTIPLY = this.vignetteBlendMode === _ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY; defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY; if (!this._toneMappingEnabled) { defines.TONEMAPPING = 0; } else { switch (this._toneMappingType) { case _ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL: defines.TONEMAPPING = 3; break; case _ImageProcessingConfiguration.TONEMAPPING_ACES: defines.TONEMAPPING = 2; break; default: defines.TONEMAPPING = 1; break; } } defines.CONTRAST = this.contrast !== 1; defines.EXPOSURE = this.exposure !== 1; defines.COLORCURVES = this.colorCurvesEnabled && !!this.colorCurves; defines.COLORGRADING = this.colorGradingEnabled && !!this.colorGradingTexture; if (defines.COLORGRADING) { defines.COLORGRADING3D = this.colorGradingTexture.is3D; } else { defines.COLORGRADING3D = false; } defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth; defines.SAMPLER3DBGRMAP = this.colorGradingBGR; defines.DITHER = this._ditheringEnabled; defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess; defines.SKIPFINALCOLORCLAMP = this.skipFinalColorClamp; defines.IMAGEPROCESSING = defines.VIGNETTE || !!defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.DITHER; } /** * Returns true if all the image processing information are ready. * @returns True if ready, otherwise, false */ isReady() { return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady(); } /** * Binds the image processing to the shader. * @param effect The effect to bind to * @param overrideAspectRatio Override the aspect ratio of the effect */ bind(effect, overrideAspectRatio) { if (this._colorCurvesEnabled && this.colorCurves) { ColorCurves.Bind(this.colorCurves, effect); } if (this._vignetteEnabled || this._ditheringEnabled) { const inverseWidth = 1 / (this.outputTextureWidth || effect.getEngine().getRenderWidth()); const inverseHeight = 1 / (this.outputTextureHeight || effect.getEngine().getRenderHeight()); effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight); if (this._ditheringEnabled) { effect.setFloat("ditherIntensity", 0.5 * this._ditheringIntensity); } if (this._vignetteEnabled) { const aspectRatio = overrideAspectRatio != null ? overrideAspectRatio : inverseHeight / inverseWidth; let vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5); let vignetteScaleX = vignetteScaleY * aspectRatio; const vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY); vignetteScaleX = Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch); vignetteScaleY = Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch); effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCenterX, -vignetteScaleY * this.vignetteCenterY); const vignettePower = -2 * this.vignetteWeight; effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower); } } effect.setFloat("exposureLinear", this.exposure); effect.setFloat("contrast", this.contrast); if (this.colorGradingTexture) { effect.setTexture("txColorTransform", this.colorGradingTexture); const textureSize = this.colorGradingTexture.getSize().height; effect.setFloat4( "colorTransformSettings", (textureSize - 1) / textureSize, // textureScale 0.5 / textureSize, // textureOffset textureSize, // textureSize this.colorGradingTexture.level // weight ); } } /** * Clones the current image processing instance. * @returns The cloned image processing */ clone() { return SerializationHelper.Clone(() => new _ImageProcessingConfiguration(), this); } /** * Serializes the current image processing instance to a json representation. * @returns a JSON representation */ serialize() { return SerializationHelper.Serialize(this); } /** * Parses the image processing from a json representation. * @param source the JSON source to parse * @returns The parsed image processing */ static Parse(source) { const parsed = SerializationHelper.Parse(() => new _ImageProcessingConfiguration(), source, null, null); if (source.vignetteCentreX !== void 0) { parsed.vignetteCenterX = source.vignetteCentreX; } if (source.vignetteCentreY !== void 0) { parsed.vignetteCenterY = source.vignetteCentreY; } return parsed; } /** * Used to apply the vignette as a mix with the pixel color. */ static get VIGNETTEMODE_MULTIPLY() { return this._VIGNETTEMODE_MULTIPLY; } /** * Used to apply the vignette as a replacement of the pixel color. */ static get VIGNETTEMODE_OPAQUE() { return this._VIGNETTEMODE_OPAQUE; } }; ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0; ImageProcessingConfiguration.TONEMAPPING_ACES = 1; ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL = 2; ImageProcessingConfiguration.PrepareUniforms = PrepareUniformsForImageProcessing; ImageProcessingConfiguration.PrepareSamplers = PrepareSamplersForImageProcessing; ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0; ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1; __decorate([ serializeAsColorCurves() ], ImageProcessingConfiguration.prototype, "colorCurves", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0); __decorate([ serializeAsTexture("colorGradingTexture") ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_exposure", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_contrast", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "vignetteCenterX", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "vignetteCenterY", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0); __decorate([ serializeAsColor4() ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_ditheringEnabled", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_ditheringIntensity", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_skipFinalColorClamp", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "outputTextureWidth", void 0); __decorate([ serialize() ], ImageProcessingConfiguration.prototype, "outputTextureHeight", void 0); SerializationHelper._ImageProcessingConfigurationParser = ImageProcessingConfiguration.Parse; RegisterClass("BABYLON.ImageProcessingConfiguration", ImageProcessingConfiguration); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/uniformBuffer.js var UniformBuffer; var init_uniformBuffer = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/uniformBuffer.js"() { init_logger(); init_tools(); UniformBuffer = class _UniformBuffer { static { __name(this, "UniformBuffer"); } /** * Instantiates a new Uniform buffer objects. * * Handles blocks of uniform on the GPU. * * If WebGL 2 is not available, this class falls back on traditional setUniformXXX calls. * * For more information, please refer to : * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object * @param engine Define the engine the buffer is associated with * @param data Define the data contained in the buffer * @param dynamic Define if the buffer is updatable * @param name to assign to the buffer (debugging purpose) * @param forceNoUniformBuffer define that this object must not rely on UBO objects * @param trackUBOsInFrame define if the UBOs should be tracked in the frame (default: undefined - will use the value from Engine._features.trackUbosInFrame) */ constructor(engine, data, dynamic = false, name260, forceNoUniformBuffer = false, trackUBOsInFrame) { this._uniformNames = []; this._valueCache = {}; this._engine = engine; this._noUBO = !engine.supportsUniformBuffers || forceNoUniformBuffer; this._dynamic = dynamic; this._name = name260 ?? "no-name"; this._data = data || []; this._uniformLocations = {}; this._uniformSizes = {}; this._uniformArraySizes = {}; this._uniformLocationPointer = 0; this._needSync = false; this._trackUBOsInFrame = false; if (trackUBOsInFrame === void 0 && this._engine._features.trackUbosInFrame || trackUBOsInFrame === true) { this._buffers = []; this._bufferIndex = -1; this._createBufferOnWrite = false; this._currentFrameId = 0; this._trackUBOsInFrame = true; } if (this._noUBO) { this.updateMatrix3x3 = this._updateMatrix3x3ForEffect; this.updateMatrix2x2 = this._updateMatrix2x2ForEffect; this.updateFloat = this._updateFloatForEffect; this.updateFloat2 = this._updateFloat2ForEffect; this.updateFloat3 = this._updateFloat3ForEffect; this.updateFloat4 = this._updateFloat4ForEffect; this.updateFloatArray = this._updateFloatArrayForEffect; this.updateArray = this._updateArrayForEffect; this.updateIntArray = this._updateIntArrayForEffect; this.updateUIntArray = this._updateUIntArrayForEffect; this.updateMatrix = this._updateMatrixForEffect; this.updateMatrices = this._updateMatricesForEffect; this.updateVector3 = this._updateVector3ForEffect; this.updateVector4 = this._updateVector4ForEffect; this.updateColor3 = this._updateColor3ForEffect; this.updateColor4 = this._updateColor4ForEffect; this.updateDirectColor4 = this._updateDirectColor4ForEffect; this.updateInt = this._updateIntForEffect; this.updateInt2 = this._updateInt2ForEffect; this.updateInt3 = this._updateInt3ForEffect; this.updateInt4 = this._updateInt4ForEffect; this.updateUInt = this._updateUIntForEffect; this.updateUInt2 = this._updateUInt2ForEffect; this.updateUInt3 = this._updateUInt3ForEffect; this.updateUInt4 = this._updateUInt4ForEffect; } else { this._engine._uniformBuffers.push(this); this.updateMatrix3x3 = this._updateMatrix3x3ForUniform; this.updateMatrix2x2 = this._updateMatrix2x2ForUniform; this.updateFloat = this._updateFloatForUniform; this.updateFloat2 = this._updateFloat2ForUniform; this.updateFloat3 = this._updateFloat3ForUniform; this.updateFloat4 = this._updateFloat4ForUniform; this.updateFloatArray = this._updateFloatArrayForUniform; this.updateArray = this._updateArrayForUniform; this.updateIntArray = this._updateIntArrayForUniform; this.updateUIntArray = this._updateUIntArrayForUniform; this.updateMatrix = this._updateMatrixForUniform; this.updateMatrices = this._updateMatricesForUniform; this.updateVector3 = this._updateVector3ForUniform; this.updateVector4 = this._updateVector4ForUniform; this.updateColor3 = this._updateColor3ForUniform; this.updateColor4 = this._updateColor4ForUniform; this.updateDirectColor4 = this._updateDirectColor4ForUniform; this.updateInt = this._updateIntForUniform; this.updateInt2 = this._updateInt2ForUniform; this.updateInt3 = this._updateInt3ForUniform; this.updateInt4 = this._updateInt4ForUniform; this.updateUInt = this._updateUIntForUniform; this.updateUInt2 = this._updateUInt2ForUniform; this.updateUInt3 = this._updateUInt3ForUniform; this.updateUInt4 = this._updateUInt4ForUniform; } } /** * Indicates if the buffer is using the WebGL2 UBO implementation, * or just falling back on setUniformXXX calls. */ get useUbo() { return !this._noUBO; } /** * Indicates if the WebGL underlying uniform buffer is in sync * with the javascript cache data. */ get isSync() { return !this._needSync; } /** * Indicates if the WebGL underlying uniform buffer is dynamic. * Also, a dynamic UniformBuffer will disable cache verification and always * update the underlying WebGL uniform buffer to the GPU. * @returns if Dynamic, otherwise false */ isDynamic() { return this._dynamic; } /** * The data cache on JS side. * @returns the underlying data as a float array */ getData() { return this._bufferData; } /** * The underlying WebGL Uniform buffer. * @returns the webgl buffer */ getBuffer() { return this._buffer; } /** * The names of the uniforms in the buffer. * @returns an array of uniform names */ getUniformNames() { return this._uniformNames; } /** * std140 layout specifies how to align data within an UBO structure. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159 * for specs. * @param size */ _fillAlignment(size) { let alignment; if (size <= 2) { alignment = size; } else { alignment = 4; } if (this._uniformLocationPointer % alignment !== 0) { const oldPointer = this._uniformLocationPointer; this._uniformLocationPointer += alignment - this._uniformLocationPointer % alignment; const diff = this._uniformLocationPointer - oldPointer; for (let i = 0; i < diff; i++) { this._data.push(0); } } } /** * Adds an uniform in the buffer. * Warning : the subsequents calls of this function must be in the same order as declared in the shader * for the layout to be correct ! The addUniform function only handles types like float, vec2, vec3, vec4, mat4, * meaning size=1,2,3,4 or 16. It does not handle struct types. * @param name Name of the uniform, as used in the uniform block in the shader. * @param size Data size, or data directly. * @param arraySize The number of elements in the array, 0 if not an array. */ addUniform(name260, size, arraySize = 0) { if (arraySize > 0 && typeof size === "number") { this._uniformArraySizes[name260] = { strideSize: size, arraySize }; } if (this._uniformLocations[name260] !== void 0) { return; } this._uniformNames.push(name260); if (this._noUBO) { return; } let data; if (arraySize > 0) { if (size instanceof Array) { throw "addUniform should not be use with Array in UBO: " + name260; } this._fillAlignment(4); if (size == 16) { size = size * arraySize; } else { const perElementPadding = 4 - size; const totalPadding = perElementPadding * arraySize; size = size * arraySize + totalPadding; } data = []; for (let i = 0; i < size; i++) { data.push(0); } } else { if (size instanceof Array) { data = size; size = data.length; } else { data = []; for (let i = 0; i < size; i++) { data.push(0); } } this._fillAlignment(size); } this._uniformSizes[name260] = size; this._uniformLocations[name260] = this._uniformLocationPointer; this._uniformLocationPointer += size; for (let i = 0; i < size; i++) { this._data.push(data[i]); } this._needSync = true; } /** * Adds a Matrix 4x4 to the uniform buffer. * @param name Name of the uniform, as used in the uniform block in the shader. * @param mat A 4x4 matrix. */ addMatrix(name260, mat) { this.addUniform(name260, Array.prototype.slice.call(mat.asArray())); } /** * Adds a vec2 to the uniform buffer. * @param name Name of the uniform, as used in the uniform block in the shader. * @param x Define the x component value of the vec2 * @param y Define the y component value of the vec2 */ addFloat2(name260, x, y) { const temp = [x, y]; this.addUniform(name260, temp); } /** * Adds a vec3 to the uniform buffer. * @param name Name of the uniform, as used in the uniform block in the shader. * @param x Define the x component value of the vec3 * @param y Define the y component value of the vec3 * @param z Define the z component value of the vec3 */ addFloat3(name260, x, y, z) { const temp = [x, y, z]; this.addUniform(name260, temp); } /** * Adds a vec3 to the uniform buffer. * @param name Name of the uniform, as used in the uniform block in the shader. * @param color Define the vec3 from a Color */ addColor3(name260, color) { const temp = [color.r, color.g, color.b]; this.addUniform(name260, temp); } /** * Adds a vec4 to the uniform buffer. * @param name Name of the uniform, as used in the uniform block in the shader. * @param color Define the rgb components from a Color * @param alpha Define the a component of the vec4 */ addColor4(name260, color, alpha) { const temp = [color.r, color.g, color.b, alpha]; this.addUniform(name260, temp); } /** * Adds a vec3 to the uniform buffer. * @param name Name of the uniform, as used in the uniform block in the shader. * @param vector Define the vec3 components from a Vector */ addVector3(name260, vector) { const temp = [vector.x, vector.y, vector.z]; this.addUniform(name260, temp); } /** * Adds a Matrix 3x3 to the uniform buffer. * @param name Name of the uniform, as used in the uniform block in the shader. */ addMatrix3x3(name260) { this.addUniform(name260, 12); } /** * Adds a Matrix 2x2 to the uniform buffer. * @param name Name of the uniform, as used in the uniform block in the shader. */ addMatrix2x2(name260) { this.addUniform(name260, 8); } /** * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`. */ create() { if (this._noUBO) { return; } if (this._buffer) { return; } this._fillAlignment(4); this._bufferData = new Float32Array(this._data); this._rebuild(); this._needSync = true; } // The result of this method is used for debugging purpose, as part of the buffer name // It is meant to more easily know what this buffer is about when debugging // Some buffers can have a lot of uniforms (several dozens), so the method only returns the first 10 of them // (should be enough to understand what the buffer is for) _getNamesDebug() { const names = []; let i = 0; for (const name260 in this._uniformLocations) { names.push(name260); if (++i === 10) { break; } } return names.join(","); } /** @internal */ _rebuild() { if (this._noUBO || !this._bufferData) { return; } if (this._dynamic) { this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData, this._name + "_UniformList:" + this._getNamesDebug()); } else { this._buffer = this._engine.createUniformBuffer(this._bufferData, this._name + "_UniformList:" + this._getNamesDebug()); } if (this._trackUBOsInFrame) { this._buffers.push([this._buffer, this._engine._features.checkUbosContentBeforeUpload ? this._bufferData.slice() : void 0]); this._bufferIndex = this._buffers.length - 1; this._createBufferOnWrite = false; } } /** @internal */ _rebuildAfterContextLost() { if (this._trackUBOsInFrame) { this._buffers = []; this._currentFrameId = 0; } this._rebuild(); } /** @internal */ get _numBuffers() { return this._buffers.length; } /** @internal */ get _indexBuffer() { return this._bufferIndex; } /** Gets or sets the name of this buffer */ get name() { return this._name; } set name(value) { this._name = value; } /** Gets the current effect */ get currentEffect() { return this._currentEffect; } _buffersEqual(buf1, buf2) { for (let i = 0; i < buf1.length; ++i) { if (buf1[i] !== buf2[i]) { return false; } } return true; } _copyBuffer(src, dst) { for (let i = 0; i < src.length; ++i) { dst[i] = src[i]; } } /** * Updates the WebGL Uniform Buffer on the GPU. * If the `dynamic` flag is set to true, no cache comparison is done. * Otherwise, the buffer will be updated only if the cache differs. */ update() { if (this._noUBO) { return; } this.bindUniformBuffer(); if (!this._buffer) { this.create(); return; } if (!this._dynamic && !this._needSync) { this._createBufferOnWrite = this._trackUBOsInFrame; return; } if (this._buffers && this._buffers.length > 1 && this._buffers[this._bufferIndex][1]) { if (this._buffersEqual(this._bufferData, this._buffers[this._bufferIndex][1])) { this._needSync = false; this._createBufferOnWrite = this._trackUBOsInFrame; return; } else { this._copyBuffer(this._bufferData, this._buffers[this._bufferIndex][1]); } } this._engine.updateUniformBuffer(this._buffer, this._bufferData); if (this._engine._features._collectUbosUpdatedInFrame) { if (!_UniformBuffer._UpdatedUbosInFrame[this._name]) { _UniformBuffer._UpdatedUbosInFrame[this._name] = 0; } _UniformBuffer._UpdatedUbosInFrame[this._name]++; } this._needSync = false; this._createBufferOnWrite = this._trackUBOsInFrame; } _createNewBuffer() { if (this._bufferIndex + 1 < this._buffers.length) { this._bufferIndex++; this._buffer = this._buffers[this._bufferIndex][0]; this._createBufferOnWrite = false; this._needSync = true; } else { this._rebuild(); } } _checkNewFrame() { if (this._trackUBOsInFrame && this._currentFrameId !== this._engine.frameId) { this._currentFrameId = this._engine.frameId; this._createBufferOnWrite = false; if (this._buffers && this._buffers.length > 0) { this._needSync = this._bufferIndex !== 0; this._bufferIndex = 0; this._buffer = this._buffers[this._bufferIndex][0]; } else { this._bufferIndex = -1; } } } /** * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader. * @param data Define the flattened data * @param size Define the size of the data. */ updateUniform(uniformName, data, size) { this._checkNewFrame(); let location2 = this._uniformLocations[uniformName]; if (location2 === void 0) { if (this._buffer) { Logger.Error("Cannot add an uniform after UBO has been created. uniformName=" + uniformName); return; } this.addUniform(uniformName, size); location2 = this._uniformLocations[uniformName]; } if (!this._buffer) { this.create(); } if (!this._dynamic) { let changed = false; for (let i = 0; i < size; i++) { if (size === 16 && !this._engine._features.uniformBufferHardCheckMatrix || this._bufferData[location2 + i] !== Math.fround(data[i])) { changed = true; if (this._createBufferOnWrite) { this._createNewBuffer(); } this._bufferData[location2 + i] = data[i]; } } this._needSync = this._needSync || changed; } else { for (let i = 0; i < size; i++) { this._bufferData[location2 + i] = data[i]; } } } /** * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader. * @param data Define the flattened data * @param size Define the size of the data. */ updateUniformArray(uniformName, data, size) { this._checkNewFrame(); const location2 = this._uniformLocations[uniformName]; if (location2 === void 0) { Logger.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine."); return; } if (!this._buffer) { this.create(); } const arraySizes = this._uniformArraySizes[uniformName]; if (!this._dynamic) { let changed = false; let countToFour = 0; let baseStride = 0; for (let i = 0; i < size; i++) { if (this._bufferData[location2 + baseStride * 4 + countToFour] !== Tools.FloatRound(data[i])) { changed = true; if (this._createBufferOnWrite) { this._createNewBuffer(); } this._bufferData[location2 + baseStride * 4 + countToFour] = data[i]; } countToFour++; if (countToFour === arraySizes.strideSize) { for (; countToFour < 4; countToFour++) { this._bufferData[location2 + baseStride * 4 + countToFour] = 0; } countToFour = 0; baseStride++; } } this._needSync = this._needSync || changed; } else { for (let i = 0; i < size; i++) { this._bufferData[location2 + i] = data[i]; } } } _cacheMatrix(name260, matrix) { this._checkNewFrame(); const cache = this._valueCache[name260]; const flag = matrix.updateFlag; if (cache !== void 0 && cache === flag) { return false; } this._valueCache[name260] = flag; return true; } // Update methods _updateMatrix3x3ForUniform(name260, matrix) { for (let i = 0; i < 3; i++) { _UniformBuffer._TempBuffer[i * 4] = matrix[i * 3]; _UniformBuffer._TempBuffer[i * 4 + 1] = matrix[i * 3 + 1]; _UniformBuffer._TempBuffer[i * 4 + 2] = matrix[i * 3 + 2]; _UniformBuffer._TempBuffer[i * 4 + 3] = 0; } this.updateUniform(name260, _UniformBuffer._TempBuffer, 12); } _updateMatrix3x3ForEffect(name260, matrix) { this._currentEffect.setMatrix3x3(name260, matrix); } _updateMatrix2x2ForEffect(name260, matrix) { this._currentEffect.setMatrix2x2(name260, matrix); } _updateMatrix2x2ForUniform(name260, matrix) { for (let i = 0; i < 2; i++) { _UniformBuffer._TempBuffer[i * 4] = matrix[i * 2]; _UniformBuffer._TempBuffer[i * 4 + 1] = matrix[i * 2 + 1]; _UniformBuffer._TempBuffer[i * 4 + 2] = 0; _UniformBuffer._TempBuffer[i * 4 + 3] = 0; } this.updateUniform(name260, _UniformBuffer._TempBuffer, 8); } _updateFloatForEffect(name260, x, suffix = "") { this._currentEffect.setFloat(name260 + suffix, x); } _updateFloatForUniform(name260, x) { _UniformBuffer._TempBuffer[0] = x; this.updateUniform(name260, _UniformBuffer._TempBuffer, 1); } _updateFloat2ForEffect(name260, x, y, suffix = "") { this._currentEffect.setFloat2(name260 + suffix, x, y); } _updateFloat2ForUniform(name260, x, y) { _UniformBuffer._TempBuffer[0] = x; _UniformBuffer._TempBuffer[1] = y; this.updateUniform(name260, _UniformBuffer._TempBuffer, 2); } _updateFloat3ForEffect(name260, x, y, z, suffix = "") { this._currentEffect.setFloat3(name260 + suffix, x, y, z); } _updateFloat3ForUniform(name260, x, y, z) { _UniformBuffer._TempBuffer[0] = x; _UniformBuffer._TempBuffer[1] = y; _UniformBuffer._TempBuffer[2] = z; this.updateUniform(name260, _UniformBuffer._TempBuffer, 3); } _updateFloat4ForEffect(name260, x, y, z, w, suffix = "") { this._currentEffect.setFloat4(name260 + suffix, x, y, z, w); } _updateFloat4ForUniform(name260, x, y, z, w) { _UniformBuffer._TempBuffer[0] = x; _UniformBuffer._TempBuffer[1] = y; _UniformBuffer._TempBuffer[2] = z; _UniformBuffer._TempBuffer[3] = w; this.updateUniform(name260, _UniformBuffer._TempBuffer, 4); } _updateFloatArrayForEffect(name260, array, suffix = "") { switch (this._uniformArraySizes[name260]?.strideSize) { case 2: this._currentEffect.setFloatArray2(name260 + suffix, array); break; case 3: this._currentEffect.setFloatArray3(name260 + suffix, array); break; case 4: this._currentEffect.setFloatArray4(name260 + suffix, array); break; default: this._currentEffect.setFloatArray(name260 + suffix, array); break; } } _updateFloatArrayForUniform(name260, array) { this.updateUniformArray(name260, array, array.length); } _updateArrayForEffect(name260, array) { this._currentEffect.setArray(name260, array); } _updateArrayForUniform(name260, array) { this.updateUniformArray(name260, array, array.length); } _updateIntArrayForEffect(name260, array) { this._currentEffect.setIntArray(name260, array); } _updateIntArrayForUniform(name260, array) { _UniformBuffer._TempBufferInt32View.set(array); this.updateUniformArray(name260, _UniformBuffer._TempBuffer, array.length); } _updateUIntArrayForEffect(name260, array) { this._currentEffect.setUIntArray(name260, array); } _updateUIntArrayForUniform(name260, array) { _UniformBuffer._TempBufferUInt32View.set(array); this.updateUniformArray(name260, _UniformBuffer._TempBuffer, array.length); } _updateMatrixForEffect(name260, mat) { this._currentEffect.setMatrix(name260, mat); } _updateMatrixForUniform(name260, mat) { if (this._cacheMatrix(name260, mat)) { this.updateUniform(name260, mat.asArray(), 16); } } _updateMatricesForEffect(name260, mat) { this._currentEffect.setMatrices(name260, mat); } _updateMatricesForUniform(name260, mat) { this.updateUniform(name260, mat, mat.length); } _updateVector3ForEffect(name260, vector) { this._currentEffect.setVector3(name260, vector); } _updateVector3ForUniform(name260, vector) { _UniformBuffer._TempBuffer[0] = vector.x; _UniformBuffer._TempBuffer[1] = vector.y; _UniformBuffer._TempBuffer[2] = vector.z; this.updateUniform(name260, _UniformBuffer._TempBuffer, 3); } _updateVector4ForEffect(name260, vector) { this._currentEffect.setVector4(name260, vector); } _updateVector4ForUniform(name260, vector) { _UniformBuffer._TempBuffer[0] = vector.x; _UniformBuffer._TempBuffer[1] = vector.y; _UniformBuffer._TempBuffer[2] = vector.z; _UniformBuffer._TempBuffer[3] = vector.w; this.updateUniform(name260, _UniformBuffer._TempBuffer, 4); } _updateColor3ForEffect(name260, color, suffix = "") { this._currentEffect.setColor3(name260 + suffix, color); } _updateColor3ForUniform(name260, color) { _UniformBuffer._TempBuffer[0] = color.r; _UniformBuffer._TempBuffer[1] = color.g; _UniformBuffer._TempBuffer[2] = color.b; this.updateUniform(name260, _UniformBuffer._TempBuffer, 3); } _updateColor4ForEffect(name260, color, alpha, suffix = "") { this._currentEffect.setColor4(name260 + suffix, color, alpha); } _updateDirectColor4ForEffect(name260, color, suffix = "") { this._currentEffect.setDirectColor4(name260 + suffix, color); } _updateColor4ForUniform(name260, color, alpha) { _UniformBuffer._TempBuffer[0] = color.r; _UniformBuffer._TempBuffer[1] = color.g; _UniformBuffer._TempBuffer[2] = color.b; _UniformBuffer._TempBuffer[3] = alpha; this.updateUniform(name260, _UniformBuffer._TempBuffer, 4); } _updateDirectColor4ForUniform(name260, color) { _UniformBuffer._TempBuffer[0] = color.r; _UniformBuffer._TempBuffer[1] = color.g; _UniformBuffer._TempBuffer[2] = color.b; _UniformBuffer._TempBuffer[3] = color.a; this.updateUniform(name260, _UniformBuffer._TempBuffer, 4); } _updateIntForEffect(name260, x, suffix = "") { this._currentEffect.setInt(name260 + suffix, x); } _updateIntForUniform(name260, x) { _UniformBuffer._TempBufferInt32View[0] = x; this.updateUniform(name260, _UniformBuffer._TempBuffer, 1); } _updateInt2ForEffect(name260, x, y, suffix = "") { this._currentEffect.setInt2(name260 + suffix, x, y); } _updateInt2ForUniform(name260, x, y) { _UniformBuffer._TempBufferInt32View[0] = x; _UniformBuffer._TempBufferInt32View[1] = y; this.updateUniform(name260, _UniformBuffer._TempBuffer, 2); } _updateInt3ForEffect(name260, x, y, z, suffix = "") { this._currentEffect.setInt3(name260 + suffix, x, y, z); } _updateInt3ForUniform(name260, x, y, z) { _UniformBuffer._TempBufferInt32View[0] = x; _UniformBuffer._TempBufferInt32View[1] = y; _UniformBuffer._TempBufferInt32View[2] = z; this.updateUniform(name260, _UniformBuffer._TempBuffer, 3); } _updateInt4ForEffect(name260, x, y, z, w, suffix = "") { this._currentEffect.setInt4(name260 + suffix, x, y, z, w); } _updateInt4ForUniform(name260, x, y, z, w) { _UniformBuffer._TempBufferInt32View[0] = x; _UniformBuffer._TempBufferInt32View[1] = y; _UniformBuffer._TempBufferInt32View[2] = z; _UniformBuffer._TempBufferInt32View[3] = w; this.updateUniform(name260, _UniformBuffer._TempBuffer, 4); } _updateUIntForEffect(name260, x, suffix = "") { this._currentEffect.setUInt(name260 + suffix, x); } _updateUIntForUniform(name260, x) { _UniformBuffer._TempBufferUInt32View[0] = x; this.updateUniform(name260, _UniformBuffer._TempBuffer, 1); } _updateUInt2ForEffect(name260, x, y, suffix = "") { this._currentEffect.setUInt2(name260 + suffix, x, y); } _updateUInt2ForUniform(name260, x, y) { _UniformBuffer._TempBufferUInt32View[0] = x; _UniformBuffer._TempBufferUInt32View[1] = y; this.updateUniform(name260, _UniformBuffer._TempBuffer, 2); } _updateUInt3ForEffect(name260, x, y, z, suffix = "") { this._currentEffect.setUInt3(name260 + suffix, x, y, z); } _updateUInt3ForUniform(name260, x, y, z) { _UniformBuffer._TempBufferUInt32View[0] = x; _UniformBuffer._TempBufferUInt32View[1] = y; _UniformBuffer._TempBufferUInt32View[2] = z; this.updateUniform(name260, _UniformBuffer._TempBuffer, 3); } _updateUInt4ForEffect(name260, x, y, z, w, suffix = "") { this._currentEffect.setUInt4(name260 + suffix, x, y, z, w); } _updateUInt4ForUniform(name260, x, y, z, w) { _UniformBuffer._TempBufferUInt32View[0] = x; _UniformBuffer._TempBufferUInt32View[1] = y; _UniformBuffer._TempBufferUInt32View[2] = z; _UniformBuffer._TempBufferUInt32View[3] = w; this.updateUniform(name260, _UniformBuffer._TempBuffer, 4); } /** * Sets a sampler uniform on the effect. * @param name Define the name of the sampler. * @param texture Define the texture to set in the sampler */ setTexture(name260, texture) { this._currentEffect.setTexture(name260, texture); } /** * Sets an array of sampler uniforms on the effect. * @param name Define the name of uniform. * @param textures Define the textures to set in the array of samplers */ setTextureArray(name260, textures) { this._currentEffect.setTextureArray(name260, textures); } /** * Sets a sampler uniform on the effect. * @param name Define the name of the sampler. * @param texture Define the (internal) texture to set in the sampler */ bindTexture(name260, texture) { this._currentEffect._bindTexture(name260, texture); } /** * Directly updates the value of the uniform in the cache AND on the GPU. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader. * @param data Define the flattened data */ updateUniformDirectly(uniformName, data) { this.updateUniform(uniformName, data, data.length); this.update(); } /** * Associates an effect to this uniform buffer * @param effect Define the effect to associate the buffer to * @param name Name of the uniform block in the shader. */ bindToEffect(effect, name260) { this._currentEffect = effect; this._currentEffectName = name260; } /** * Binds the current (GPU) buffer to the effect */ bindUniformBuffer() { if (!this._noUBO && this._buffer && this._currentEffect) { this._currentEffect.bindUniformBuffer(this._buffer, this._currentEffectName); } } /** * Dissociates the current effect from this uniform buffer */ unbindEffect() { this._currentEffect = void 0; this._currentEffectName = void 0; } /** * Sets the current state of the class (_bufferIndex, _buffer) to point to the data buffer passed in parameter if this buffer is one of the buffers handled by the class (meaning if it can be found in the _buffers array) * This method is meant to be able to update a buffer at any time: just call setDataBuffer to set the class in the right state, call some updateXXX methods and then call udpate() => that will update the GPU buffer on the graphic card * @param dataBuffer buffer to look for * @returns true if the buffer has been found and the class internal state points to it, else false */ setDataBuffer(dataBuffer) { if (!this._buffers) { return this._buffer === dataBuffer; } for (let b = 0; b < this._buffers.length; ++b) { const buffer = this._buffers[b]; if (buffer[0] === dataBuffer) { this._bufferIndex = b; this._buffer = dataBuffer; this._createBufferOnWrite = false; this._currentEffect = void 0; if (this._buffers.length > 1 && this._buffers[b][1]) { this._bufferData.set(this._buffers[b][1]); } this._valueCache = {}; this._currentFrameId = this._engine.frameId; return true; } } return false; } /** * Checks if the uniform buffer has a uniform with the given name. * @param name Name of the uniform to check * @returns True if the uniform exists, false otherwise. */ has(name260) { return this._uniformLocations[name260] !== void 0; } /** * Disposes the uniform buffer. */ dispose() { if (this._noUBO) { return; } const uniformBuffers = this._engine._uniformBuffers; const index = uniformBuffers.indexOf(this); if (index !== -1) { uniformBuffers[index] = uniformBuffers[uniformBuffers.length - 1]; uniformBuffers.pop(); } if (this._trackUBOsInFrame && this._buffers) { for (let i = 0; i < this._buffers.length; ++i) { const buffer = this._buffers[i][0]; this._engine._releaseBuffer(buffer); } } else if (this._buffer && this._engine._releaseBuffer(this._buffer)) { this._buffer = null; } } }; UniformBuffer._UpdatedUbosInFrame = {}; UniformBuffer._MAX_UNIFORM_SIZE = 256; UniformBuffer._TempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE); UniformBuffer._TempBufferInt32View = new Int32Array(UniformBuffer._TempBuffer.buffer); UniformBuffer._TempBufferUInt32View = new Uint32Array(UniformBuffer._TempBuffer.buffer); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Collisions/pickingInfo.js var PickingInfo; var init_pickingInfo = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Collisions/pickingInfo.js"() { init_math_vector(); init_buffer(); PickingInfo = class { static { __name(this, "PickingInfo"); } constructor() { this.hit = false; this.distance = 0; this.pickedPoint = null; this.pickedMesh = null; this.bu = 0; this.bv = 0; this.faceId = -1; this.subMeshFaceId = -1; this.subMeshId = 0; this.pickedSprite = null; this.thinInstanceIndex = -1; this.ray = null; this.originMesh = null; this.aimTransform = null; this.gripTransform = null; } /** * Gets the normal corresponding 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 (default: true) * @returns The normal corresponding to the face the pick collided with * @remarks Note that the returned normal will always point towards the picking ray. */ getNormal(useWorldCoordinates = false, useVerticesNormals = true) { if (!this.pickedMesh || useVerticesNormals && !this.pickedMesh.isVerticesDataPresent(VertexBuffer.NormalKind)) { return null; } let indices = this.pickedMesh.getIndices(); if (indices?.length === 0) { indices = null; } let result; const tmp0 = TmpVectors.Vector3[0]; const tmp1 = TmpVectors.Vector3[1]; const tmp2 = TmpVectors.Vector3[2]; if (useVerticesNormals) { const normals = this.pickedMesh.getVerticesData(VertexBuffer.NormalKind); let normal0 = indices ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3] * 3, tmp0) : tmp0.copyFromFloats(normals[this.faceId * 3 * 3], normals[this.faceId * 3 * 3 + 1], normals[this.faceId * 3 * 3 + 2]); let normal1 = indices ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3 + 1] * 3, tmp1) : tmp1.copyFromFloats(normals[(this.faceId * 3 + 1) * 3], normals[(this.faceId * 3 + 1) * 3 + 1], normals[(this.faceId * 3 + 1) * 3 + 2]); let normal2 = indices ? Vector3.FromArrayToRef(normals, indices[this.faceId * 3 + 2] * 3, tmp2) : tmp2.copyFromFloats(normals[(this.faceId * 3 + 2) * 3], normals[(this.faceId * 3 + 2) * 3 + 1], normals[(this.faceId * 3 + 2) * 3 + 2]); normal0 = normal0.scale(this.bu); normal1 = normal1.scale(this.bv); normal2 = normal2.scale(1 - this.bu - this.bv); result = new Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z); } else { const positions = this.pickedMesh.getVerticesData(VertexBuffer.PositionKind); const vertex1 = indices ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3] * 3, tmp0) : tmp0.copyFromFloats(positions[this.faceId * 3 * 3], positions[this.faceId * 3 * 3 + 1], positions[this.faceId * 3 * 3 + 2]); const vertex2 = indices ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3 + 1] * 3, tmp1) : tmp1.copyFromFloats(positions[(this.faceId * 3 + 1) * 3], positions[(this.faceId * 3 + 1) * 3 + 1], positions[(this.faceId * 3 + 1) * 3 + 2]); const vertex3 = indices ? Vector3.FromArrayToRef(positions, indices[this.faceId * 3 + 2] * 3, tmp2) : tmp2.copyFromFloats(positions[(this.faceId * 3 + 2) * 3], positions[(this.faceId * 3 + 2) * 3 + 1], positions[(this.faceId * 3 + 2) * 3 + 2]); const p1p2 = vertex1.subtract(vertex2); const p3p2 = vertex3.subtract(vertex2); result = Vector3.Cross(p1p2, p3p2); } const transformNormalToWorld = /* @__PURE__ */ __name((pickedMesh, n) => { if (this.thinInstanceIndex !== -1) { const tm = pickedMesh.thinInstanceGetWorldMatrices()[this.thinInstanceIndex]; if (tm) { Vector3.TransformNormalToRef(n, tm, n); } } let wm = pickedMesh.getWorldMatrix(); if (pickedMesh.nonUniformScaling) { TmpVectors.Matrix[0].copyFrom(wm); wm = TmpVectors.Matrix[0]; wm.setTranslationFromFloats(0, 0, 0); wm.invert(); wm.transposeToRef(TmpVectors.Matrix[1]); wm = TmpVectors.Matrix[1]; } Vector3.TransformNormalToRef(n, wm, n); }, "transformNormalToWorld"); if (useWorldCoordinates) { transformNormalToWorld(this.pickedMesh, result); } if (this.ray) { const normalForDirectionChecking = TmpVectors.Vector3[0].copyFrom(result); if (!useWorldCoordinates) { transformNormalToWorld(this.pickedMesh, normalForDirectionChecking); } if (Vector3.Dot(normalForDirectionChecking, this.ray.direction) > 0) { result.negateInPlace(); } } result.normalize(); return result; } /** * Gets the texture coordinates of where the pick occurred * @param uvSet The UV set to use to calculate the texture coordinates (default: VertexBuffer.UVKind) * @returns The vector containing the coordinates of the texture */ getTextureCoordinates(uvSet = VertexBuffer.UVKind) { if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(uvSet)) { return null; } const indices = this.pickedMesh.getIndices(); if (!indices) { return null; } const uvs = this.pickedMesh.getVerticesData(uvSet); if (!uvs) { return null; } let uv0 = Vector2.FromArray(uvs, indices[this.faceId * 3] * 2); let uv1 = Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2); let uv2 = Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2); uv0 = uv0.scale(this.bu); uv1 = uv1.scale(this.bv); uv2 = uv2.scale(1 - this.bu - this.bv); return new Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Actions/actionEvent.js var ActionEvent; var init_actionEvent = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Actions/actionEvent.js"() { ActionEvent = class _ActionEvent { static { __name(this, "ActionEvent"); } /** * 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 */ constructor(source, pointerX, pointerY, meshUnderPointer, sourceEvent, 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 */ static CreateNew(source, evt, additionalData) { const 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 */ static CreateNewFromSprite(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 */ static CreateNewFromScene(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 */ static CreateNewFromPrimitive(prim, pointerPos, evt, additionalData) { return new _ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/floatingOriginMatrixOverrides.js function OffsetWorldToRef(offset, world, ref) { const refArray = ref.asArray(); const worldArray = world.asArray(); for (let i = 0; i < 16; i++) { refArray[i] = worldArray[i]; } refArray[12] -= offset.x; refArray[13] -= offset.y; refArray[14] -= offset.z; Matrix.FromArrayToRef(refArray, 0, ref); return ref; } function OffsetViewToRef(view, ref) { const refArray = ref.asArray(); const viewArray = view.asArray(); for (let i = 0; i < 16; i++) { refArray[i] = viewArray[i]; } refArray[12] = 0; refArray[13] = 0; refArray[14] = 0; Matrix.FromArrayToRef(refArray, 0, ref); return ref; } function OffsetViewProjectionToRef(view, projection, ref) { MultiplyMatricesToRef(OffsetViewToRef(view, ref), projection, ref); return ref; } function OffsetWorldViewToRef(offset, worldView, view, ref) { InvertMatrixToRef(view, TempMat1); MultiplyMatricesToRef(worldView, TempMat1, TempMat2); OffsetWorldToRef(offset, TempMat2, TempMat1); OffsetViewToRef(view, TempMat2); MultiplyMatricesToRef(TempMat1, TempMat2, ref); return ref; } function OffsetWorldViewProjectionToRef(offset, worldViewProjection, viewProjection, view, projection, ref) { InvertMatrixToRef(viewProjection, TempMat1); MultiplyMatricesToRef(worldViewProjection, TempMat1, TempMat2); OffsetWorldToRef(offset, TempMat2, TempMat1); OffsetViewProjectionToRef(view, projection, TempMat2); MultiplyMatricesToRef(TempMat1, TempMat2, ref); return ref; } function GetOffsetMatrix(uniformName, mat) { TempFinalMat.updateFlag = mat.updateFlag; const scene = FloatingOriginCurrentScene.getScene(); if (!scene) { return mat; } const offset = scene.floatingOriginOffset; switch (uniformName) { case "world": return OffsetWorldToRef(offset, mat, TempFinalMat); case "view": return OffsetViewToRef(mat, TempFinalMat); case "worldView": return OffsetWorldViewToRef(offset, mat, scene.getViewMatrix(), TempFinalMat); case "viewProjection": return OffsetViewProjectionToRef(scene.getViewMatrix(), scene.getProjectionMatrix(), TempFinalMat); case "worldViewProjection": return OffsetWorldViewProjectionToRef(offset, mat, scene.getTransformMatrix(), scene.getViewMatrix(), scene.getProjectionMatrix(), TempFinalMat); default: return mat; } } function ResetMatrixFunctions() { Effect.prototype.setMatrix = OriginalSetMatrix; EffectInternal._setMatrixOverride = void 0; UniformBufferInternal.prototype._updateMatrixForUniform = OriginalUpdateMatrixForUniform; UniformBufferInternal.prototype._updateMatrixForUniformOverride = void 0; } function OverrideMatrixFunctions() { EffectInternal.prototype._setMatrixOverride = OriginalSetMatrix; EffectInternal.prototype.setMatrix = function(uniformName, matrix) { this._setMatrixOverride(uniformName, GetOffsetMatrix(uniformName, matrix)); return this; }; UniformBufferInternal.prototype._updateMatrixForUniformOverride = OriginalUpdateMatrixForUniform; UniformBufferInternal.prototype._updateMatrixForUniform = function(uniformName, matrix) { this._updateMatrixForUniformOverride(uniformName, GetOffsetMatrix(uniformName, matrix)); }; } var TempFinalMat, TempMat1, TempMat2, FloatingOriginCurrentScene, UniformBufferInternal, EffectInternal, OriginalUpdateMatrixForUniform, OriginalSetMatrix; var init_floatingOriginMatrixOverrides = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/floatingOriginMatrixOverrides.js"() { init_effect(); init_math_vector(); init_thinMath_matrix_functions(); init_uniformBuffer(); TempFinalMat = new Matrix(); TempMat1 = new Matrix(); TempMat2 = new Matrix(); FloatingOriginCurrentScene = { getScene: /* @__PURE__ */ __name(() => void 0, "getScene") }; __name(OffsetWorldToRef, "OffsetWorldToRef"); __name(OffsetViewToRef, "OffsetViewToRef"); __name(OffsetViewProjectionToRef, "OffsetViewProjectionToRef"); __name(OffsetWorldViewToRef, "OffsetWorldViewToRef"); __name(OffsetWorldViewProjectionToRef, "OffsetWorldViewProjectionToRef"); __name(GetOffsetMatrix, "GetOffsetMatrix"); UniformBufferInternal = UniformBuffer; EffectInternal = Effect; OriginalUpdateMatrixForUniform = UniformBufferInternal.prototype._updateMatrixForUniform; OriginalSetMatrix = Effect.prototype.setMatrix; __name(ResetMatrixFunctions, "ResetMatrixFunctions"); __name(OverrideMatrixFunctions, "OverrideMatrixFunctions"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/sceneComponent.js var SceneComponentConstants, Stage; var init_sceneComponent = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/sceneComponent.js"() { SceneComponentConstants = class { static { __name(this, "SceneComponentConstants"); } }; SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer"; SceneComponentConstants.NAME_LAYER = "Layer"; SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem"; SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer"; SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem"; SceneComponentConstants.NAME_GAMEPAD = "Gamepad"; SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue"; SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer"; SceneComponentConstants.NAME_PREPASSRENDERER = "PrePassRenderer"; SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer"; SceneComponentConstants.NAME_DEPTHPEELINGRENDERER = "DepthPeelingRenderer"; SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager"; SceneComponentConstants.NAME_SPRITE = "Sprite"; SceneComponentConstants.NAME_SUBSURFACE = "SubSurface"; SceneComponentConstants.NAME_OUTLINERENDERER = "Outline"; SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture"; SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator"; SceneComponentConstants.NAME_OCTREE = "Octree"; SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine"; SceneComponentConstants.NAME_AUDIO = "Audio"; SceneComponentConstants.NAME_FLUIDRENDERER = "FluidRenderer"; SceneComponentConstants.NAME_IBLCDFGENERATOR = "iblCDFGenerator"; SceneComponentConstants.NAME_CLUSTEREDLIGHTING = "ClusteredLighting"; SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0; SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0; SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0; SceneComponentConstants.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER = 0; SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1; SceneComponentConstants.STEP_BEFORECAMERADRAW_PREPASS = 0; SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 1; SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 2; SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_PREPASS = 0; SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER = 1; SceneComponentConstants.STEP_BEFORERENDERINGMESH_PREPASS = 0; SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 1; SceneComponentConstants.STEP_AFTERRENDERINGMESH_PREPASS = 0; SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 1; SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0; SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1; SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0; SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0; SceneComponentConstants.STEP_BEFORECLEAR_PREPASS = 1; SceneComponentConstants.STEP_BEFORERENDERTARGETCLEAR_PREPASS = 0; SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_PREPASS = 0; SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER = 1; SceneComponentConstants.STEP_AFTERCAMERADRAW_PREPASS = 0; SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 1; SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 2; SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 3; SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 4; SceneComponentConstants.STEP_AFTERCAMERADRAW_FLUIDRENDERER = 5; SceneComponentConstants.STEP_AFTERCAMERAPOSTPROCESS_LAYER = 0; SceneComponentConstants.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER = 0; SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0; SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 0; SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1; SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 2; SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3; SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0; SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER = 1; SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_CLUSTEREDLIGHTING = 2; SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0; SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0; SceneComponentConstants.STEP_POINTERUP_SPRITE = 0; Stage = class _Stage extends Array { static { __name(this, "Stage"); } /** * Hide ctor from the rest of the world. * @param items The items to add. */ constructor(items) { super(...items); } /** * Creates a new Stage. * @returns A new instance of a Stage */ static Create() { return Object.create(_Stage.prototype); } /** * Registers a step in an ordered way in the targeted stage. * @param index Defines the position to register the step in * @param component Defines the component attached to the step * @param action Defines the action to launch during the step */ registerStep(index, component, action) { let i = 0; let maxIndex = Number.MAX_VALUE; for (; i < this.length; i++) { const step = this[i]; maxIndex = step.index; if (index < maxIndex) { break; } } this.splice(i, 0, { index, component, action: action.bind(component) }); } /** * Clears all the steps from the stage. */ clear() { this.length = 0; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Events/pointerEvents.js var PointerEventTypes, PointerInfoBase, PointerInfoPre, PointerInfo; var init_pointerEvents = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Events/pointerEvents.js"() { init_math_vector(); PointerEventTypes = class { static { __name(this, "PointerEventTypes"); } }; PointerEventTypes.POINTERDOWN = 1; PointerEventTypes.POINTERUP = 2; PointerEventTypes.POINTERMOVE = 4; PointerEventTypes.POINTERWHEEL = 8; PointerEventTypes.POINTERPICK = 16; PointerEventTypes.POINTERTAP = 32; PointerEventTypes.POINTERDOUBLETAP = 64; PointerInfoBase = class { static { __name(this, "PointerInfoBase"); } /** * Instantiates the base class of pointers info. * @param type Defines the type of event (PointerEventTypes) * @param event Defines the related dom event */ constructor(type, event) { this.type = type; this.event = event; } }; PointerInfoPre = class extends PointerInfoBase { static { __name(this, "PointerInfoPre"); } /** * 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 */ constructor(type, event, localX, localY) { super(type, event); this.ray = null; this.originalPickingInfo = null; this.skipOnPointerObservable = false; this.localPosition = new Vector2(localX, localY); } }; PointerInfo = class extends PointerInfoBase { static { __name(this, "PointerInfo"); } /** * Defines the picking info associated with this PointerInfo object (if applicable) */ get pickInfo() { if (!this._pickInfo) { this._generatePickInfo(); } return this._pickInfo; } /** * 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) * @param inputManager Defines the InputManager to use if there is no pickInfo */ constructor(type, event, pickInfo, inputManager = null) { super(type, event); this._pickInfo = pickInfo; this._inputManager = inputManager; } /** * Generates the picking info if needed */ /** @internal */ _generatePickInfo() { if (this._inputManager) { this._pickInfo = this._inputManager._pickMove(this.event); this._inputManager._setRayOnPointerInfo(this._pickInfo, this.event); this._inputManager = null; } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Actions/abstractActionManager.js var AbstractActionManager; var init_abstractActionManager = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Actions/abstractActionManager.js"() { AbstractActionManager = class _AbstractActionManager { static { __name(this, "AbstractActionManager"); } constructor() { this.hoverCursor = ""; this.actions = []; this.isRecursive = false; this.disposeWhenUnowned = true; } /** * Does exist one action manager with at least one trigger **/ static get HasTriggers() { for (const t in _AbstractActionManager.Triggers) { if (Object.prototype.hasOwnProperty.call(_AbstractActionManager.Triggers, t)) { return true; } } return false; } /** * Does exist one action manager with at least one pick trigger **/ static get HasPickTriggers() { for (const t in _AbstractActionManager.Triggers) { if (Object.prototype.hasOwnProperty.call(_AbstractActionManager.Triggers, t)) { const tAsInt = parseInt(t); if (tAsInt >= 1 && tAsInt <= 7) { return true; } } } return false; } /** * Does exist one action manager that handles actions of a given trigger * @param trigger defines the trigger to be tested * @returns a boolean indicating whether the trigger is handled by at least one action manager **/ static HasSpecificTrigger(trigger) { for (const t in _AbstractActionManager.Triggers) { if (Object.prototype.hasOwnProperty.call(_AbstractActionManager.Triggers, t)) { const tAsInt = parseInt(t); if (tAsInt === trigger) { return true; } } } return false; } }; AbstractActionManager.Triggers = {}; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Events/keyboardEvents.js var KeyboardEventTypes, KeyboardInfo, KeyboardInfoPre; var init_keyboardEvents = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Events/keyboardEvents.js"() { KeyboardEventTypes = class { static { __name(this, "KeyboardEventTypes"); } }; KeyboardEventTypes.KEYDOWN = 1; KeyboardEventTypes.KEYUP = 2; KeyboardInfo = class { static { __name(this, "KeyboardInfo"); } /** * 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 */ constructor(type, event) { this.type = type; this.event = event; } }; KeyboardInfoPre = class extends KeyboardInfo { static { __name(this, "KeyboardInfoPre"); } /** * Defines whether the engine should skip the next onKeyboardObservable associated to this pre. * @deprecated use skipOnKeyboardObservable property instead */ get skipOnPointerObservable() { return this.skipOnKeyboardObservable; } set skipOnPointerObservable(value) { this.skipOnKeyboardObservable = value; } /** * 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 */ constructor(type, event) { super(type, event); this.type = type; this.event = event; this.skipOnKeyboardObservable = false; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceEnums.js var DeviceType, PointerInput, NativePointerInput, DualShockInput, DualSenseInput, XboxInput, SwitchInput; var init_deviceEnums = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceEnums.js"() { (function(DeviceType2) { DeviceType2[DeviceType2["Generic"] = 0] = "Generic"; DeviceType2[DeviceType2["Keyboard"] = 1] = "Keyboard"; DeviceType2[DeviceType2["Mouse"] = 2] = "Mouse"; DeviceType2[DeviceType2["Touch"] = 3] = "Touch"; DeviceType2[DeviceType2["DualShock"] = 4] = "DualShock"; DeviceType2[DeviceType2["Xbox"] = 5] = "Xbox"; DeviceType2[DeviceType2["Switch"] = 6] = "Switch"; DeviceType2[DeviceType2["DualSense"] = 7] = "DualSense"; })(DeviceType || (DeviceType = {})); (function(PointerInput2) { PointerInput2[PointerInput2["Horizontal"] = 0] = "Horizontal"; PointerInput2[PointerInput2["Vertical"] = 1] = "Vertical"; PointerInput2[PointerInput2["LeftClick"] = 2] = "LeftClick"; PointerInput2[PointerInput2["MiddleClick"] = 3] = "MiddleClick"; PointerInput2[PointerInput2["RightClick"] = 4] = "RightClick"; PointerInput2[PointerInput2["BrowserBack"] = 5] = "BrowserBack"; PointerInput2[PointerInput2["BrowserForward"] = 6] = "BrowserForward"; PointerInput2[PointerInput2["MouseWheelX"] = 7] = "MouseWheelX"; PointerInput2[PointerInput2["MouseWheelY"] = 8] = "MouseWheelY"; PointerInput2[PointerInput2["MouseWheelZ"] = 9] = "MouseWheelZ"; PointerInput2[PointerInput2["Move"] = 12] = "Move"; })(PointerInput || (PointerInput = {})); (function(NativePointerInput2) { NativePointerInput2[NativePointerInput2["Horizontal"] = 0] = "Horizontal"; NativePointerInput2[NativePointerInput2["Vertical"] = 1] = "Vertical"; NativePointerInput2[NativePointerInput2["LeftClick"] = 2] = "LeftClick"; NativePointerInput2[NativePointerInput2["MiddleClick"] = 3] = "MiddleClick"; NativePointerInput2[NativePointerInput2["RightClick"] = 4] = "RightClick"; NativePointerInput2[NativePointerInput2["BrowserBack"] = 5] = "BrowserBack"; NativePointerInput2[NativePointerInput2["BrowserForward"] = 6] = "BrowserForward"; NativePointerInput2[NativePointerInput2["MouseWheelX"] = 7] = "MouseWheelX"; NativePointerInput2[NativePointerInput2["MouseWheelY"] = 8] = "MouseWheelY"; NativePointerInput2[NativePointerInput2["MouseWheelZ"] = 9] = "MouseWheelZ"; NativePointerInput2[NativePointerInput2["DeltaHorizontal"] = 10] = "DeltaHorizontal"; NativePointerInput2[NativePointerInput2["DeltaVertical"] = 11] = "DeltaVertical"; })(NativePointerInput || (NativePointerInput = {})); (function(DualShockInput2) { DualShockInput2[DualShockInput2["Cross"] = 0] = "Cross"; DualShockInput2[DualShockInput2["Circle"] = 1] = "Circle"; DualShockInput2[DualShockInput2["Square"] = 2] = "Square"; DualShockInput2[DualShockInput2["Triangle"] = 3] = "Triangle"; DualShockInput2[DualShockInput2["L1"] = 4] = "L1"; DualShockInput2[DualShockInput2["R1"] = 5] = "R1"; DualShockInput2[DualShockInput2["L2"] = 6] = "L2"; DualShockInput2[DualShockInput2["R2"] = 7] = "R2"; DualShockInput2[DualShockInput2["Share"] = 8] = "Share"; DualShockInput2[DualShockInput2["Options"] = 9] = "Options"; DualShockInput2[DualShockInput2["L3"] = 10] = "L3"; DualShockInput2[DualShockInput2["R3"] = 11] = "R3"; DualShockInput2[DualShockInput2["DPadUp"] = 12] = "DPadUp"; DualShockInput2[DualShockInput2["DPadDown"] = 13] = "DPadDown"; DualShockInput2[DualShockInput2["DPadLeft"] = 14] = "DPadLeft"; DualShockInput2[DualShockInput2["DPadRight"] = 15] = "DPadRight"; DualShockInput2[DualShockInput2["Home"] = 16] = "Home"; DualShockInput2[DualShockInput2["TouchPad"] = 17] = "TouchPad"; DualShockInput2[DualShockInput2["LStickXAxis"] = 18] = "LStickXAxis"; DualShockInput2[DualShockInput2["LStickYAxis"] = 19] = "LStickYAxis"; DualShockInput2[DualShockInput2["RStickXAxis"] = 20] = "RStickXAxis"; DualShockInput2[DualShockInput2["RStickYAxis"] = 21] = "RStickYAxis"; })(DualShockInput || (DualShockInput = {})); (function(DualSenseInput2) { DualSenseInput2[DualSenseInput2["Cross"] = 0] = "Cross"; DualSenseInput2[DualSenseInput2["Circle"] = 1] = "Circle"; DualSenseInput2[DualSenseInput2["Square"] = 2] = "Square"; DualSenseInput2[DualSenseInput2["Triangle"] = 3] = "Triangle"; DualSenseInput2[DualSenseInput2["L1"] = 4] = "L1"; DualSenseInput2[DualSenseInput2["R1"] = 5] = "R1"; DualSenseInput2[DualSenseInput2["L2"] = 6] = "L2"; DualSenseInput2[DualSenseInput2["R2"] = 7] = "R2"; DualSenseInput2[DualSenseInput2["Create"] = 8] = "Create"; DualSenseInput2[DualSenseInput2["Options"] = 9] = "Options"; DualSenseInput2[DualSenseInput2["L3"] = 10] = "L3"; DualSenseInput2[DualSenseInput2["R3"] = 11] = "R3"; DualSenseInput2[DualSenseInput2["DPadUp"] = 12] = "DPadUp"; DualSenseInput2[DualSenseInput2["DPadDown"] = 13] = "DPadDown"; DualSenseInput2[DualSenseInput2["DPadLeft"] = 14] = "DPadLeft"; DualSenseInput2[DualSenseInput2["DPadRight"] = 15] = "DPadRight"; DualSenseInput2[DualSenseInput2["Home"] = 16] = "Home"; DualSenseInput2[DualSenseInput2["TouchPad"] = 17] = "TouchPad"; DualSenseInput2[DualSenseInput2["LStickXAxis"] = 18] = "LStickXAxis"; DualSenseInput2[DualSenseInput2["LStickYAxis"] = 19] = "LStickYAxis"; DualSenseInput2[DualSenseInput2["RStickXAxis"] = 20] = "RStickXAxis"; DualSenseInput2[DualSenseInput2["RStickYAxis"] = 21] = "RStickYAxis"; })(DualSenseInput || (DualSenseInput = {})); (function(XboxInput2) { XboxInput2[XboxInput2["A"] = 0] = "A"; XboxInput2[XboxInput2["B"] = 1] = "B"; XboxInput2[XboxInput2["X"] = 2] = "X"; XboxInput2[XboxInput2["Y"] = 3] = "Y"; XboxInput2[XboxInput2["LB"] = 4] = "LB"; XboxInput2[XboxInput2["RB"] = 5] = "RB"; XboxInput2[XboxInput2["LT"] = 6] = "LT"; XboxInput2[XboxInput2["RT"] = 7] = "RT"; XboxInput2[XboxInput2["Back"] = 8] = "Back"; XboxInput2[XboxInput2["Start"] = 9] = "Start"; XboxInput2[XboxInput2["LS"] = 10] = "LS"; XboxInput2[XboxInput2["RS"] = 11] = "RS"; XboxInput2[XboxInput2["DPadUp"] = 12] = "DPadUp"; XboxInput2[XboxInput2["DPadDown"] = 13] = "DPadDown"; XboxInput2[XboxInput2["DPadLeft"] = 14] = "DPadLeft"; XboxInput2[XboxInput2["DPadRight"] = 15] = "DPadRight"; XboxInput2[XboxInput2["Home"] = 16] = "Home"; XboxInput2[XboxInput2["LStickXAxis"] = 17] = "LStickXAxis"; XboxInput2[XboxInput2["LStickYAxis"] = 18] = "LStickYAxis"; XboxInput2[XboxInput2["RStickXAxis"] = 19] = "RStickXAxis"; XboxInput2[XboxInput2["RStickYAxis"] = 20] = "RStickYAxis"; })(XboxInput || (XboxInput = {})); (function(SwitchInput2) { SwitchInput2[SwitchInput2["B"] = 0] = "B"; SwitchInput2[SwitchInput2["A"] = 1] = "A"; SwitchInput2[SwitchInput2["Y"] = 2] = "Y"; SwitchInput2[SwitchInput2["X"] = 3] = "X"; SwitchInput2[SwitchInput2["L"] = 4] = "L"; SwitchInput2[SwitchInput2["R"] = 5] = "R"; SwitchInput2[SwitchInput2["ZL"] = 6] = "ZL"; SwitchInput2[SwitchInput2["ZR"] = 7] = "ZR"; SwitchInput2[SwitchInput2["Minus"] = 8] = "Minus"; SwitchInput2[SwitchInput2["Plus"] = 9] = "Plus"; SwitchInput2[SwitchInput2["LS"] = 10] = "LS"; SwitchInput2[SwitchInput2["RS"] = 11] = "RS"; SwitchInput2[SwitchInput2["DPadUp"] = 12] = "DPadUp"; SwitchInput2[SwitchInput2["DPadDown"] = 13] = "DPadDown"; SwitchInput2[SwitchInput2["DPadLeft"] = 14] = "DPadLeft"; SwitchInput2[SwitchInput2["DPadRight"] = 15] = "DPadRight"; SwitchInput2[SwitchInput2["Home"] = 16] = "Home"; SwitchInput2[SwitchInput2["Capture"] = 17] = "Capture"; SwitchInput2[SwitchInput2["LStickXAxis"] = 18] = "LStickXAxis"; SwitchInput2[SwitchInput2["LStickYAxis"] = 19] = "LStickYAxis"; SwitchInput2[SwitchInput2["RStickXAxis"] = 20] = "RStickXAxis"; SwitchInput2[SwitchInput2["RStickYAxis"] = 21] = "RStickYAxis"; })(SwitchInput || (SwitchInput = {})); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Events/deviceInputEvents.js var DeviceInputEventType, EventConstants; var init_deviceInputEvents = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Events/deviceInputEvents.js"() { (function(DeviceInputEventType2) { DeviceInputEventType2[DeviceInputEventType2["PointerMove"] = 0] = "PointerMove"; DeviceInputEventType2[DeviceInputEventType2["PointerDown"] = 1] = "PointerDown"; DeviceInputEventType2[DeviceInputEventType2["PointerUp"] = 2] = "PointerUp"; })(DeviceInputEventType || (DeviceInputEventType = {})); EventConstants = class { static { __name(this, "EventConstants"); } }; EventConstants.DOM_DELTA_PIXEL = 0; EventConstants.DOM_DELTA_LINE = 1; EventConstants.DOM_DELTA_PAGE = 2; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/eventFactory.js var DeviceEventFactory; var init_eventFactory = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/eventFactory.js"() { init_deviceInputEvents(); init_deviceEnums(); DeviceEventFactory = class { static { __name(this, "DeviceEventFactory"); } /** * Create device input events based on provided type and slot * * @param deviceType Type of device * @param deviceSlot "Slot" or index that device is referenced in * @param inputIndex Id of input to be checked * @param currentState Current value for given input * @param deviceInputSystem Reference to DeviceInputSystem * @param elementToAttachTo HTMLElement to reference as target for inputs * @param pointerId PointerId to use for pointer events * @returns IUIEvent object */ static CreateDeviceEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId) { switch (deviceType) { case DeviceType.Keyboard: return this._CreateKeyboardEvent(inputIndex, currentState, deviceInputSystem, elementToAttachTo); case DeviceType.Mouse: if (inputIndex === PointerInput.MouseWheelX || inputIndex === PointerInput.MouseWheelY || inputIndex === PointerInput.MouseWheelZ) { return this._CreateWheelEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo); } // eslint-disable-next-line no-fallthrough case DeviceType.Touch: return this._CreatePointerEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId); default: throw `Unable to generate event for device ${DeviceType[deviceType]}`; } } /** * Creates pointer event * * @param deviceType Type of device * @param deviceSlot "Slot" or index that device is referenced in * @param inputIndex Id of input to be checked * @param currentState Current value for given input * @param deviceInputSystem Reference to DeviceInputSystem * @param elementToAttachTo HTMLElement to reference as target for inputs * @param pointerId PointerId to use for pointer events * @returns IUIEvent object (Pointer) */ static _CreatePointerEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo, pointerId) { const evt = this._CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo); if (deviceType === DeviceType.Mouse) { evt.deviceType = DeviceType.Mouse; evt.pointerId = 1; evt.pointerType = "mouse"; } else { evt.deviceType = DeviceType.Touch; evt.pointerId = pointerId ?? deviceSlot; evt.pointerType = "touch"; } let buttons = 0; buttons += deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.LeftClick); buttons += deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.RightClick) * 2; buttons += deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.MiddleClick) * 4; evt.buttons = buttons; if (inputIndex === PointerInput.Move) { evt.type = "pointermove"; } else if (inputIndex >= PointerInput.LeftClick && inputIndex <= PointerInput.RightClick) { evt.type = currentState === 1 ? "pointerdown" : "pointerup"; evt.button = inputIndex - 2; } return evt; } /** * Create Mouse Wheel Event * @param deviceType Type of device * @param deviceSlot "Slot" or index that device is referenced in * @param inputIndex Id of input to be checked * @param currentState Current value for given input * @param deviceInputSystem Reference to DeviceInputSystem * @param elementToAttachTo HTMLElement to reference as target for inputs * @returns IUIEvent object (Wheel) */ static _CreateWheelEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo) { const evt = this._CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo); evt.pointerId = 1; evt.type = "wheel"; evt.deltaMode = EventConstants.DOM_DELTA_PIXEL; evt.deltaX = 0; evt.deltaY = 0; evt.deltaZ = 0; switch (inputIndex) { case PointerInput.MouseWheelX: evt.deltaX = currentState; break; case PointerInput.MouseWheelY: evt.deltaY = currentState; break; case PointerInput.MouseWheelZ: evt.deltaZ = currentState; break; } return evt; } /** * Create Mouse Event * @param deviceType Type of device * @param deviceSlot "Slot" or index that device is referenced in * @param inputIndex Id of input to be checked * @param currentState Current value for given input * @param deviceInputSystem Reference to DeviceInputSystem * @param elementToAttachTo HTMLElement to reference as target for inputs * @returns IUIEvent object (Mouse) */ static _CreateMouseEvent(deviceType, deviceSlot, inputIndex, currentState, deviceInputSystem, elementToAttachTo) { const evt = this._CreateEvent(elementToAttachTo); const pointerX = deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.Horizontal); const pointerY = deviceInputSystem.pollInput(deviceType, deviceSlot, PointerInput.Vertical); if (elementToAttachTo) { evt.movementX = 0; evt.movementY = 0; evt.offsetX = evt.movementX - elementToAttachTo.getBoundingClientRect().x; evt.offsetY = evt.movementY - elementToAttachTo.getBoundingClientRect().y; } else { evt.movementX = deviceInputSystem.pollInput( deviceType, deviceSlot, 10 /* NativePointerInput.DeltaHorizontal */ ); evt.movementY = deviceInputSystem.pollInput( deviceType, deviceSlot, 11 /* NativePointerInput.DeltaVertical */ ); evt.offsetX = 0; evt.offsetY = 0; } this._CheckNonCharacterKeys(evt, deviceInputSystem); evt.clientX = pointerX; evt.clientY = pointerY; evt.x = pointerX; evt.y = pointerY; evt.deviceType = deviceType; evt.deviceSlot = deviceSlot; evt.inputIndex = inputIndex; return evt; } /** * Create Keyboard Event * @param inputIndex Id of input to be checked * @param currentState Current value for given input * @param deviceInputSystem Reference to DeviceInputSystem * @param elementToAttachTo HTMLElement to reference as target for inputs * @returns IEvent object (Keyboard) */ static _CreateKeyboardEvent(inputIndex, currentState, deviceInputSystem, elementToAttachTo) { const evt = this._CreateEvent(elementToAttachTo); this._CheckNonCharacterKeys(evt, deviceInputSystem); evt.deviceType = DeviceType.Keyboard; evt.deviceSlot = 0; evt.inputIndex = inputIndex; evt.type = currentState === 1 ? "keydown" : "keyup"; evt.key = String.fromCharCode(inputIndex); evt.keyCode = inputIndex; return evt; } /** * Add parameters for non-character keys (Ctrl, Alt, Meta, Shift) * @param evt Event object to add parameters to * @param deviceInputSystem DeviceInputSystem to pull values from */ static _CheckNonCharacterKeys(evt, deviceInputSystem) { const isKeyboardActive = deviceInputSystem.isDeviceAvailable(DeviceType.Keyboard); const altKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 18) === 1; const ctrlKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 17) === 1; const metaKey = isKeyboardActive && (deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 91) === 1 || deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 92) === 1 || deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 93) === 1); const shiftKey = isKeyboardActive && deviceInputSystem.pollInput(DeviceType.Keyboard, 0, 16) === 1; evt.altKey = altKey; evt.ctrlKey = ctrlKey; evt.metaKey = metaKey; evt.shiftKey = shiftKey; } /** * Create base event object * @param elementToAttachTo Value to use as event target * @returns */ static _CreateEvent(elementToAttachTo) { const evt = {}; evt.preventDefault = () => { }; evt.target = elementToAttachTo; return evt; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/nativeDeviceInputSystem.js var NativeDeviceInputSystem; var init_nativeDeviceInputSystem = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/nativeDeviceInputSystem.js"() { init_eventFactory(); init_deviceEnums(); NativeDeviceInputSystem = class { static { __name(this, "NativeDeviceInputSystem"); } constructor(onDeviceConnected, onDeviceDisconnected, onInputChanged) { this._nativeInput = _native.DeviceInputSystem ? new _native.DeviceInputSystem(onDeviceConnected, onDeviceDisconnected, (deviceType, deviceSlot, inputIndex, currentState) => { const evt = DeviceEventFactory.CreateDeviceEvent(deviceType, deviceSlot, inputIndex, currentState, this); onInputChanged(deviceType, deviceSlot, evt); }) : this._createDummyNativeInput(); } // Public functions /** * Checks for current device input value, given an id and input index. Throws exception if requested device not initialized. * @param deviceType Enum specifying 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 */ pollInput(deviceType, deviceSlot, inputIndex) { return this._nativeInput.pollInput(deviceType, deviceSlot, inputIndex); } /** * Check for a specific device in the DeviceInputSystem * @param deviceType Type of device to check for * @returns bool with status of device's existence */ isDeviceAvailable(deviceType) { return deviceType === DeviceType.Mouse || deviceType === DeviceType.Touch; } /** * Dispose of all the observables */ dispose() { this._nativeInput.dispose(); } /** * For versions of BabylonNative that don't have the NativeInput plugin initialized, create a dummy version * @returns Object with dummy functions */ _createDummyNativeInput() { const nativeInput = { pollInput: /* @__PURE__ */ __name(() => { return 0; }, "pollInput"), isDeviceAvailable: /* @__PURE__ */ __name(() => { return false; }, "isDeviceAvailable"), dispose: /* @__PURE__ */ __name(() => { }, "dispose") }; return nativeInput; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/webDeviceInputSystem.js var MAX_KEYCODES, MAX_POINTER_INPUTS, WebDeviceInputSystem; var init_webDeviceInputSystem = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/webDeviceInputSystem.js"() { init_domManagement(); init_tools(); init_eventFactory(); init_deviceEnums(); MAX_KEYCODES = 255; MAX_POINTER_INPUTS = Object.keys(PointerInput).length / 2; WebDeviceInputSystem = class { static { __name(this, "WebDeviceInputSystem"); } /** * Constructor for the WebDeviceInputSystem * @param engine Engine to reference * @param onDeviceConnected Callback to execute when device is connected * @param onDeviceDisconnected Callback to execute when device is disconnected * @param onInputChanged Callback to execute when input changes on device */ constructor(engine, onDeviceConnected, onDeviceDisconnected, onInputChanged) { this._inputs = []; this._keyboardActive = false; this._pointerActive = false; this._usingSafari = Tools.IsSafari(); this._usingMacOs = IsNavigatorAvailable() && /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform); this._keyboardDownEvent = (evt) => { }; this._keyboardUpEvent = (evt) => { }; this._keyboardBlurEvent = (evt) => { }; this._pointerMoveEvent = (evt) => { }; this._pointerDownEvent = (evt) => { }; this._pointerUpEvent = (evt) => { }; this._pointerCancelEvent = (evt) => { }; this._pointerCancelTouch = (pointerId) => { }; this._pointerLeaveEvent = (evt) => { }; this._pointerWheelEvent = (evt) => { }; this._pointerBlurEvent = (evt) => { }; this._pointerMacOsChromeOutEvent = (evt) => { }; this._eventsAttached = false; this._mouseId = -1; this._isUsingFirefox = IsNavigatorAvailable() && navigator.userAgent && navigator.userAgent.indexOf("Firefox") !== -1; this._isUsingChromium = IsNavigatorAvailable() && navigator.userAgent && navigator.userAgent.indexOf("Chrome") !== -1; this._maxTouchPoints = 0; this._pointerInputClearObserver = null; this._gamepadConnectedEvent = (evt) => { }; this._gamepadDisconnectedEvent = (evt) => { }; this._eventPrefix = Tools.GetPointerPrefix(engine); this._engine = engine; this._onDeviceConnected = onDeviceConnected; this._onDeviceDisconnected = onDeviceDisconnected; this._onInputChanged = onInputChanged; this._mouseId = this._isUsingFirefox ? 0 : 1; this._enableEvents(); if (this._usingMacOs) { this._metaKeys = []; } if (!this._engine._onEngineViewChanged) { this._engine._onEngineViewChanged = () => { this._enableEvents(); }; } } // Public functions /** * Checks for current device input value, given an id and input index. Throws exception if requested device not initialized. * @param deviceType Enum specifying 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 */ pollInput(deviceType, deviceSlot, inputIndex) { const device = this._inputs[deviceType][deviceSlot]; if (!device) { throw `Unable to find device ${DeviceType[deviceType]}`; } if (deviceType >= DeviceType.DualShock && deviceType <= DeviceType.DualSense) { this._updateDevice(deviceType, deviceSlot, inputIndex); } const currentValue = device[inputIndex]; if (currentValue === void 0) { throw `Unable to find input ${inputIndex} for device ${DeviceType[deviceType]} in slot ${deviceSlot}`; } if (inputIndex === PointerInput.Move) { Tools.Warn(`Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data.`); } return currentValue; } /** * Check for a specific device in the DeviceInputSystem * @param deviceType Type of device to check for * @returns bool with status of device's existence */ isDeviceAvailable(deviceType) { return this._inputs[deviceType] !== void 0; } /** * Dispose of all the eventlisteners */ dispose() { this._onDeviceConnected = () => { }; this._onDeviceDisconnected = () => { }; this._onInputChanged = () => { }; delete this._engine._onEngineViewChanged; if (this._elementToAttachTo) { this._disableEvents(); } } /** * Enable listening for user input events */ _enableEvents() { const inputElement = this?._engine.getInputElement(); if (inputElement && (!this._eventsAttached || this._elementToAttachTo !== inputElement)) { this._disableEvents(); if (this._inputs) { for (const inputs of this._inputs) { if (inputs) { for (const deviceSlotKey in inputs) { const deviceSlot = +deviceSlotKey; const device = inputs[deviceSlot]; if (device) { for (let inputIndex = 0; inputIndex < device.length; inputIndex++) { device[inputIndex] = 0; } } } } } } this._elementToAttachTo = inputElement; this._elementToAttachTo.tabIndex = this._elementToAttachTo.tabIndex !== -1 ? this._elementToAttachTo.tabIndex : this._engine.canvasTabIndex; this._handleKeyActions(); this._handlePointerActions(); this._handleGamepadActions(); this._eventsAttached = true; this._checkForConnectedDevices(); } } /** * Disable listening for user input events */ _disableEvents() { if (this._elementToAttachTo) { this._elementToAttachTo.removeEventListener("blur", this._keyboardBlurEvent); this._elementToAttachTo.removeEventListener("blur", this._pointerBlurEvent); this._elementToAttachTo.removeEventListener("keydown", this._keyboardDownEvent); this._elementToAttachTo.removeEventListener("keyup", this._keyboardUpEvent); this._elementToAttachTo.removeEventListener(this._eventPrefix + "move", this._pointerMoveEvent); this._elementToAttachTo.removeEventListener(this._eventPrefix + "down", this._pointerDownEvent); this._elementToAttachTo.removeEventListener(this._eventPrefix + "up", this._pointerUpEvent); this._elementToAttachTo.removeEventListener(this._eventPrefix + "cancel", this._pointerCancelEvent); this._elementToAttachTo.removeEventListener(this._eventPrefix + "leave", this._pointerLeaveEvent); this._elementToAttachTo.removeEventListener(this._wheelEventName, this._pointerWheelEvent); if (this._usingMacOs && this._isUsingChromium) { this._elementToAttachTo.removeEventListener("lostpointercapture", this._pointerMacOsChromeOutEvent); } window.removeEventListener("gamepadconnected", this._gamepadConnectedEvent); window.removeEventListener("gamepaddisconnected", this._gamepadDisconnectedEvent); } if (this._pointerInputClearObserver) { this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver); } this._eventsAttached = false; } /** * Checks for existing connections to devices and register them, if necessary * Currently handles gamepads and mouse */ _checkForConnectedDevices() { if (navigator.getGamepads) { const gamepads = navigator.getGamepads(); for (const gamepad of gamepads) { if (gamepad) { this._addGamePad(gamepad); } } } if (typeof matchMedia === "function" && matchMedia("(pointer:fine)").matches) { this._addPointerDevice(DeviceType.Mouse, 0, 0, 0); } } // Private functions /** * Add a gamepad to the DeviceInputSystem * @param gamepad A single DOM Gamepad object */ _addGamePad(gamepad) { const deviceType = this._getGamepadDeviceType(gamepad.id); const deviceSlot = gamepad.index; this._gamepads = this._gamepads || new Array(gamepad.index + 1); this._registerDevice(deviceType, deviceSlot, gamepad.buttons.length + gamepad.axes.length); this._gamepads[deviceSlot] = deviceType; } /** * Add pointer device to DeviceInputSystem * @param deviceType Type of Pointer to add * @param deviceSlot Pointer ID (0 for mouse, pointerId for Touch) * @param currentX Current X at point of adding * @param currentY Current Y at point of adding */ _addPointerDevice(deviceType, deviceSlot, currentX, currentY) { if (!this._pointerActive) { this._pointerActive = true; } this._registerDevice(deviceType, deviceSlot, MAX_POINTER_INPUTS); const pointer = this._inputs[deviceType][deviceSlot]; pointer[0] = currentX; pointer[1] = currentY; } /** * Add device and inputs to device array * @param deviceType Enum specifying device type * @param deviceSlot "Slot" or index that device is referenced in * @param numberOfInputs Number of input entries to create for given device */ _registerDevice(deviceType, deviceSlot, numberOfInputs) { if (deviceSlot === void 0) { throw `Unable to register device ${DeviceType[deviceType]} to undefined slot.`; } if (!this._inputs[deviceType]) { this._inputs[deviceType] = {}; } if (!this._inputs[deviceType][deviceSlot]) { const device = new Array(numberOfInputs); device.fill(0); this._inputs[deviceType][deviceSlot] = device; this._onDeviceConnected(deviceType, deviceSlot); } } /** * Given a specific device name, remove that device from the device map * @param deviceType Enum specifying device type * @param deviceSlot "Slot" or index that device is referenced in */ _unregisterDevice(deviceType, deviceSlot) { if (this._inputs[deviceType][deviceSlot]) { delete this._inputs[deviceType][deviceSlot]; this._onDeviceDisconnected(deviceType, deviceSlot); } } /** * Handle all actions that come from keyboard interaction */ _handleKeyActions() { this._keyboardDownEvent = (evt) => { if (!this._keyboardActive) { this._keyboardActive = true; this._registerDevice(DeviceType.Keyboard, 0, MAX_KEYCODES); } const kbKey = this._inputs[DeviceType.Keyboard][0]; if (kbKey) { kbKey[evt.keyCode] = 1; const deviceEvent = evt; deviceEvent.inputIndex = evt.keyCode; if (this._usingMacOs && evt.metaKey && evt.key !== "Meta") { if (!this._metaKeys.includes(evt.keyCode)) { this._metaKeys.push(evt.keyCode); } } this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent); } }; this._keyboardUpEvent = (evt) => { if (!this._keyboardActive) { this._keyboardActive = true; this._registerDevice(DeviceType.Keyboard, 0, MAX_KEYCODES); } const kbKey = this._inputs[DeviceType.Keyboard][0]; if (kbKey) { kbKey[evt.keyCode] = 0; const deviceEvent = evt; deviceEvent.inputIndex = evt.keyCode; if (this._usingMacOs && evt.key === "Meta" && this._metaKeys.length > 0) { for (const keyCode of this._metaKeys) { const deviceEvent2 = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, keyCode, 0, this, this._elementToAttachTo); kbKey[keyCode] = 0; this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent2); } this._metaKeys.splice(0, this._metaKeys.length); } this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent); } }; this._keyboardBlurEvent = () => { if (this._keyboardActive) { const kbKey = this._inputs[DeviceType.Keyboard][0]; for (let i = 0; i < kbKey.length; i++) { if (kbKey[i] !== 0) { kbKey[i] = 0; const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Keyboard, 0, i, 0, this, this._elementToAttachTo); this._onInputChanged(DeviceType.Keyboard, 0, deviceEvent); } } if (this._usingMacOs) { this._metaKeys.splice(0, this._metaKeys.length); } } }; this._elementToAttachTo.addEventListener("keydown", this._keyboardDownEvent); this._elementToAttachTo.addEventListener("keyup", this._keyboardUpEvent); this._elementToAttachTo.addEventListener("blur", this._keyboardBlurEvent); } /** * Handle all actions that come from pointer interaction */ _handlePointerActions() { this._maxTouchPoints = IsNavigatorAvailable() && navigator.maxTouchPoints || 2; if (!this._activeTouchIds) { this._activeTouchIds = new Array(this._maxTouchPoints); } for (let i = 0; i < this._maxTouchPoints; i++) { this._activeTouchIds[i] = -1; } this._pointerMoveEvent = (evt) => { const deviceType = this._getPointerType(evt); let deviceSlot = deviceType === DeviceType.Mouse ? 0 : this._activeTouchIds.indexOf(evt.pointerId); if (deviceType === DeviceType.Touch && deviceSlot === -1) { const idx = this._activeTouchIds.indexOf(-1); if (idx >= 0) { deviceSlot = idx; this._activeTouchIds[idx] = evt.pointerId; this._onDeviceConnected(deviceType, deviceSlot); } else { Tools.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`); return; } } if (!this._inputs[deviceType]) { this._inputs[deviceType] = {}; } if (!this._inputs[deviceType][deviceSlot]) { this._addPointerDevice(deviceType, deviceSlot, evt.clientX, evt.clientY); } const pointer = this._inputs[deviceType][deviceSlot]; if (pointer) { const deviceEvent = evt; deviceEvent.inputIndex = PointerInput.Move; pointer[PointerInput.Horizontal] = evt.clientX; pointer[PointerInput.Vertical] = evt.clientY; if (deviceType === DeviceType.Touch && pointer[PointerInput.LeftClick] === 0) { pointer[PointerInput.LeftClick] = 1; } if (evt.pointerId === void 0) { evt.pointerId = this._mouseId; } this._onInputChanged(deviceType, deviceSlot, deviceEvent); if (!this._usingSafari && evt.button !== -1) { deviceEvent.inputIndex = evt.button + 2; pointer[evt.button + 2] = pointer[evt.button + 2] ? 0 : 1; this._onInputChanged(deviceType, deviceSlot, deviceEvent); } } }; this._pointerDownEvent = (evt) => { const deviceType = this._getPointerType(evt); let deviceSlot = deviceType === DeviceType.Mouse ? 0 : evt.pointerId; if (deviceType === DeviceType.Touch) { let idx = this._activeTouchIds.indexOf(evt.pointerId); if (idx === -1) { idx = this._activeTouchIds.indexOf(-1); } if (idx >= 0) { deviceSlot = idx; this._activeTouchIds[idx] = evt.pointerId; } else { Tools.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`); return; } } if (!this._inputs[deviceType]) { this._inputs[deviceType] = {}; } if (!this._inputs[deviceType][deviceSlot]) { this._addPointerDevice(deviceType, deviceSlot, evt.clientX, evt.clientY); } else if (deviceType === DeviceType.Touch) { this._onDeviceConnected(deviceType, deviceSlot); } const pointer = this._inputs[deviceType][deviceSlot]; if (pointer) { const previousHorizontal = pointer[PointerInput.Horizontal]; const previousVertical = pointer[PointerInput.Vertical]; if (deviceType === DeviceType.Mouse) { if (evt.pointerId === void 0) { evt.pointerId = this._mouseId; } if (!document.pointerLockElement) { try { this._elementToAttachTo.setPointerCapture(this._mouseId); } catch (e) { } } } else { if (evt.pointerId && !document.pointerLockElement) { try { this._elementToAttachTo.setPointerCapture(evt.pointerId); } catch (e) { } } } pointer[PointerInput.Horizontal] = evt.clientX; pointer[PointerInput.Vertical] = evt.clientY; pointer[evt.button + 2] = 1; const deviceEvent = evt; deviceEvent.inputIndex = evt.button + 2; this._onInputChanged(deviceType, deviceSlot, deviceEvent); if (previousHorizontal !== evt.clientX || previousVertical !== evt.clientY) { deviceEvent.inputIndex = PointerInput.Move; this._onInputChanged(deviceType, deviceSlot, deviceEvent); } } }; this._pointerUpEvent = (evt) => { const deviceType = this._getPointerType(evt); const deviceSlot = deviceType === DeviceType.Mouse ? 0 : this._activeTouchIds.indexOf(evt.pointerId); if (deviceType === DeviceType.Touch) { if (deviceSlot === -1) { return; } else { this._activeTouchIds[deviceSlot] = -1; } } const pointer = this._inputs[deviceType]?.[deviceSlot]; let button = evt.button; let shouldProcessPointerUp = pointer && pointer[button + 2] !== 0; if (!shouldProcessPointerUp && this._isUsingFirefox && this._usingMacOs && pointer) { button = button === 2 ? 0 : 2; shouldProcessPointerUp = pointer[button + 2] !== 0; } if (shouldProcessPointerUp) { const previousHorizontal = pointer[PointerInput.Horizontal]; const previousVertical = pointer[PointerInput.Vertical]; pointer[PointerInput.Horizontal] = evt.clientX; pointer[PointerInput.Vertical] = evt.clientY; pointer[button + 2] = 0; const deviceEvent = evt; if (evt.pointerId === void 0) { evt.pointerId = this._mouseId; } if (previousHorizontal !== evt.clientX || previousVertical !== evt.clientY) { deviceEvent.inputIndex = PointerInput.Move; this._onInputChanged(deviceType, deviceSlot, deviceEvent); } deviceEvent.inputIndex = button + 2; if (deviceType === DeviceType.Mouse && this._mouseId >= 0 && this._elementToAttachTo.hasPointerCapture?.(this._mouseId)) { this._elementToAttachTo.releasePointerCapture(this._mouseId); } else if (evt.pointerId && this._elementToAttachTo.hasPointerCapture?.(evt.pointerId)) { this._elementToAttachTo.releasePointerCapture(evt.pointerId); } this._onInputChanged(deviceType, deviceSlot, deviceEvent); if (deviceType === DeviceType.Touch) { this._onDeviceDisconnected(deviceType, deviceSlot); } } }; this._pointerCancelTouch = (pointerId) => { const deviceSlot = this._activeTouchIds.indexOf(pointerId); if (deviceSlot === -1) { return; } if (this._elementToAttachTo.hasPointerCapture?.(pointerId)) { this._elementToAttachTo.releasePointerCapture(pointerId); } this._inputs[DeviceType.Touch][deviceSlot][PointerInput.LeftClick] = 0; const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch, deviceSlot, PointerInput.LeftClick, 0, this, this._elementToAttachTo, pointerId); this._onInputChanged(DeviceType.Touch, deviceSlot, deviceEvent); this._activeTouchIds[deviceSlot] = -1; this._onDeviceDisconnected(DeviceType.Touch, deviceSlot); }; this._pointerCancelEvent = (evt) => { if (evt.pointerType === "mouse") { const pointer = this._inputs[DeviceType.Mouse][0]; if (this._mouseId >= 0 && this._elementToAttachTo.hasPointerCapture?.(this._mouseId)) { this._elementToAttachTo.releasePointerCapture(this._mouseId); } for (let inputIndex = PointerInput.LeftClick; inputIndex <= PointerInput.BrowserForward; inputIndex++) { if (pointer[inputIndex] === 1) { pointer[inputIndex] = 0; const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse, 0, inputIndex, 0, this, this._elementToAttachTo); this._onInputChanged(DeviceType.Mouse, 0, deviceEvent); } } } else { this._pointerCancelTouch(evt.pointerId); } }; this._pointerLeaveEvent = (evt) => { if (evt.pointerType === "pen") { this._pointerCancelTouch(evt.pointerId); } }; this._wheelEventName = "onwheel" in document.createElement("div") ? "wheel" : document.onmousewheel !== void 0 ? "mousewheel" : "DOMMouseScroll"; let passiveSupported = false; const noop = /* @__PURE__ */ __name(function() { }, "noop"); try { const options = Object.defineProperty({}, "passive", { get: /* @__PURE__ */ __name(function() { passiveSupported = true; }, "get") }); this._elementToAttachTo.addEventListener("test", noop, options); this._elementToAttachTo.removeEventListener("test", noop, options); } catch (e) { } this._pointerBlurEvent = () => { if (this.isDeviceAvailable(DeviceType.Mouse)) { const pointer = this._inputs[DeviceType.Mouse][0]; if (this._mouseId >= 0 && this._elementToAttachTo.hasPointerCapture?.(this._mouseId)) { this._elementToAttachTo.releasePointerCapture(this._mouseId); } for (let inputIndex = PointerInput.LeftClick; inputIndex <= PointerInput.BrowserForward; inputIndex++) { if (pointer[inputIndex] === 1) { pointer[inputIndex] = 0; const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Mouse, 0, inputIndex, 0, this, this._elementToAttachTo); this._onInputChanged(DeviceType.Mouse, 0, deviceEvent); } } } if (this.isDeviceAvailable(DeviceType.Touch)) { const pointer = this._inputs[DeviceType.Touch]; for (let deviceSlot = 0; deviceSlot < this._activeTouchIds.length; deviceSlot++) { const pointerId = this._activeTouchIds[deviceSlot]; if (this._elementToAttachTo.hasPointerCapture?.(pointerId)) { this._elementToAttachTo.releasePointerCapture(pointerId); } if (pointerId !== -1 && pointer[deviceSlot]?.[PointerInput.LeftClick] === 1) { pointer[deviceSlot][PointerInput.LeftClick] = 0; const deviceEvent = DeviceEventFactory.CreateDeviceEvent(DeviceType.Touch, deviceSlot, PointerInput.LeftClick, 0, this, this._elementToAttachTo, pointerId); this._onInputChanged(DeviceType.Touch, deviceSlot, deviceEvent); this._activeTouchIds[deviceSlot] = -1; this._onDeviceDisconnected(DeviceType.Touch, deviceSlot); } } } }; this._pointerWheelEvent = (evt) => { const deviceType = DeviceType.Mouse; const deviceSlot = 0; if (!this._inputs[deviceType]) { this._inputs[deviceType] = []; } if (!this._inputs[deviceType][deviceSlot]) { this._pointerActive = true; this._registerDevice(deviceType, deviceSlot, MAX_POINTER_INPUTS); } const pointer = this._inputs[deviceType][deviceSlot]; if (pointer) { pointer[PointerInput.MouseWheelX] = evt.deltaX || 0; pointer[PointerInput.MouseWheelY] = evt.deltaY || evt.wheelDelta || 0; pointer[PointerInput.MouseWheelZ] = evt.deltaZ || 0; const deviceEvent = evt; if (evt.pointerId === void 0) { evt.pointerId = this._mouseId; } if (pointer[PointerInput.MouseWheelX] !== 0) { deviceEvent.inputIndex = PointerInput.MouseWheelX; this._onInputChanged(deviceType, deviceSlot, deviceEvent); } if (pointer[PointerInput.MouseWheelY] !== 0) { deviceEvent.inputIndex = PointerInput.MouseWheelY; this._onInputChanged(deviceType, deviceSlot, deviceEvent); } if (pointer[PointerInput.MouseWheelZ] !== 0) { deviceEvent.inputIndex = PointerInput.MouseWheelZ; this._onInputChanged(deviceType, deviceSlot, deviceEvent); } } }; if (this._usingMacOs && this._isUsingChromium) { this._pointerMacOsChromeOutEvent = (evt) => { if (evt.buttons > 1) { this._pointerCancelEvent(evt); } }; this._elementToAttachTo.addEventListener("lostpointercapture", this._pointerMacOsChromeOutEvent); } this._elementToAttachTo.addEventListener(this._eventPrefix + "move", this._pointerMoveEvent); this._elementToAttachTo.addEventListener(this._eventPrefix + "down", this._pointerDownEvent); this._elementToAttachTo.addEventListener(this._eventPrefix + "up", this._pointerUpEvent); this._elementToAttachTo.addEventListener(this._eventPrefix + "cancel", this._pointerCancelEvent); this._elementToAttachTo.addEventListener(this._eventPrefix + "leave", this._pointerLeaveEvent); this._elementToAttachTo.addEventListener("blur", this._pointerBlurEvent); this._elementToAttachTo.addEventListener(this._wheelEventName, this._pointerWheelEvent, passiveSupported ? { passive: false } : false); this._pointerInputClearObserver = this._engine.onEndFrameObservable.add(() => { if (this.isDeviceAvailable(DeviceType.Mouse)) { const pointer = this._inputs[DeviceType.Mouse][0]; pointer[PointerInput.MouseWheelX] = 0; pointer[PointerInput.MouseWheelY] = 0; pointer[PointerInput.MouseWheelZ] = 0; } }); } /** * Handle all actions that come from gamepad interaction */ _handleGamepadActions() { this._gamepadConnectedEvent = (evt) => { this._addGamePad(evt.gamepad); }; this._gamepadDisconnectedEvent = (evt) => { if (this._gamepads) { const deviceType = this._getGamepadDeviceType(evt.gamepad.id); const 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 specifying device type * @param deviceSlot "Slot" or index that device is referenced in * @param inputIndex Id of input to be checked */ _updateDevice(deviceType, deviceSlot, inputIndex) { const gp = navigator.getGamepads()[deviceSlot]; if (gp && deviceType === this._gamepads[deviceSlot]) { const 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 */ _getGamepadDeviceType(deviceName) { if (deviceName.indexOf("054c") !== -1) { return deviceName.indexOf("0ce6") !== -1 ? DeviceType.DualSense : DeviceType.DualShock; } else if (deviceName.indexOf("Xbox One") !== -1 || deviceName.search("Xbox 360") !== -1 || deviceName.search("xinput") !== -1) { return DeviceType.Xbox; } else if (deviceName.indexOf("057e") !== -1) { return DeviceType.Switch; } return DeviceType.Generic; } /** * Get DeviceType from a given pointer/mouse/touch event. * @param evt PointerEvent to evaluate * @returns DeviceType interpreted from event */ _getPointerType(evt) { let deviceType = DeviceType.Mouse; if (evt.pointerType === "touch" || evt.pointerType === "pen" || evt.touches) { deviceType = DeviceType.Touch; } return deviceType; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSource.js var DeviceSource; var init_deviceSource = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSource.js"() { init_observable(); DeviceSource = class { static { __name(this, "DeviceSource"); } /** * Default Constructor * @param deviceInputSystem - Reference to DeviceInputSystem * @param deviceType - Type of device * @param deviceSlot - "Slot" or index that device is referenced in */ constructor(deviceInputSystem, deviceType, deviceSlot = 0) { this.deviceType = deviceType; this.deviceSlot = deviceSlot; this.onInputChangedObservable = new Observable(); this._deviceInputSystem = deviceInputSystem; } /** * Get input for specific input * @param inputIndex - index of specific input on device * @returns Input value from DeviceInputSystem */ getInput(inputIndex) { return this._deviceInputSystem.pollInput(this.deviceType, this.deviceSlot, inputIndex); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/internalDeviceSourceManager.js var InternalDeviceSourceManager; var init_internalDeviceSourceManager = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/internalDeviceSourceManager.js"() { init_deviceEnums(); init_nativeDeviceInputSystem(); init_webDeviceInputSystem(); init_deviceSource(); InternalDeviceSourceManager = class { static { __name(this, "InternalDeviceSourceManager"); } constructor(engine) { this._registeredManagers = new Array(); this._refCount = 0; this.registerManager = (manager) => { for (let deviceType = 0; deviceType < this._devices.length; deviceType++) { const device = this._devices[deviceType]; for (const deviceSlotKey in device) { const deviceSlot = +deviceSlotKey; manager._addDevice(new DeviceSource(this._deviceInputSystem, deviceType, deviceSlot)); } } this._registeredManagers.push(manager); }; this.unregisterManager = (manager) => { const idx = this._registeredManagers.indexOf(manager); if (idx > -1) { this._registeredManagers.splice(idx, 1); } }; const numberOfDeviceTypes = Object.keys(DeviceType).length / 2; this._devices = new Array(numberOfDeviceTypes); const onDeviceConnected = /* @__PURE__ */ __name((deviceType, deviceSlot) => { if (!this._devices[deviceType]) { this._devices[deviceType] = new Array(); } if (!this._devices[deviceType][deviceSlot]) { this._devices[deviceType][deviceSlot] = deviceSlot; } for (const manager of this._registeredManagers) { const deviceSource = new DeviceSource(this._deviceInputSystem, deviceType, deviceSlot); manager._addDevice(deviceSource); } }, "onDeviceConnected"); const onDeviceDisconnected = /* @__PURE__ */ __name((deviceType, deviceSlot) => { if (this._devices[deviceType]?.[deviceSlot]) { delete this._devices[deviceType][deviceSlot]; } for (const manager of this._registeredManagers) { manager._removeDevice(deviceType, deviceSlot); } }, "onDeviceDisconnected"); const onInputChanged = /* @__PURE__ */ __name((deviceType, deviceSlot, eventData) => { if (eventData) { for (const manager of this._registeredManagers) { manager._onInputChanged(deviceType, deviceSlot, eventData); } } }, "onInputChanged"); if (typeof _native !== "undefined") { this._deviceInputSystem = new NativeDeviceInputSystem(onDeviceConnected, onDeviceDisconnected, onInputChanged); } else { this._deviceInputSystem = new WebDeviceInputSystem(engine, onDeviceConnected, onDeviceDisconnected, onInputChanged); } } dispose() { this._deviceInputSystem.dispose(); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSourceManager.js var DeviceSourceManager; var init_deviceSourceManager = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/DeviceInput/InputDevices/deviceSourceManager.js"() { init_deviceEnums(); init_observable(); init_internalDeviceSourceManager(); DeviceSourceManager = class { static { __name(this, "DeviceSourceManager"); } // Public Functions /** * Gets a DeviceSource, given a type and slot * @param deviceType - Type of Device * @param deviceSlot - Slot or ID of device * @returns DeviceSource */ getDeviceSource(deviceType, deviceSlot) { if (deviceSlot === void 0) { if (this._firstDevice[deviceType] === void 0) { return null; } deviceSlot = this._firstDevice[deviceType]; } if (!this._devices[deviceType] || this._devices[deviceType][deviceSlot] === void 0) { return null; } return this._devices[deviceType][deviceSlot]; } /** * Gets an array of DeviceSource objects for a given device type * @param deviceType - Type of Device * @returns All available DeviceSources of a given type */ getDeviceSources(deviceType) { if (!this._devices[deviceType]) { return []; } return this._devices[deviceType].filter((source) => { return !!source; }); } /** * Default constructor * @param engine - Used to get canvas (if applicable) */ constructor(engine) { const numberOfDeviceTypes = Object.keys(DeviceType).length / 2; this._devices = new Array(numberOfDeviceTypes); this._firstDevice = new Array(numberOfDeviceTypes); this._engine = engine; if (!this._engine._deviceSourceManager) { this._engine._deviceSourceManager = new InternalDeviceSourceManager(engine); } this._engine._deviceSourceManager._refCount++; this.onDeviceConnectedObservable = new Observable((observer) => { for (const devices of this._devices) { if (devices) { for (const device of devices) { if (device) { this.onDeviceConnectedObservable.notifyObserver(observer, device); } } } } }); this.onDeviceDisconnectedObservable = new Observable(); this._engine._deviceSourceManager.registerManager(this); this._onDisposeObserver = engine.onDisposeObservable.add(() => { this.dispose(); }); } /** * Dispose of DeviceSourceManager */ dispose() { this.onDeviceConnectedObservable.clear(); this.onDeviceDisconnectedObservable.clear(); if (this._engine._deviceSourceManager) { this._engine._deviceSourceManager.unregisterManager(this); if (--this._engine._deviceSourceManager._refCount < 1) { this._engine._deviceSourceManager.dispose(); delete this._engine._deviceSourceManager; } } this._engine.onDisposeObservable.remove(this._onDisposeObserver); } // Hidden Functions /** * @param deviceSource - Source to add * @internal */ _addDevice(deviceSource) { if (!this._devices[deviceSource.deviceType]) { this._devices[deviceSource.deviceType] = []; } if (!this._devices[deviceSource.deviceType][deviceSource.deviceSlot]) { this._devices[deviceSource.deviceType][deviceSource.deviceSlot] = deviceSource; this._updateFirstDevices(deviceSource.deviceType); } this.onDeviceConnectedObservable.notifyObservers(deviceSource); } /** * @param deviceType - DeviceType * @param deviceSlot - DeviceSlot * @internal */ _removeDevice(deviceType, deviceSlot) { const deviceSource = this._devices[deviceType]?.[deviceSlot]; this.onDeviceDisconnectedObservable.notifyObservers(deviceSource); if (this._devices[deviceType]?.[deviceSlot]) { delete this._devices[deviceType][deviceSlot]; } this._updateFirstDevices(deviceType); } /** * @param deviceType - DeviceType * @param deviceSlot - DeviceSlot * @param eventData - Event * @internal */ _onInputChanged(deviceType, deviceSlot, eventData) { this._devices[deviceType]?.[deviceSlot]?.onInputChangedObservable.notifyObservers(eventData); } // Private Functions _updateFirstDevices(type) { switch (type) { case DeviceType.Keyboard: case DeviceType.Mouse: this._firstDevice[type] = 0; break; case DeviceType.Touch: case DeviceType.DualSense: case DeviceType.DualShock: case DeviceType.Xbox: case DeviceType.Switch: case DeviceType.Generic: { delete this._firstDevice[type]; const devices = this._devices[type]; if (devices) { for (let i = 0; i < devices.length; i++) { if (devices[i]) { this._firstDevice[type] = i; break; } } } break; } } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/import.helper.js var _ImportHelper; var init_import_helper = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/import.helper.js"() { _ImportHelper = class { static { __name(this, "_ImportHelper"); } }; _ImportHelper._IsPickingAvailable = false; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Inputs/scene.inputManager.js var _ClickInfo, InputManager; var init_scene_inputManager = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Inputs/scene.inputManager.js"() { init_pointerEvents(); init_abstractActionManager(); init_pickingInfo(); init_math_vector(); init_actionEvent(); init_keyboardEvents(); init_deviceEnums(); init_deviceSourceManager(); init_engineStore(); init_import_helper(); _ClickInfo = class { static { __name(this, "_ClickInfo"); } constructor() { this._singleClick = false; this._doubleClick = false; this._hasSwiped = false; this._ignore = false; } get singleClick() { return this._singleClick; } get doubleClick() { return this._doubleClick; } get hasSwiped() { return this._hasSwiped; } get ignore() { return this._ignore; } set singleClick(b) { this._singleClick = b; } set doubleClick(b) { this._doubleClick = b; } set hasSwiped(b) { this._hasSwiped = b; } set ignore(b) { this._ignore = b; } }; InputManager = class _InputManager { static { __name(this, "InputManager"); } /** * Creates a new InputManager * @param scene - defines the hosting scene */ constructor(scene) { this._alreadyAttached = false; this._meshPickProceed = false; this._currentPickResult = null; this._previousPickResult = null; this._activePointerIds = new Array(); this._activePointerIdsCount = 0; this._doubleClickOccured = false; this._isSwiping = false; this._swipeButtonPressed = -1; this._skipPointerTap = false; this._isMultiTouchGesture = false; this._pointerX = 0; this._pointerY = 0; this._startingPointerPosition = new Vector2(0, 0); this._previousStartingPointerPosition = new Vector2(0, 0); this._startingPointerTime = 0; this._previousStartingPointerTime = 0; this._pointerCaptures = {}; this._meshUnderPointerId = {}; this._movePointerInfo = null; this._cameraObserverCount = 0; this._delayedClicks = [null, null, null, null, null]; this._deviceSourceManager = null; this._scene = scene || EngineStore.LastCreatedScene; if (!this._scene) { return; } } /** * Gets the mesh that is currently under the pointer * @returns Mesh that the pointer is pointer is hovering over */ get meshUnderPointer() { if (this._movePointerInfo) { this._movePointerInfo._generatePickInfo(); this._movePointerInfo = null; } return this._pointerOverMesh; } /** * 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 */ getMeshUnderPointerByPointerId(pointerId) { return this._meshUnderPointerId[pointerId] || null; } /** * Gets the pointer coordinates in 2D without any translation (ie. straight out of the pointer event) * @returns Vector with X/Y values directly from pointer event */ get unTranslatedPointer() { return new Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY); } /** * Gets or sets the current on-screen X position of the pointer * @returns Translated X with respect to screen */ get pointerX() { return this._pointerX; } set pointerX(value) { this._pointerX = value; } /** * Gets or sets the current on-screen Y position of the pointer * @returns Translated Y with respect to screen */ get pointerY() { return this._pointerY; } set pointerY(value) { this._pointerY = value; } _updatePointerPosition(evt) { const 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; } _processPointerMove(pickResult, evt) { const scene = this._scene; const engine = scene.getEngine(); const canvas = engine.getInputElement(); if (canvas) { canvas.tabIndex = engine.canvasTabIndex; if (!scene.doNotHandleCursors) { canvas.style.cursor = scene.defaultCursor; } } this._setCursorAndPointerOverMesh(pickResult, evt, scene); for (const step of scene._pointerMoveStage) { pickResult = pickResult || this._pickMove(evt); const isMeshPicked = pickResult?.pickedMesh ? true : false; pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas); } const type = evt.inputIndex >= PointerInput.MouseWheelX && evt.inputIndex <= PointerInput.MouseWheelZ ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE; if (scene.onPointerMove) { pickResult = pickResult || this._pickMove(evt); scene.onPointerMove(evt, pickResult, type); } let pointerInfo; if (pickResult) { pointerInfo = new PointerInfo(type, evt, pickResult); this._setRayOnPointerInfo(pickResult, evt); } else { pointerInfo = new PointerInfo(type, evt, null, this); this._movePointerInfo = pointerInfo; } if (scene.onPointerObservable.hasObservers()) { scene.onPointerObservable.notifyObservers(pointerInfo, type); } } // Pointers handling /** @internal */ _setRayOnPointerInfo(pickInfo, event) { const scene = this._scene; if (pickInfo && _ImportHelper._IsPickingAvailable) { if (!pickInfo.ray) { pickInfo.ray = scene.createPickingRay(event.offsetX, event.offsetY, Matrix.Identity(), scene.activeCamera); } } } /** @internal */ _addCameraPointerObserver(observer, mask) { this._cameraObserverCount++; return this._scene.onPointerObservable.add(observer, mask); } /** @internal */ _removeCameraPointerObserver(observer) { this._cameraObserverCount--; return this._scene.onPointerObservable.remove(observer); } _checkForPicking() { return !!(this._scene.onPointerObservable.observers.length > this._cameraObserverCount || this._scene.onPointerPick); } _checkPrePointerObservable(pickResult, evt, type) { const scene = this._scene; const pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY); if (pickResult) { pi.originalPickingInfo = pickResult; pi.ray = pickResult.ray; if (evt.pointerType === "xr-near" && pickResult.originMesh) { pi.nearInteractionPickingInfo = pickResult; } } scene.onPrePointerObservable.notifyObservers(pi, type); if (pi.skipOnPointerObservable) { return true; } else { return false; } } /** @internal */ _pickMove(evt) { const scene = this._scene; const pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerMovePredicate, scene.pointerMoveFastCheck, scene.cameraToUseForPointers, scene.pointerMoveTrianglePredicate); this._setCursorAndPointerOverMesh(pickResult, evt, scene); return pickResult; } _setCursorAndPointerOverMesh(pickResult, evt, scene) { const engine = scene.getEngine(); const canvas = engine.getInputElement(); if (pickResult?.pickedMesh) { this.setPointerOverMesh(pickResult.pickedMesh, evt.pointerId, pickResult, evt); if (!scene.doNotHandleCursors && canvas && this._pointerOverMesh) { const actionManager = this._pointerOverMesh._getActionManagerForTrigger(); if (actionManager && actionManager.hasPointerTriggers) { canvas.style.cursor = actionManager.hoverCursor || scene.hoverCursor; } } } else { this.setPointerOverMesh(null, evt.pointerId, pickResult, evt); } } /** * 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) */ simulatePointerMove(pickResult, pointerEventInit) { const evt = new PointerEvent("pointermove", pointerEventInit); evt.inputIndex = PointerInput.Move; if (this._checkPrePointerObservable(pickResult, evt, 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) */ simulatePointerDown(pickResult, pointerEventInit) { const evt = new PointerEvent("pointerdown", pointerEventInit); evt.inputIndex = evt.button + 2; if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERDOWN)) { return; } this._processPointerDown(pickResult, evt); } _processPointerDown(pickResult, evt) { const scene = this._scene; if (pickResult?.pickedMesh) { this._pickedDownMesh = pickResult.pickedMesh; const actionManager = pickResult.pickedMesh._getActionManagerForTrigger(); if (actionManager) { if (actionManager.hasPickTriggers) { actionManager.processTrigger(5, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult)); switch (evt.button) { case 0: actionManager.processTrigger(2, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult)); break; case 1: actionManager.processTrigger(4, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult)); break; case 2: actionManager.processTrigger(3, new ActionEvent(pickResult.pickedMesh, scene.pointerX, scene.pointerY, pickResult.pickedMesh, evt, pickResult)); break; } } if (actionManager.hasSpecificTrigger(8)) { window.setTimeout(() => { const pickResult2 = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, (mesh) => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(8) && mesh === this._pickedDownMesh, false, scene.cameraToUseForPointers); if (pickResult2?.pickedMesh && actionManager) { if (this._activePointerIdsCount !== 0 && Date.now() - this._startingPointerTime > _InputManager.LongPressDelay && !this._isPointerSwiping()) { this._startingPointerTime = 0; actionManager.processTrigger(8, ActionEvent.CreateNew(pickResult2.pickedMesh, evt)); } } }, _InputManager.LongPressDelay); } } } else { for (const step of scene._pointerDownStage) { pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt, false); } } let pointerInfo; const type = PointerEventTypes.POINTERDOWN; if (pickResult) { if (scene.onPointerDown) { scene.onPointerDown(evt, pickResult, type); } pointerInfo = new PointerInfo(type, evt, pickResult); this._setRayOnPointerInfo(pickResult, evt); } else { pointerInfo = new PointerInfo(type, evt, null, this); } if (scene.onPointerObservable.hasObservers()) { scene.onPointerObservable.notifyObservers(pointerInfo, type); } } /** * @internal * @internals Boolean if delta for pointer exceeds drag movement threshold */ _isPointerSwiping() { return this._isSwiping; } /** * 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) */ simulatePointerUp(pickResult, pointerEventInit, doubleTap) { const evt = new PointerEvent("pointerup", pointerEventInit); evt.inputIndex = PointerInput.Move; const clickInfo = new _ClickInfo(); if (doubleTap) { clickInfo.doubleClick = true; } else { clickInfo.singleClick = true; } if (this._checkPrePointerObservable(pickResult, evt, PointerEventTypes.POINTERUP)) { return; } this._processPointerUp(pickResult, evt, clickInfo); } _processPointerUp(pickResult, evt, clickInfo) { const scene = this._scene; if (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.observers.length > this._cameraObserverCount) { const type = PointerEventTypes.POINTERPICK; const pi = new PointerInfo(type, evt, pickResult); this._setRayOnPointerInfo(pickResult, evt); scene.onPointerObservable.notifyObservers(pi, type); } } const actionManager = pickResult.pickedMesh._getActionManagerForTrigger(); if (actionManager && !clickInfo.ignore) { actionManager.processTrigger(7, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult)); if (!clickInfo.hasSwiped && clickInfo.singleClick) { actionManager.processTrigger(1, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult)); } const doubleClickActionManager = pickResult.pickedMesh._getActionManagerForTrigger(6); if (clickInfo.doubleClick && doubleClickActionManager) { doubleClickActionManager.processTrigger(6, ActionEvent.CreateNew(pickResult.pickedMesh, evt, pickResult)); } } } else { if (!clickInfo.ignore) { for (const step of scene._pointerUpStage) { pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt, clickInfo.doubleClick); } } } if (this._pickedDownMesh && this._pickedDownMesh !== this._pickedUpMesh) { const pickedDownActionManager = this._pickedDownMesh._getActionManagerForTrigger(16); if (pickedDownActionManager) { pickedDownActionManager.processTrigger(16, ActionEvent.CreateNew(this._pickedDownMesh, evt)); } } if (!clickInfo.ignore) { const pi = new PointerInfo(PointerEventTypes.POINTERUP, evt, pickResult); this._setRayOnPointerInfo(pickResult, evt); scene.onPointerObservable.notifyObservers(pi, PointerEventTypes.POINTERUP); if (scene.onPointerUp) { scene.onPointerUp(evt, pickResult, PointerEventTypes.POINTERUP); } if (!clickInfo.hasSwiped && !this._skipPointerTap && !this._isMultiTouchGesture) { let type = 0; if (clickInfo.singleClick) { type = PointerEventTypes.POINTERTAP; } else if (clickInfo.doubleClick) { type = PointerEventTypes.POINTERDOUBLETAP; } if (type) { const pi2 = new PointerInfo(type, evt, pickResult); if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) { scene.onPointerObservable.notifyObservers(pi2, 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 */ isPointerCaptured(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) */ attachControl(attachUp = true, attachDown = true, attachMove = true, elementToAttachTo = null) { const scene = this._scene; const engine = scene.getEngine(); if (!elementToAttachTo) { elementToAttachTo = engine.getInputElement(); } if (this._alreadyAttached) { this.detachControl(); } if (elementToAttachTo) { this._alreadyAttachedTo = elementToAttachTo; } this._deviceSourceManager = new DeviceSourceManager(engine); this._initActionManager = (act) => { if (!this._meshPickProceed) { const pickResult = scene.skipPointerUpPicking || scene._registeredActions === 0 && !this._checkForPicking() && !scene.onPointerUp ? null : scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerUpPredicate, scene.pointerUpFastCheck, scene.cameraToUseForPointers, scene.pointerUpTrianglePredicate); this._currentPickResult = pickResult; if (pickResult) { act = pickResult.hit && pickResult.pickedMesh ? pickResult.pickedMesh._getActionManagerForTrigger() : null; } this._meshPickProceed = true; } return act; }; this._delayedSimpleClick = (btn, clickInfo, cb) => { if (Date.now() - this._previousStartingPointerTime > _InputManager.DoubleClickDelay && !this._doubleClickOccured || btn !== this._previousButtonPressed) { this._doubleClickOccured = false; clickInfo.singleClick = true; clickInfo.ignore = false; if (this._delayedClicks[btn]) { const evt = this._delayedClicks[btn].evt; const type = PointerEventTypes.POINTERTAP; const pi = new PointerInfo(type, evt, this._currentPickResult); if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) { scene.onPointerObservable.notifyObservers(pi, type); } this._delayedClicks[btn] = null; } } }; this._initClickEvent = (obs1, obs2, evt, cb) => { const clickInfo = new _ClickInfo(); this._currentPickResult = null; let act = null; let checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP); if (!checkPicking && AbstractActionManager) { act = this._initActionManager(act, clickInfo); if (act) { checkPicking = act.hasPickTriggers; } } let needToIgnoreNext = false; checkPicking = checkPicking && !this._isMultiTouchGesture; if (checkPicking) { const btn = evt.button; clickInfo.hasSwiped = this._isPointerSwiping(); if (!clickInfo.hasSwiped) { let checkSingleClickImmediately = !_InputManager.ExclusiveDoubleClickMode; if (!checkSingleClickImmediately) { checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) && !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP); if (checkSingleClickImmediately && !AbstractActionManager.HasSpecificTrigger(6)) { act = this._initActionManager(act, clickInfo); if (act) { checkSingleClickImmediately = !act.hasSpecificTrigger(6); } } } if (checkSingleClickImmediately) { if (Date.now() - this._previousStartingPointerTime > _InputManager.DoubleClickDelay || btn !== this._previousButtonPressed) { clickInfo.singleClick = true; cb(clickInfo, this._currentPickResult); needToIgnoreNext = true; } } else { const delayedClick = { evt, clickInfo, timeoutId: window.setTimeout(this._delayedSimpleClick.bind(this, btn, clickInfo, cb), _InputManager.DoubleClickDelay) }; this._delayedClicks[btn] = delayedClick; } let checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP); if (!checkDoubleClick && AbstractActionManager.HasSpecificTrigger(6)) { act = this._initActionManager(act, clickInfo); if (act) { checkDoubleClick = act.hasSpecificTrigger(6); } } if (checkDoubleClick) { if (btn === this._previousButtonPressed && Date.now() - this._previousStartingPointerTime < _InputManager.DoubleClickDelay && !this._doubleClickOccured) { if (!clickInfo.hasSwiped && !this._isPointerSwiping()) { this._previousStartingPointerTime = 0; this._doubleClickOccured = true; clickInfo.doubleClick = true; clickInfo.ignore = false; if (_InputManager.ExclusiveDoubleClickMode && this._delayedClicks[btn]) { clearTimeout(this._delayedClicks[btn]?.timeoutId); this._delayedClicks[btn] = null; } cb(clickInfo, this._currentPickResult); } 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._delayedClicks[btn]) { clearTimeout(this._delayedClicks[btn]?.timeoutId); this._delayedClicks[btn] = null; } cb(clickInfo, this._previousPickResult); } else { cb(clickInfo, this._currentPickResult); } } needToIgnoreNext = true; } 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 = (evt) => { this._updatePointerPosition(evt); if (!this._isSwiping && this._swipeButtonPressed !== -1) { this._isSwiping = Math.abs(this._startingPointerPosition.x - this._pointerX) > _InputManager.DragMovementThreshold || Math.abs(this._startingPointerPosition.y - this._pointerY) > _InputManager.DragMovementThreshold; } if (engine.isPointerLock) { engine._verifyPointerLock(); } if (this._checkPrePointerObservable(null, evt, evt.inputIndex >= PointerInput.MouseWheelX && evt.inputIndex <= PointerInput.MouseWheelZ ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE)) { return; } if (!scene.cameraToUseForPointers && !scene.activeCamera) { return; } if (scene.skipPointerMovePicking) { this._processPointerMove(new PickingInfo(), evt); return; } if (!scene.pointerMovePredicate) { scene.pointerMovePredicate = (mesh) => mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || scene.constantlyUpdateMeshUnderPointer || mesh._getActionManagerForTrigger() !== null) && (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0); } const pickResult = scene._registeredActions > 0 || scene.constantlyUpdateMeshUnderPointer ? this._pickMove(evt) : null; this._processPointerMove(pickResult, evt); }; this._onPointerDown = (evt) => { const freeIndex = this._activePointerIds.indexOf(-1); if (freeIndex === -1) { this._activePointerIds.push(evt.pointerId); } else { this._activePointerIds[freeIndex] = evt.pointerId; } this._activePointerIdsCount++; this._pickedDownMesh = null; this._meshPickProceed = false; if (_InputManager.ExclusiveDoubleClickMode) { for (let i = 0; i < this._delayedClicks.length; i++) { if (this._delayedClicks[i]) { if (evt.button === i) { clearTimeout(this._delayedClicks[i]?.timeoutId); } else { const clickInfo = this._delayedClicks[i].clickInfo; this._doubleClickOccured = false; clickInfo.singleClick = true; clickInfo.ignore = false; const prevEvt = this._delayedClicks[i].evt; const type = PointerEventTypes.POINTERTAP; const pi = new PointerInfo(type, prevEvt, this._currentPickResult); if (scene.onPointerObservable.hasObservers() && scene.onPointerObservable.hasSpecificMask(type)) { scene.onPointerObservable.notifyObservers(pi, type); } this._delayedClicks[i] = null; } } } } this._updatePointerPosition(evt); if (this._swipeButtonPressed === -1) { this._swipeButtonPressed = evt.button; } if (scene.preventDefaultOnPointerDown && elementToAttachTo) { evt.preventDefault(); elementToAttachTo.focus(); } this._startingPointerPosition.x = this._pointerX; this._startingPointerPosition.y = this._pointerY; this._startingPointerTime = Date.now(); if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOWN)) { return; } if (!scene.cameraToUseForPointers && !scene.activeCamera) { return; } this._pointerCaptures[evt.pointerId] = true; if (!scene.pointerDownPredicate) { scene.pointerDownPredicate = (mesh) => { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0); }; } this._pickedDownMesh = null; let pickResult; if (scene.skipPointerDownPicking || scene._registeredActions === 0 && !this._checkForPicking() && !scene.onPointerDown) { pickResult = new PickingInfo(); } else { pickResult = scene.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, scene.pointerDownPredicate, scene.pointerDownFastCheck, scene.cameraToUseForPointers, scene.pointerDownTrianglePredicate); } this._processPointerDown(pickResult, evt); }; this._onPointerUp = (evt) => { const pointerIdIndex = this._activePointerIds.indexOf(evt.pointerId); if (pointerIdIndex === -1) { return; } this._activePointerIds[pointerIdIndex] = -1; this._activePointerIdsCount--; this._pickedUpMesh = null; this._meshPickProceed = false; this._updatePointerPosition(evt); if (scene.preventDefaultOnPointerUp && elementToAttachTo) { evt.preventDefault(); elementToAttachTo.focus(); } this._initClickEvent(scene.onPrePointerObservable, scene.onPointerObservable, evt, (clickInfo, pickResult) => { if (scene.onPrePointerObservable.hasObservers()) { this._skipPointerTap = false; if (!clickInfo.ignore) { if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERUP)) { if (this._swipeButtonPressed === evt.button) { this._isSwiping = false; this._swipeButtonPressed = -1; } if (evt.buttons === 0) { this._pointerCaptures[evt.pointerId] = false; } return; } if (!clickInfo.hasSwiped) { if (clickInfo.singleClick && scene.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) { if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERTAP)) { this._skipPointerTap = true; } } if (clickInfo.doubleClick && scene.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) { if (this._checkPrePointerObservable(null, evt, PointerEventTypes.POINTERDOUBLETAP)) { this._skipPointerTap = true; } } } } } if (!this._pointerCaptures[evt.pointerId]) { if (this._swipeButtonPressed === evt.button) { this._isSwiping = false; this._swipeButtonPressed = -1; } return; } if (evt.buttons === 0) { this._pointerCaptures[evt.pointerId] = false; } if (!scene.cameraToUseForPointers && !scene.activeCamera) { return; } if (!scene.pointerUpPredicate) { scene.pointerUpPredicate = (mesh) => { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0); }; } if (!this._meshPickProceed && (AbstractActionManager && AbstractActionManager.HasTriggers || this._checkForPicking() || scene.onPointerUp)) { this._initActionManager(null, clickInfo); } if (!pickResult) { pickResult = this._currentPickResult; } this._processPointerUp(pickResult, evt, clickInfo); this._previousPickResult = this._currentPickResult; if (this._swipeButtonPressed === evt.button) { this._isSwiping = false; this._swipeButtonPressed = -1; } }); }; this._onKeyDown = (evt) => { const type = KeyboardEventTypes.KEYDOWN; if (scene.onPreKeyboardObservable.hasObservers()) { const pi = new KeyboardInfoPre(type, evt); scene.onPreKeyboardObservable.notifyObservers(pi, type); if (pi.skipOnKeyboardObservable) { return; } } if (scene.onKeyboardObservable.hasObservers()) { const pi = new KeyboardInfo(type, evt); scene.onKeyboardObservable.notifyObservers(pi, type); } if (scene.actionManager) { scene.actionManager.processTrigger(14, ActionEvent.CreateNewFromScene(scene, evt)); } }; this._onKeyUp = (evt) => { const type = KeyboardEventTypes.KEYUP; if (scene.onPreKeyboardObservable.hasObservers()) { const pi = new KeyboardInfoPre(type, evt); scene.onPreKeyboardObservable.notifyObservers(pi, type); if (pi.skipOnKeyboardObservable) { return; } } if (scene.onKeyboardObservable.hasObservers()) { const pi = new KeyboardInfo(type, evt); scene.onKeyboardObservable.notifyObservers(pi, type); } if (scene.actionManager) { scene.actionManager.processTrigger(15, ActionEvent.CreateNewFromScene(scene, evt)); } }; this._deviceSourceManager.onDeviceConnectedObservable.add((deviceSource) => { if (deviceSource.deviceType === DeviceType.Mouse) { deviceSource.onInputChangedObservable.add((eventData) => { this._originMouseEvent = eventData; if (eventData.inputIndex === PointerInput.LeftClick || eventData.inputIndex === PointerInput.MiddleClick || eventData.inputIndex === PointerInput.RightClick || eventData.inputIndex === PointerInput.BrowserBack || eventData.inputIndex === PointerInput.BrowserForward) { if (attachDown && deviceSource.getInput(eventData.inputIndex) === 1) { this._onPointerDown(eventData); } else if (attachUp && deviceSource.getInput(eventData.inputIndex) === 0) { this._onPointerUp(eventData); } } else if (attachMove) { if (eventData.inputIndex === PointerInput.Move) { this._onPointerMove(eventData); } else if (eventData.inputIndex === PointerInput.MouseWheelX || eventData.inputIndex === PointerInput.MouseWheelY || eventData.inputIndex === PointerInput.MouseWheelZ) { this._onPointerMove(eventData); } } }); } else if (deviceSource.deviceType === DeviceType.Touch) { deviceSource.onInputChangedObservable.add((eventData) => { if (eventData.inputIndex === PointerInput.LeftClick) { if (attachDown && deviceSource.getInput(eventData.inputIndex) === 1) { this._onPointerDown(eventData); if (this._activePointerIdsCount > 1) { this._isMultiTouchGesture = true; } } else if (attachUp && deviceSource.getInput(eventData.inputIndex) === 0) { this._onPointerUp(eventData); if (this._activePointerIdsCount === 0) { this._isMultiTouchGesture = false; } } } if (attachMove && eventData.inputIndex === PointerInput.Move) { this._onPointerMove(eventData); } }); } else if (deviceSource.deviceType === DeviceType.Keyboard) { deviceSource.onInputChangedObservable.add((eventData) => { if (eventData.type === "keydown") { this._onKeyDown(eventData); } else if (eventData.type === "keyup") { this._onKeyUp(eventData); } }); } }); this._alreadyAttached = true; } /** * Detaches all event handlers */ detachControl() { if (this._alreadyAttached) { this._deviceSourceManager.dispose(); this._deviceSourceManager = null; if (this._alreadyAttachedTo && !this._scene.doNotHandleCursors) { this._alreadyAttachedTo.style.cursor = this._scene.defaultCursor; } this._alreadyAttached = false; this._alreadyAttachedTo = null; } } /** * Set the value of meshUnderPointer for a given pointerId * @param mesh - defines the mesh to use * @param pointerId - optional pointer id when using more than one pointer. Defaults to 0 * @param pickResult - optional pickingInfo data used to find mesh * @param evt - optional pointer event */ setPointerOverMesh(mesh, pointerId = 0, pickResult, evt) { if (this._meshUnderPointerId[pointerId] === mesh && (!mesh || !mesh._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting)) { return; } const underPointerMesh = this._meshUnderPointerId[pointerId]; let actionManager; if (underPointerMesh) { actionManager = underPointerMesh._getActionManagerForTrigger(10); if (actionManager) { actionManager.processTrigger(10, new ActionEvent(underPointerMesh, this._pointerX, this._pointerY, mesh, evt, { pointerId })); } } if (mesh) { this._meshUnderPointerId[pointerId] = mesh; this._pointerOverMesh = mesh; actionManager = mesh._getActionManagerForTrigger(9); if (actionManager) { actionManager.processTrigger(9, new ActionEvent(mesh, this._pointerX, this._pointerY, mesh, evt, { pointerId, pickResult })); } } else { delete this._meshUnderPointerId[pointerId]; this._pointerOverMesh = null; } if (this._scene.onMeshUnderPointerUpdatedObservable.hasObservers()) { this._scene.onMeshUnderPointerUpdatedObservable.notifyObservers({ mesh, pointerId }); } } /** * Gets the mesh under the pointer * @returns a Mesh or null if no mesh is under the pointer */ getPointerOverMesh() { return this.meshUnderPointer; } /** * @param mesh - Mesh to invalidate * @internal */ _invalidateMesh(mesh) { if (this._pointerOverMesh === mesh) { this._pointerOverMesh = null; } if (this._pickedDownMesh === mesh) { this._pickedDownMesh = null; } if (this._pickedUpMesh === mesh) { this._pickedUpMesh = null; } for (const pointerId in this._meshUnderPointerId) { if (this._meshUnderPointerId[pointerId] === mesh) { delete this._meshUnderPointerId[pointerId]; } } } }; InputManager.DragMovementThreshold = 10; InputManager.LongPressDelay = 500; InputManager.DoubleClickDelay = 300; InputManager.ExclusiveDoubleClickMode = false; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/uniqueIdGenerator.js var UniqueIdGenerator; var init_uniqueIdGenerator = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/uniqueIdGenerator.js"() { UniqueIdGenerator = class { static { __name(this, "UniqueIdGenerator"); } /** * Gets an unique (relatively to the current scene) Id */ static get UniqueId() { const result = this._UniqueIdCounter; this._UniqueIdCounter++; return result; } }; UniqueIdGenerator._UniqueIdCounter = 1; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Inputs/pointerPickingConfiguration.js var PointerPickingConfiguration; var init_pointerPickingConfiguration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Inputs/pointerPickingConfiguration.js"() { PointerPickingConfiguration = class { static { __name(this, "PointerPickingConfiguration"); } constructor() { this.pointerDownFastCheck = false; this.pointerUpFastCheck = false; this.pointerMoveFastCheck = false; this.skipPointerMovePicking = false; this.skipPointerDownPicking = false; this.skipPointerUpPicking = false; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/frameGraphTypes.js var backbufferColorTextureHandle, backbufferDepthStencilTextureHandle; var init_frameGraphTypes = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/frameGraphTypes.js"() { backbufferColorTextureHandle = 0; backbufferDepthStencilTextureHandle = 1; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Passes/pass.js var FrameGraphPass; var init_pass = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Passes/pass.js"() { FrameGraphPass = class { static { __name(this, "FrameGraphPass"); } constructor(name260, _parentTask, _context) { this.name = name260; this._parentTask = _parentTask; this._context = _context; this.disabled = false; } setExecuteFunc(func) { this._executeFunc = func; } _execute() { if (!this.disabled) { this._executeFunc(this._context); } } _isValid() { return this._executeFunc !== void 0 ? null : "Execute function is not set (call setExecuteFunc to set it)"; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Passes/cullPass.js var FrameGraphCullPass; var init_cullPass = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Passes/cullPass.js"() { init_pass(); FrameGraphCullPass = class extends FrameGraphPass { static { __name(this, "FrameGraphCullPass"); } /** * Checks if a pass is a cull pass. * @param pass The pass to check. * @returns True if the pass is a cull pass, else false. */ static IsCullPass(pass) { return pass.setObjectList !== void 0; } /** * Gets the object list used by the cull pass. */ get objectList() { return this._objectList; } /** * Sets the object list to use for culling. * @param objectList The object list to use for culling. */ setObjectList(objectList) { this._objectList = objectList; } /** @internal */ constructor(name260, parentTask, context, engine) { super(name260, parentTask, context); this._engine = engine; } /** @internal */ _isValid() { const errMsg = super._isValid(); return errMsg ? errMsg : this._objectList !== void 0 ? null : "Object list is not set (call setObjectList to set it)"; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Passes/renderPass.js var FrameGraphRenderPass; var init_renderPass = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Passes/renderPass.js"() { init_pass(); FrameGraphRenderPass = class extends FrameGraphPass { static { __name(this, "FrameGraphRenderPass"); } /** * Checks if a pass is a render pass. * @param pass The pass to check. * @returns True if the pass is a render pass, else false. */ static IsRenderPass(pass) { return pass.setRenderTarget !== void 0; } /** * Gets the render target(s) used by the render pass. */ get renderTarget() { return this._renderTarget; } /** * Gets the render target depth used by the render pass. */ get renderTargetDepth() { return this._renderTargetDepth; } /** @internal */ constructor(name260, parentTask, context, engine) { super(name260, parentTask, context); this._dependencies = /* @__PURE__ */ new Set(); this.depthReadOnly = false; this.stencilReadOnly = false; this._engine = engine; } /** * Sets the render target(s) to use for rendering. * @param renderTargetHandle The render target to use for rendering, or an array of render targets to use for multi render target rendering. */ setRenderTarget(renderTargetHandle) { this._renderTarget = renderTargetHandle; } /** * Sets the render target depth to use for rendering. * @param renderTargetHandle The render target depth to use for rendering. */ setRenderTargetDepth(renderTargetHandle) { this._renderTargetDepth = renderTargetHandle; } /** * Adds dependencies to the render pass. * @param dependencies The dependencies to add. */ addDependencies(dependencies) { if (dependencies === void 0) { return; } if (Array.isArray(dependencies)) { for (const dependency of dependencies) { this._dependencies.add(dependency); } } else { this._dependencies.add(dependencies); } } /** * Collects the dependencies of the render pass. * @param dependencies The set of dependencies to update. */ collectDependencies(dependencies) { const iterator = this._dependencies.keys(); for (let key = iterator.next(); key.done !== true; key = iterator.next()) { dependencies.add(key.value); } if (this._renderTarget !== void 0) { if (Array.isArray(this._renderTarget)) { for (const handle of this._renderTarget) { if (handle !== void 0) { dependencies.add(handle); } } } else { dependencies.add(this._renderTarget); } } if (this._renderTargetDepth !== void 0) { dependencies.add(this._renderTargetDepth); } } /** @internal */ _execute() { this._frameGraphRenderTarget = this._frameGraphRenderTarget || this._context.createRenderTarget(this.name, this._renderTarget, this._renderTargetDepth, this.depthReadOnly, this.stencilReadOnly); this._context.bindRenderTarget(this._frameGraphRenderTarget, `frame graph render pass - ${this.name}`); super._execute(); this._context._flushDebugMessages(); } /** @internal */ _isValid() { const errMsg = super._isValid(); return errMsg ? errMsg : this._renderTarget !== void 0 || this.renderTargetDepth !== void 0 ? null : "Render target and render target depth cannot both be undefined."; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/frameGraphTask.js var FrameGraphTask; var init_frameGraphTask = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/frameGraphTask.js"() { init_cullPass(); init_renderPass(); init_observable(); FrameGraphTask = class { static { __name(this, "FrameGraphTask"); } /** * The name of the task. */ get name() { return this._name; } set name(value) { this._name = value; } /** * Whether the task is disabled. */ get disabled() { return this._disabled; } set disabled(value) { this._disabled = value; } /** * Gets the render passes of the task. */ get passes() { return this._passes; } /** * Gets the disabled render passes of the task. */ get passesDisabled() { return this._passesDisabled; } /** * Checks if the task is ready to be executed. * @returns True if the task is ready to be executed, else false. */ isReady() { return true; } /** * Disposes of the task. */ dispose() { this._reset(); this.onTexturesAllocatedObservable.clear(); } /** * Constructs a new frame graph task. * @param name The name of the task. * @param frameGraph The frame graph this task is associated with. */ constructor(name260, frameGraph) { this._passes = []; this._passesDisabled = []; this._disabled = false; this.onTexturesAllocatedObservable = new Observable(); this.name = name260; this._frameGraph = frameGraph; this._reset(); } /** @internal */ _reset() { this._passes.length = 0; this._passesDisabled.length = 0; } /** @internal */ _addPass(pass, disabled) { if (disabled) { this._passesDisabled.push(pass); } else { this._passes.push(pass); } } /** @internal */ _checkTask() { let outputTexture = null; let outputDepthTexture = null; let outputObjectList; for (const pass of this._passes) { const errMsg = pass._isValid(); if (errMsg) { throw new Error(`Pass "${pass.name}" is not valid. ${errMsg}`); } if (FrameGraphRenderPass.IsRenderPass(pass)) { const handles = Array.isArray(pass.renderTarget) ? pass.renderTarget : [pass.renderTarget]; outputTexture = []; for (const handle of handles) { if (handle !== void 0) { outputTexture.push(this._frameGraph.textureManager.getTextureFromHandle(handle)); } } outputDepthTexture = pass.renderTargetDepth !== void 0 ? this._frameGraph.textureManager.getTextureFromHandle(pass.renderTargetDepth) : null; } else if (FrameGraphCullPass.IsCullPass(pass)) { outputObjectList = pass.objectList; } } let disabledOutputTexture = null; let disabledOutputTextureHandle = []; let disabledOutputDepthTexture = null; let disabledOutputObjectList; for (const pass of this._passesDisabled) { const errMsg = pass._isValid(); if (errMsg) { throw new Error(`Pass "${pass.name}" is not valid. ${errMsg}`); } if (FrameGraphRenderPass.IsRenderPass(pass)) { const handles = Array.isArray(pass.renderTarget) ? pass.renderTarget : [pass.renderTarget]; disabledOutputTexture = []; for (const handle of handles) { if (handle !== void 0) { disabledOutputTexture.push(this._frameGraph.textureManager.getTextureFromHandle(handle)); } } disabledOutputTextureHandle = handles; disabledOutputDepthTexture = pass.renderTargetDepth !== void 0 ? this._frameGraph.textureManager.getTextureFromHandle(pass.renderTargetDepth) : null; } else if (FrameGraphCullPass.IsCullPass(pass)) { disabledOutputObjectList = pass.objectList; } } if (this._passesDisabled.length > 0) { if (!this._checkSameRenderTarget(outputTexture, disabledOutputTexture)) { let ok = true; for (const handle of disabledOutputTextureHandle) { if (handle !== void 0 && !this._frameGraph.textureManager.isHistoryTexture(handle)) { ok = false; break; } } if (!ok) { throw new Error(`The output texture of the task "${this.name}" is different when it is enabled or disabled.`); } } if (outputDepthTexture !== disabledOutputDepthTexture) { throw new Error(`The output depth texture of the task "${this.name}" is different when it is enabled or disabled.`); } if (outputObjectList !== disabledOutputObjectList) { throw new Error(`The output object list of the task "${this.name}" is different when it is enabled or disabled.`); } } } /** @internal */ _getPasses() { return this.disabled && this._passesDisabled.length > 0 ? this._passesDisabled : this._passes; } _checkSameRenderTarget(src, dst) { if (src === null || dst === null) { return src === dst; } if (src.length !== dst.length) { return false; } for (let i = 0; i < src.length; i++) { if (src[i] !== dst[i]) { return false; } } return true; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/packingFunctions.js var name15, shader15, packingFunctionsWGSL; var init_packingFunctions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/packingFunctions.js"() { init_shaderStore(); name15 = "packingFunctions"; shader15 = `fn pack(depth: f32)->vec4f {const bit_shift: vec4f= vec4f(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const bit_mask: vec4f= vec4f(0.0,1.0/255.0,1.0/255.0,1.0/255.0);var res: vec4f=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} fn unpack(color: vec4f)->f32 {const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`; if (!ShaderStore.IncludesShadersStoreWGSL[name15]) { ShaderStore.IncludesShadersStoreWGSL[name15] = shader15; } packingFunctionsWGSL = { name: name15, shader: shader15 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bayerDitherFunctions.js var name16, shader16, bayerDitherFunctionsWGSL; var init_bayerDitherFunctions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bayerDitherFunctions.js"() { init_shaderStore(); name16 = "bayerDitherFunctions"; shader16 = `fn bayerDither2(_P: vec2f)->f32 {return ((2.0*_P.y+_P.x+1.0)%(4.0));} fn bayerDither4(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0)); var P2: vec2f=floor(0.5*((_P)%(4.0))); return 4.0*bayerDither2(P1)+bayerDither2(P2);} fn bayerDither8(_P: vec2f)->f32 {var P1: vec2f=((_P)%(2.0)); var P2: vec2f=floor(0.5 *((_P)%(4.0))); var P4: vec2f=floor(0.25*((_P)%(8.0))); return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} `; if (!ShaderStore.IncludesShadersStoreWGSL[name16]) { ShaderStore.IncludesShadersStoreWGSL[name16] = shader16; } bayerDitherFunctionsWGSL = { name: name16, shader: shader16 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragmentExtraDeclaration.js var name17, shader17, shadowMapFragmentExtraDeclarationWGSL; var init_shadowMapFragmentExtraDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragmentExtraDeclaration.js"() { init_shaderStore(); init_packingFunctions(); init_bayerDitherFunctions(); name17 = "shadowMapFragmentExtraDeclaration"; shader17 = `#if SM_FLOAT==0 #include #endif #if SM_SOFTTRANSPARENTSHADOW==1 #include uniform softTransparentShadowSM: vec2f; #endif varying vDepthMetricSM: f32; #if SM_USEDISTANCE==1 uniform lightDataSM: vec3f;varying vPositionWSM: vec3f; #endif uniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying zSM: f32; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name17]) { ShaderStore.IncludesShadersStoreWGSL[name17] = shader17; } shadowMapFragmentExtraDeclarationWGSL = { name: name17, shader: shader17 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragmentDeclaration.js var name18, shader18, clipPlaneFragmentDeclarationWGSL; var init_clipPlaneFragmentDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragmentDeclaration.js"() { init_shaderStore(); name18 = "clipPlaneFragmentDeclaration"; shader18 = `#ifdef CLIPPLANE varying fClipDistance: f32; #endif #ifdef CLIPPLANE2 varying fClipDistance2: f32; #endif #ifdef CLIPPLANE3 varying fClipDistance3: f32; #endif #ifdef CLIPPLANE4 varying fClipDistance4: f32; #endif #ifdef CLIPPLANE5 varying fClipDistance5: f32; #endif #ifdef CLIPPLANE6 varying fClipDistance6: f32; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name18]) { ShaderStore.IncludesShadersStoreWGSL[name18] = shader18; } clipPlaneFragmentDeclarationWGSL = { name: name18, shader: shader18 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragment.js var name19, shader19, clipPlaneFragmentWGSL; var init_clipPlaneFragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneFragment.js"() { init_shaderStore(); name19 = "clipPlaneFragment"; shader19 = `#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) if (false) {} #endif #ifdef CLIPPLANE else if (fragmentInputs.fClipDistance>0.0) {discard;} #endif #ifdef CLIPPLANE2 else if (fragmentInputs.fClipDistance2>0.0) {discard;} #endif #ifdef CLIPPLANE3 else if (fragmentInputs.fClipDistance3>0.0) {discard;} #endif #ifdef CLIPPLANE4 else if (fragmentInputs.fClipDistance4>0.0) {discard;} #endif #ifdef CLIPPLANE5 else if (fragmentInputs.fClipDistance5>0.0) {discard;} #endif #ifdef CLIPPLANE6 else if (fragmentInputs.fClipDistance6>0.0) {discard;} #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name19]) { ShaderStore.IncludesShadersStoreWGSL[name19] = shader19; } clipPlaneFragmentWGSL = { name: name19, shader: shader19 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragment.js var name20, shader20, shadowMapFragmentWGSL; var init_shadowMapFragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragment.js"() { init_shaderStore(); name20 = "shadowMapFragment"; shader20 = `var depthSM: f32=fragmentInputs.vDepthMetricSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 #if SM_USEDISTANCE==1 depthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; #else #ifdef USE_REVERSE_DEPTHBUFFER depthSM=(-fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; #else depthSM=(fragmentInputs.zSM+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; #endif #endif depthSM=clamp(depthSM,0.0,1.0); #ifdef USE_REVERSE_DEPTHBUFFER fragmentOutputs.fragDepth=clamp(1.0-depthSM,0.0,1.0); #else fragmentOutputs.fragDepth=clamp(depthSM,0.0,1.0); #endif #elif SM_USEDISTANCE==1 depthSM=(length(fragmentInputs.vPositionWSM-uniforms.lightDataSM)+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; #endif #if SM_ESM==1 depthSM=clamp(exp(-min(87.,uniforms.biasAndScaleSM.z*depthSM)),0.,1.); #endif #if SM_FLOAT==1 fragmentOutputs.color= vec4f(depthSM,1.0,1.0,1.0); #else fragmentOutputs.color=pack(depthSM); #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name20]) { ShaderStore.IncludesShadersStoreWGSL[name20] = shader20; } shadowMapFragmentWGSL = { name: name20, shader: shader20 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/shadowMap.fragment.js var shadowMap_fragment_exports = {}; __export(shadowMap_fragment_exports, { shadowMapPixelShaderWGSL: () => shadowMapPixelShaderWGSL }); var name21, shader21, shadowMapPixelShaderWGSL; var init_shadowMap_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/shadowMap.fragment.js"() { init_shaderStore(); init_shadowMapFragmentExtraDeclaration(); init_clipPlaneFragmentDeclaration(); init_clipPlaneFragment(); init_shadowMapFragment(); name21 = "shadowMapPixelShader"; shader21 = `#include #ifdef ALPHATEXTURE varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #endif #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #include #ifdef ALPHATEXTURE var opacityMap: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUV);var alphaFromAlphaTexture: f32=opacityMap.a; #if SM_SOFTTRANSPARENTSHADOW==1 if (uniforms.softTransparentShadowSM.y==1.0) {opacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;} #endif #ifdef ALPHATESTVALUE if (alphaFromAlphaTexture=uniforms.softTransparentShadowSM.x*alphaFromAlphaTexture) {discard;} #else if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x) {discard;} #endif #endif #include }`; if (!ShaderStore.ShadersStoreWGSL[name21]) { ShaderStore.ShadersStoreWGSL[name21] = shader21; } shadowMapPixelShaderWGSL = { name: name21, shader: shader21 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesDeclaration.js var name22, shader22, bonesDeclarationWGSL; var init_bonesDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesDeclaration.js"() { init_shaderStore(); name22 = "bonesDeclaration"; shader22 = `#if NUM_BONE_INFLUENCERS>0 attribute matricesIndices : vec4;attribute matricesWeights : vec4; #if NUM_BONE_INFLUENCERS>4 attribute matricesIndicesExtra : vec4;attribute matricesWeightsExtra : vec4; #endif #ifndef BAKED_VERTEX_ANIMATION_TEXTURE #ifdef BONETEXTURE var boneSampler : texture_2d;uniform boneTextureWidth : f32; #else uniform mBones : array; #endif #ifdef BONES_VELOCITY_ENABLED uniform mPreviousBones : array; #endif #ifdef BONETEXTURE fn readMatrixFromRawSampler(smp : texture_2d,index : f32)->mat4x4f {let offset=i32(index) *4; let m0=textureLoad(smp,vec2(offset+0,0),0);let m1=textureLoad(smp,vec2(offset+1,0),0);let m2=textureLoad(smp,vec2(offset+2,0),0);let m3=textureLoad(smp,vec2(offset+3,0),0);return mat4x4f(m0,m1,m2,m3);} #endif #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name22]) { ShaderStore.IncludesShadersStoreWGSL[name22] = shader22; } bonesDeclarationWGSL = { name: name22, shader: shader22 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimationDeclaration.js var name23, shader23, bakedVertexAnimationDeclarationWGSL; var init_bakedVertexAnimationDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimationDeclaration.js"() { init_shaderStore(); name23 = "bakedVertexAnimationDeclaration"; shader23 = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE uniform bakedVertexAnimationTime: f32;uniform bakedVertexAnimationTextureSizeInverted: vec2;uniform bakedVertexAnimationSettings: vec4;var bakedVertexAnimationTexture : texture_2d; #ifdef INSTANCES attribute bakedVertexAnimationSettingsInstanced : vec4; #endif fn readMatrixFromRawSamplerVAT(smp : texture_2d,index : f32,frame : f32)->mat4x4 {let offset=i32(index)*4;let frameUV=i32(frame);let m0=textureLoad(smp,vec2(offset+0,frameUV),0);let m1=textureLoad(smp,vec2(offset+1,frameUV),0);let m2=textureLoad(smp,vec2(offset+2,frameUV),0);let m3=textureLoad(smp,vec2(offset+3,frameUV),0);return mat4x4(m0,m1,m2,m3);} #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name23]) { ShaderStore.IncludesShadersStoreWGSL[name23] = shader23; } bakedVertexAnimationDeclarationWGSL = { name: name23, shader: shader23 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobalDeclaration.js var name24, shader24, morphTargetsVertexGlobalDeclarationWGSL; var init_morphTargetsVertexGlobalDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobalDeclaration.js"() { init_shaderStore(); name24 = "morphTargetsVertexGlobalDeclaration"; shader24 = `#ifdef MORPHTARGETS uniform morphTargetInfluences : array; #ifdef MORPHTARGETS_TEXTURE uniform morphTargetTextureIndices : array;uniform morphTargetTextureInfo : vec3;var morphTargets : texture_2d_array;var morphTargetsSampler : sampler;fn readVector3FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec3 { let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0).xyz;} fn readVector4FromRawSampler(targetIndex : i32,vertexIndex : f32)->vec4 { let y=floor(vertexIndex/uniforms.morphTargetTextureInfo.y);let x=vertexIndex-y*uniforms.morphTargetTextureInfo.y;let textureUV=vec2((x+0.5)/uniforms.morphTargetTextureInfo.y,(y+0.5)/uniforms.morphTargetTextureInfo.z);return textureSampleLevel(morphTargets,morphTargetsSampler,textureUV,i32(uniforms.morphTargetTextureIndices[targetIndex]),0.0);} #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name24]) { ShaderStore.IncludesShadersStoreWGSL[name24] = shader24; } morphTargetsVertexGlobalDeclarationWGSL = { name: name24, shader: shader24 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexDeclaration.js var name25, shader25, morphTargetsVertexDeclarationWGSL; var init_morphTargetsVertexDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexDeclaration.js"() { init_shaderStore(); name25 = "morphTargetsVertexDeclaration"; shader25 = `#ifdef MORPHTARGETS #ifndef MORPHTARGETS_TEXTURE #ifdef MORPHTARGETS_POSITION attribute position{X} : vec3; #endif #ifdef MORPHTARGETS_NORMAL attribute normal{X} : vec3; #endif #ifdef MORPHTARGETS_TANGENT attribute tangent{X} : vec3; #endif #ifdef MORPHTARGETS_UV attribute uv_{X} : vec2; #endif #ifdef MORPHTARGETS_UV2 attribute uv2_{X} : vec2; #endif #ifdef MORPHTARGETS_COLOR attribute color{X} : vec4; #endif #elif {X}==0 uniform morphTargetCount: f32; #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name25]) { ShaderStore.IncludesShadersStoreWGSL[name25] = shader25; } morphTargetsVertexDeclarationWGSL = { name: name25, shader: shader25 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/sceneUboDeclaration.js var name26, shader26, sceneUboDeclarationWGSL; var init_sceneUboDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/sceneUboDeclaration.js"() { init_shaderStore(); name26 = "sceneUboDeclaration"; shader26 = `struct Scene {viewProjection : mat4x4, #ifdef MULTIVIEW viewProjectionR : mat4x4, #endif view : mat4x4, projection : mat4x4, vEyePosition : vec4,}; #define SCENE_UBO var scene : Scene; `; if (!ShaderStore.IncludesShadersStoreWGSL[name26]) { ShaderStore.IncludesShadersStoreWGSL[name26] = shader26; } sceneUboDeclarationWGSL = { name: name26, shader: shader26 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/meshUboDeclaration.js var name27, shader27, meshUboDeclarationWGSL; var init_meshUboDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/meshUboDeclaration.js"() { init_shaderStore(); name27 = "meshUboDeclaration"; shader27 = `struct Mesh {world : mat4x4, visibility : f32,};var mesh : Mesh; #define WORLD_UBO `; if (!ShaderStore.IncludesShadersStoreWGSL[name27]) { ShaderStore.IncludesShadersStoreWGSL[name27] = shader27; } meshUboDeclarationWGSL = { name: name27, shader: shader27 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexExtraDeclaration.js var name28, shader28, shadowMapVertexExtraDeclarationWGSL; var init_shadowMapVertexExtraDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexExtraDeclaration.js"() { init_shaderStore(); name28 = "shadowMapVertexExtraDeclaration"; shader28 = `#if SM_NORMALBIAS==1 uniform lightDataSM: vec3f; #endif uniform biasAndScaleSM: vec3f;uniform depthValuesSM: vec2f;varying vDepthMetricSM: f32; #if SM_USEDISTANCE==1 varying vPositionWSM: vec3f; #endif #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying zSM: f32; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name28]) { ShaderStore.IncludesShadersStoreWGSL[name28] = shader28; } shadowMapVertexExtraDeclarationWGSL = { name: name28, shader: shader28 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertexDeclaration.js var name29, shader29, clipPlaneVertexDeclarationWGSL; var init_clipPlaneVertexDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertexDeclaration.js"() { init_shaderStore(); name29 = "clipPlaneVertexDeclaration"; shader29 = `#ifdef CLIPPLANE uniform vClipPlane: vec4;varying fClipDistance: f32; #endif #ifdef CLIPPLANE2 uniform vClipPlane2: vec4;varying fClipDistance2: f32; #endif #ifdef CLIPPLANE3 uniform vClipPlane3: vec4;varying fClipDistance3: f32; #endif #ifdef CLIPPLANE4 uniform vClipPlane4: vec4;varying fClipDistance4: f32; #endif #ifdef CLIPPLANE5 uniform vClipPlane5: vec4;varying fClipDistance5: f32; #endif #ifdef CLIPPLANE6 uniform vClipPlane6: vec4;varying fClipDistance6: f32; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name29]) { ShaderStore.IncludesShadersStoreWGSL[name29] = shader29; } clipPlaneVertexDeclarationWGSL = { name: name29, shader: shader29 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobal.js var name30, shader30, morphTargetsVertexGlobalWGSL; var init_morphTargetsVertexGlobal = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertexGlobal.js"() { init_shaderStore(); name30 = "morphTargetsVertexGlobal"; shader30 = `#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE var vertexID : f32; #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name30]) { ShaderStore.IncludesShadersStoreWGSL[name30] = shader30; } morphTargetsVertexGlobalWGSL = { name: name30, shader: shader30 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertex.js var name31, shader31, morphTargetsVertexWGSL; var init_morphTargetsVertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/morphTargetsVertex.js"() { init_shaderStore(); name31 = "morphTargetsVertex"; shader31 = `#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE #if {X}==0 for (var i=0; i=uniforms.morphTargetCount) {break;} vertexID=f32(vertexInputs.vertexIndex)*uniforms.morphTargetTextureInfo.x; #ifdef MORPHTARGETS_POSITION positionUpdated=positionUpdated+(readVector3FromRawSampler(i,vertexID)-vertexInputs.position)*uniforms.morphTargetInfluences[i]; #endif #ifdef MORPHTARGETTEXTURE_HASPOSITIONS vertexID=vertexID+1.0; #endif #ifdef MORPHTARGETS_NORMAL normalUpdated=normalUpdated+(readVector3FromRawSampler(i,vertexID) -vertexInputs.normal)*uniforms.morphTargetInfluences[i]; #endif #ifdef MORPHTARGETTEXTURE_HASNORMALS vertexID=vertexID+1.0; #endif #ifdef MORPHTARGETS_UV uvUpdated=uvUpdated+(readVector3FromRawSampler(i,vertexID).xy-vertexInputs.uv)*uniforms.morphTargetInfluences[i]; #endif #ifdef MORPHTARGETTEXTURE_HASUVS vertexID=vertexID+1.0; #endif #ifdef MORPHTARGETS_TANGENT tangentUpdated=vec4f(tangentUpdated.xyz+(readVector3FromRawSampler(i,vertexID) -vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[i],tangentUpdated.a); #endif #ifdef MORPHTARGETTEXTURE_HASTANGENTS vertexID=vertexID+1.0; #endif #ifdef MORPHTARGETS_UV2 uv2Updated=uv2Updated+(readVector3FromRawSampler(i,vertexID).xy-vertexInputs.uv2)*uniforms.morphTargetInfluences[i]; #endif #ifdef MORPHTARGETS_COLOR colorUpdated=colorUpdated+(readVector4FromRawSampler(i,vertexID)-vertexInputs.color)*uniforms.morphTargetInfluences[i]; #endif } #endif #else #ifdef MORPHTARGETS_POSITION positionUpdated=positionUpdated+(vertexInputs.position{X}-vertexInputs.position)*uniforms.morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_NORMAL normalUpdated=normalUpdated+(vertexInputs.normal{X}-vertexInputs.normal)*uniforms.morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_TANGENT tangentUpdated=vec4f(tangentUpdated.xyz+(vertexInputs.tangent{X}-vertexInputs.tangent.xyz)*uniforms.morphTargetInfluences[{X}],tangentUpdated.a); #endif #ifdef MORPHTARGETS_UV uvUpdated=uvUpdated+(vertexInputs.uv_{X}-vertexInputs.uv)*uniforms.morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_UV2 uv2Updated=uv2Updated+(vertexInputs.uv2_{X}-vertexInputs.uv2)*uniforms.morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_COLOR colorUpdated=colorUpdated+(vertexInputs.color{X}-vertexInputs.color)*uniforms.morphTargetInfluences[{X}]; #endif #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name31]) { ShaderStore.IncludesShadersStoreWGSL[name31] = shader31; } morphTargetsVertexWGSL = { name: name31, shader: shader31 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesVertex.js var name32, shader32, instancesVertexWGSL; var init_instancesVertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesVertex.js"() { init_shaderStore(); name32 = "instancesVertex"; shader32 = `#ifdef INSTANCES var finalWorld=mat4x4(vertexInputs.world0,vertexInputs.world1,vertexInputs.world2,vertexInputs.world3); #if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) var finalPreviousWorld=mat4x4( vertexInputs.previousWorld0,vertexInputs.previousWorld1, vertexInputs.previousWorld2,vertexInputs.previousWorld3); #endif #ifdef THIN_INSTANCES #if !defined(WORLD_UBO) finalWorld=uniforms.world*finalWorld; #else finalWorld=mesh.world*finalWorld; #endif #if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) finalPreviousWorld=uniforms.previousWorld*finalPreviousWorld; #endif #endif #else #if !defined(WORLD_UBO) var finalWorld=uniforms.world; #else var finalWorld=mesh.world; #endif #if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) var finalPreviousWorld=uniforms.previousWorld; #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name32]) { ShaderStore.IncludesShadersStoreWGSL[name32] = shader32; } instancesVertexWGSL = { name: name32, shader: shader32 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesVertex.js var name33, shader33, bonesVertexWGSL; var init_bonesVertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bonesVertex.js"() { init_shaderStore(); name33 = "bonesVertex"; shader33 = `#ifndef BAKED_VERTEX_ANIMATION_TEXTURE #if NUM_BONE_INFLUENCERS>0 var influence : mat4x4; #ifdef BONETEXTURE influence=readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[0])*vertexInputs.matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[1])*vertexInputs.matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[2])*vertexInputs.matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndices[3])*vertexInputs.matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[0])*vertexInputs.matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[1])*vertexInputs.matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[2])*vertexInputs.matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 influence=influence+readMatrixFromRawSampler(boneSampler,vertexInputs.matricesIndicesExtra[3])*vertexInputs.matricesWeightsExtra[3]; #endif #else influence=uniforms.mBones[i32(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 influence=influence+uniforms.mBones[i32(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3]; #endif #endif finalWorld=finalWorld*influence; #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name33]) { ShaderStore.IncludesShadersStoreWGSL[name33] = shader33; } bonesVertexWGSL = { name: name33, shader: shader33 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimation.js var name34, shader34, bakedVertexAnimationWGSL; var init_bakedVertexAnimation = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bakedVertexAnimation.js"() { init_shaderStore(); name34 = "bakedVertexAnimation"; shader34 = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE { #ifdef INSTANCES let VATStartFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.x;let VATEndFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.y;let VATOffsetFrame: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.z;let VATSpeed: f32=vertexInputs.bakedVertexAnimationSettingsInstanced.w; #else let VATStartFrame: f32=uniforms.bakedVertexAnimationSettings.x;let VATEndFrame: f32=uniforms.bakedVertexAnimationSettings.y;let VATOffsetFrame: f32=uniforms.bakedVertexAnimationSettings.z;let VATSpeed: f32=uniforms.bakedVertexAnimationSettings.w; #endif let totalFrames: f32=VATEndFrame-VATStartFrame+1.0;let time: f32=uniforms.bakedVertexAnimationTime*VATSpeed/totalFrames;let frameCorrection: f32=select(1.0,0.0,time<1.0);let numOfFrames: f32=totalFrames-frameCorrection;var VATFrameNum: f32=fract(time)*numOfFrames;VATFrameNum=(VATFrameNum+VATOffsetFrame) % numOfFrames;VATFrameNum=floor(VATFrameNum);VATFrameNum=VATFrameNum+VATStartFrame+frameCorrection;var VATInfluence : mat4x4;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[0],VATFrameNum)*vertexInputs.matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[1],VATFrameNum)*vertexInputs.matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[2],VATFrameNum)*vertexInputs.matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndices[3],VATFrameNum)*vertexInputs.matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[0],VATFrameNum)*vertexInputs.matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[1],VATFrameNum)*vertexInputs.matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[2],VATFrameNum)*vertexInputs.matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 VATInfluence=VATInfluence+readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,vertexInputs.matricesIndicesExtra[3],VATFrameNum)*vertexInputs.matricesWeightsExtra[3]; #endif finalWorld=finalWorld*VATInfluence;} #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name34]) { ShaderStore.IncludesShadersStoreWGSL[name34] = shader34; } bakedVertexAnimationWGSL = { name: name34, shader: shader34 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexNormalBias.js var name35, shader35, shadowMapVertexNormalBiasWGSL; var init_shadowMapVertexNormalBias = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexNormalBias.js"() { init_shaderStore(); name35 = "shadowMapVertexNormalBias"; shader35 = `#if SM_NORMALBIAS==1 #if SM_DIRECTIONINLIGHTDATA==1 var worldLightDirSM: vec3f=normalize(-uniforms.lightDataSM.xyz); #else var directionToLightSM: vec3f=uniforms.lightDataSM.xyz-worldPos.xyz;var worldLightDirSM: vec3f=normalize(directionToLightSM); #endif var ndlSM: f32=dot(vNormalW,worldLightDirSM);var sinNLSM: f32=sqrt(1.0-ndlSM*ndlSM);var normalBiasSM: f32=uniforms.biasAndScaleSM.y*sinNLSM;worldPos=vec4f(worldPos.xyz-vNormalW*normalBiasSM,worldPos.w); #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name35]) { ShaderStore.IncludesShadersStoreWGSL[name35] = shader35; } shadowMapVertexNormalBiasWGSL = { name: name35, shader: shader35 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexMetric.js var name36, shader36, shadowMapVertexMetricWGSL; var init_shadowMapVertexMetric = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapVertexMetric.js"() { init_shaderStore(); name36 = "shadowMapVertexMetric"; shader36 = `#if SM_USEDISTANCE==1 vertexOutputs.vPositionWSM=worldPos.xyz; #endif #if SM_DEPTHTEXTURE==1 #ifdef IS_NDC_HALF_ZRANGE #define BIASFACTOR 0.5 #else #define BIASFACTOR 1.0 #endif #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.position.z-=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR; #else vertexOutputs.position.z+=uniforms.biasAndScaleSM.x*vertexOutputs.position.w*BIASFACTOR; #endif #endif #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 vertexOutputs.zSM=vertexOutputs.position.z;vertexOutputs.position.z=0.0; #elif SM_USEDISTANCE==0 #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.vDepthMetricSM=(-vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; #else vertexOutputs.vDepthMetricSM=(vertexOutputs.position.z+uniforms.depthValuesSM.x)/uniforms.depthValuesSM.y+uniforms.biasAndScaleSM.x; #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name36]) { ShaderStore.IncludesShadersStoreWGSL[name36] = shader36; } shadowMapVertexMetricWGSL = { name: name36, shader: shader36 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertex.js var name37, shader37, clipPlaneVertexWGSL; var init_clipPlaneVertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clipPlaneVertex.js"() { init_shaderStore(); name37 = "clipPlaneVertex"; shader37 = `#ifdef CLIPPLANE vertexOutputs.fClipDistance=dot(worldPos,uniforms.vClipPlane); #endif #ifdef CLIPPLANE2 vertexOutputs.fClipDistance2=dot(worldPos,uniforms.vClipPlane2); #endif #ifdef CLIPPLANE3 vertexOutputs.fClipDistance3=dot(worldPos,uniforms.vClipPlane3); #endif #ifdef CLIPPLANE4 vertexOutputs.fClipDistance4=dot(worldPos,uniforms.vClipPlane4); #endif #ifdef CLIPPLANE5 vertexOutputs.fClipDistance5=dot(worldPos,uniforms.vClipPlane5); #endif #ifdef CLIPPLANE6 vertexOutputs.fClipDistance6=dot(worldPos,uniforms.vClipPlane6); #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name37]) { ShaderStore.IncludesShadersStoreWGSL[name37] = shader37; } clipPlaneVertexWGSL = { name: name37, shader: shader37 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/shadowMap.vertex.js var shadowMap_vertex_exports = {}; __export(shadowMap_vertex_exports, { shadowMapVertexShaderWGSL: () => shadowMapVertexShaderWGSL }); var name38, shader38, shadowMapVertexShaderWGSL; var init_shadowMap_vertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/shadowMap.vertex.js"() { init_shaderStore(); init_bonesDeclaration(); init_bakedVertexAnimationDeclaration(); init_morphTargetsVertexGlobalDeclaration(); init_morphTargetsVertexDeclaration(); init_helperFunctions(); init_sceneUboDeclaration(); init_meshUboDeclaration(); init_shadowMapVertexExtraDeclaration(); init_clipPlaneVertexDeclaration(); init_morphTargetsVertexGlobal(); init_morphTargetsVertex(); init_instancesVertex(); init_bonesVertex(); init_bakedVertexAnimation(); init_shadowMapVertexNormalBias(); init_shadowMapVertexMetric(); init_clipPlaneVertex(); name38 = "shadowMapVertexShader"; shader38 = `attribute position: vec3f; #ifdef NORMAL attribute normal: vec3f; #endif #include #include #include #include[0..maxSimultaneousMorphTargets] #ifdef INSTANCES attribute world0: vec4f;attribute world1: vec4f;attribute world2: vec4f;attribute world3: vec4f; #endif #include #include #include #ifdef ALPHATEXTURE varying vUV: vec2f;uniform diffuseMatrix: mat4x4f; #ifdef UV1 attribute uv: vec2f; #endif #ifdef UV2 attribute uv2: vec2f; #endif #endif #include #include #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position; #ifdef UV1 var uvUpdated: vec2f=input.uv; #endif #ifdef UV2 var uv2Updated: vec2f=input.uv2; #endif #ifdef NORMAL var normalUpdated: vec3f=input.normal; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0); #ifdef NORMAL var normWorldSM: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz); #if defined(INSTANCES) && defined(THIN_INSTANCES) var vNormalW: vec3f=normalUpdated/ vec3f(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); #else #ifdef NONUNIFORMSCALING normWorldSM=transposeMat3(inverseMat3(normWorldSM)); #endif var vNormalW: vec3f=normalize(normWorldSM*normalUpdated); #endif #endif #include vertexOutputs.position=scene.viewProjection*worldPos; #include #ifdef ALPHATEXTURE #ifdef UV1 vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef UV2 vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy; #endif #endif #include }`; if (!ShaderStore.ShadersStoreWGSL[name38]) { ShaderStore.ShadersStoreWGSL[name38] = shader38; } shadowMapVertexShaderWGSL = { name: name38, shader: shader38 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/depthBoxBlur.fragment.js var depthBoxBlur_fragment_exports = {}; __export(depthBoxBlur_fragment_exports, { depthBoxBlurPixelShaderWGSL: () => depthBoxBlurPixelShaderWGSL }); var name39, shader39, depthBoxBlurPixelShaderWGSL; var init_depthBoxBlur_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/depthBoxBlur.fragment.js"() { init_shaderStore(); name39 = "depthBoxBlurPixelShader"; shader39 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var colorDepth: vec4f=vec4f(0.0);for (var x: i32=-OFFSET; x<=OFFSET; x++) {for (var y: i32=-OFFSET; y<=OFFSET; y++) {colorDepth+=textureSample(textureSampler,textureSamplerSampler,input.vUV+ vec2f(f32(x),f32(y))/uniforms.screenSize);}} fragmentOutputs.color=(colorDepth/ f32((OFFSET*2+1)*(OFFSET*2+1)));}`; if (!ShaderStore.ShadersStoreWGSL[name39]) { ShaderStore.ShadersStoreWGSL[name39] = shader39; } depthBoxBlurPixelShaderWGSL = { name: name39, shader: shader39 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js var shadowMapFragmentSoftTransparentShadow_exports = {}; __export(shadowMapFragmentSoftTransparentShadow_exports, { shadowMapFragmentSoftTransparentShadowWGSL: () => shadowMapFragmentSoftTransparentShadowWGSL }); var name40, shader40, shadowMapFragmentSoftTransparentShadowWGSL; var init_shadowMapFragmentSoftTransparentShadow = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js"() { init_shaderStore(); name40 = "shadowMapFragmentSoftTransparentShadow"; shader40 = `#if SM_SOFTTRANSPARENTSHADOW==1 if ((bayerDither8(floor(((fragmentInputs.position.xy)%(8.0)))))/64.0>=uniforms.softTransparentShadowSM.x*alpha) {discard;} #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name40]) { ShaderStore.IncludesShadersStoreWGSL[name40] = shader40; } shadowMapFragmentSoftTransparentShadowWGSL = { name: name40, shader: shader40 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/packingFunctions.js var name41, shader41, packingFunctions; var init_packingFunctions2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/packingFunctions.js"() { init_shaderStore(); name41 = "packingFunctions"; shader41 = `vec4 pack(float depth) {const vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);const vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);vec4 res=fract(depth*bit_shift);res-=res.xxyz*bit_mask;return res;} float unpack(vec4 color) {const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);}`; if (!ShaderStore.IncludesShadersStore[name41]) { ShaderStore.IncludesShadersStore[name41] = shader41; } packingFunctions = { name: name41, shader: shader41 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bayerDitherFunctions.js var name42, shader42, bayerDitherFunctions; var init_bayerDitherFunctions2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bayerDitherFunctions.js"() { init_shaderStore(); name42 = "bayerDitherFunctions"; shader42 = `float bayerDither2(vec2 _P) {return mod(2.0*_P.y+_P.x+1.0,4.0);} float bayerDither4(vec2 _P) {vec2 P1=mod(_P,2.0); vec2 P2=floor(0.5*mod(_P,4.0)); return 4.0*bayerDither2(P1)+bayerDither2(P2);} float bayerDither8(vec2 _P) {vec2 P1=mod(_P,2.0); vec2 P2=floor(0.5 *mod(_P,4.0)); vec2 P4=floor(0.25*mod(_P,8.0)); return 4.0*(4.0*bayerDither2(P1)+bayerDither2(P2))+bayerDither2(P4);} `; if (!ShaderStore.IncludesShadersStore[name42]) { ShaderStore.IncludesShadersStore[name42] = shader42; } bayerDitherFunctions = { name: name42, shader: shader42 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentExtraDeclaration.js var name43, shader43, shadowMapFragmentExtraDeclaration; var init_shadowMapFragmentExtraDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentExtraDeclaration.js"() { init_shaderStore(); init_packingFunctions2(); init_bayerDitherFunctions2(); name43 = "shadowMapFragmentExtraDeclaration"; shader43 = `#if SM_FLOAT==0 #include #endif #if SM_SOFTTRANSPARENTSHADOW==1 #include uniform vec2 softTransparentShadowSM; #endif varying float vDepthMetricSM; #if SM_USEDISTANCE==1 uniform vec3 lightDataSM;varying vec3 vPositionWSM; #endif uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying float zSM; #endif `; if (!ShaderStore.IncludesShadersStore[name43]) { ShaderStore.IncludesShadersStore[name43] = shader43; } shadowMapFragmentExtraDeclaration = { name: name43, shader: shader43 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragmentDeclaration.js var name44, shader44, clipPlaneFragmentDeclaration; var init_clipPlaneFragmentDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragmentDeclaration.js"() { init_shaderStore(); name44 = "clipPlaneFragmentDeclaration"; shader44 = `#ifdef CLIPPLANE varying float fClipDistance; #endif #ifdef CLIPPLANE2 varying float fClipDistance2; #endif #ifdef CLIPPLANE3 varying float fClipDistance3; #endif #ifdef CLIPPLANE4 varying float fClipDistance4; #endif #ifdef CLIPPLANE5 varying float fClipDistance5; #endif #ifdef CLIPPLANE6 varying float fClipDistance6; #endif `; if (!ShaderStore.IncludesShadersStore[name44]) { ShaderStore.IncludesShadersStore[name44] = shader44; } clipPlaneFragmentDeclaration = { name: name44, shader: shader44 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragment.js var name45, shader45, clipPlaneFragment; var init_clipPlaneFragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragment.js"() { init_shaderStore(); name45 = "clipPlaneFragment"; shader45 = `#if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) if (false) {} #endif #ifdef CLIPPLANE else if (fClipDistance>0.0) {discard;} #endif #ifdef CLIPPLANE2 else if (fClipDistance2>0.0) {discard;} #endif #ifdef CLIPPLANE3 else if (fClipDistance3>0.0) {discard;} #endif #ifdef CLIPPLANE4 else if (fClipDistance4>0.0) {discard;} #endif #ifdef CLIPPLANE5 else if (fClipDistance5>0.0) {discard;} #endif #ifdef CLIPPLANE6 else if (fClipDistance6>0.0) {discard;} #endif `; if (!ShaderStore.IncludesShadersStore[name45]) { ShaderStore.IncludesShadersStore[name45] = shader45; } clipPlaneFragment = { name: name45, shader: shader45 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragment.js var name46, shader46, shadowMapFragment; var init_shadowMapFragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragment.js"() { init_shaderStore(); name46 = "shadowMapFragment"; shader46 = `float depthSM=vDepthMetricSM; #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 #if SM_USEDISTANCE==1 depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #else #ifdef USE_REVERSE_DEPTHBUFFER depthSM=(-zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #else depthSM=(zSM+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #endif #endif depthSM=clamp(depthSM,0.0,1.0); #ifdef USE_REVERSE_DEPTHBUFFER gl_FragDepth=clamp(1.0-depthSM,0.0,1.0); #else gl_FragDepth=clamp(depthSM,0.0,1.0); #endif #elif SM_USEDISTANCE==1 depthSM=(length(vPositionWSM-lightDataSM)+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #endif #if SM_ESM==1 depthSM=clamp(exp(-min(87.,biasAndScaleSM.z*depthSM)),0.,1.); #endif #if SM_FLOAT==1 gl_FragColor=vec4(depthSM,1.0,1.0,1.0); #else gl_FragColor=pack(depthSM); #endif return;`; if (!ShaderStore.IncludesShadersStore[name46]) { ShaderStore.IncludesShadersStore[name46] = shader46; } shadowMapFragment = { name: name46, shader: shader46 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/shadowMap.fragment.js var shadowMap_fragment_exports2 = {}; __export(shadowMap_fragment_exports2, { shadowMapPixelShader: () => shadowMapPixelShader }); var name47, shader47, shadowMapPixelShader; var init_shadowMap_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/shadowMap.fragment.js"() { init_shaderStore(); init_shadowMapFragmentExtraDeclaration2(); init_clipPlaneFragmentDeclaration2(); init_clipPlaneFragment2(); init_shadowMapFragment2(); name47 = "shadowMapPixelShader"; shader47 = `#include #ifdef ALPHATEXTURE varying vec2 vUV;uniform sampler2D diffuseSampler; #endif #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #include #ifdef ALPHATEXTURE vec4 opacityMap=texture2D(diffuseSampler,vUV);float alphaFromAlphaTexture=opacityMap.a; #if SM_SOFTTRANSPARENTSHADOW==1 if (softTransparentShadowSM.y==1.0) {opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alphaFromAlphaTexture=opacityMap.x+opacityMap.y+opacityMap.z;} #endif #ifdef ALPHATESTVALUE if (alphaFromAlphaTexture=softTransparentShadowSM.x*alphaFromAlphaTexture) discard; #else if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x) discard; #endif #endif #include }`; if (!ShaderStore.ShadersStore[name47]) { ShaderStore.ShadersStore[name47] = shader47; } shadowMapPixelShader = { name: name47, shader: shader47 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bonesDeclaration.js var name48, shader48, bonesDeclaration; var init_bonesDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bonesDeclaration.js"() { init_shaderStore(); name48 = "bonesDeclaration"; shader48 = `#if NUM_BONE_INFLUENCERS>0 attribute vec4 matricesIndices;attribute vec4 matricesWeights; #if NUM_BONE_INFLUENCERS>4 attribute vec4 matricesIndicesExtra;attribute vec4 matricesWeightsExtra; #endif #ifndef BAKED_VERTEX_ANIMATION_TEXTURE #ifdef BONETEXTURE uniform highp sampler2D boneSampler;uniform float boneTextureWidth; #else uniform mat4 mBones[BonesPerMesh]; #endif #ifdef BONES_VELOCITY_ENABLED uniform mat4 mPreviousBones[BonesPerMesh]; #endif #ifdef BONETEXTURE #define inline mat4 readMatrixFromRawSampler(sampler2D smp,float index) {float offset=index *4.0;float dx=1.0/boneTextureWidth;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),0.));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),0.));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),0.));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),0.));return mat4(m0,m1,m2,m3);} #endif #endif #endif `; if (!ShaderStore.IncludesShadersStore[name48]) { ShaderStore.IncludesShadersStore[name48] = shader48; } bonesDeclaration = { name: name48, shader: shader48 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bakedVertexAnimationDeclaration.js var name49, shader49, bakedVertexAnimationDeclaration; var init_bakedVertexAnimationDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bakedVertexAnimationDeclaration.js"() { init_shaderStore(); name49 = "bakedVertexAnimationDeclaration"; shader49 = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE uniform float bakedVertexAnimationTime;uniform vec2 bakedVertexAnimationTextureSizeInverted;uniform vec4 bakedVertexAnimationSettings;uniform sampler2D bakedVertexAnimationTexture; #ifdef INSTANCES attribute vec4 bakedVertexAnimationSettingsInstanced; #endif #define inline mat4 readMatrixFromRawSamplerVAT(sampler2D smp,float index,float frame) {float offset=index*4.0;float frameUV=(frame+0.5)*bakedVertexAnimationTextureSizeInverted.y;float dx=bakedVertexAnimationTextureSizeInverted.x;vec4 m0=texture2D(smp,vec2(dx*(offset+0.5),frameUV));vec4 m1=texture2D(smp,vec2(dx*(offset+1.5),frameUV));vec4 m2=texture2D(smp,vec2(dx*(offset+2.5),frameUV));vec4 m3=texture2D(smp,vec2(dx*(offset+3.5),frameUV));return mat4(m0,m1,m2,m3);} #endif `; if (!ShaderStore.IncludesShadersStore[name49]) { ShaderStore.IncludesShadersStore[name49] = shader49; } bakedVertexAnimationDeclaration = { name: name49, shader: shader49 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexGlobalDeclaration.js var name50, shader50, morphTargetsVertexGlobalDeclaration; var init_morphTargetsVertexGlobalDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexGlobalDeclaration.js"() { init_shaderStore(); name50 = "morphTargetsVertexGlobalDeclaration"; shader50 = `#ifdef MORPHTARGETS uniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS]; #ifdef MORPHTARGETS_TEXTURE uniform float morphTargetTextureIndices[NUM_MORPH_INFLUENCERS];uniform vec3 morphTargetTextureInfo;uniform highp sampler2DArray morphTargets;vec3 readVector3FromRawSampler(int targetIndex,float vertexIndex) { float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV).xyz;} vec4 readVector4FromRawSampler(int targetIndex,float vertexIndex) { float y=floor(vertexIndex/morphTargetTextureInfo.y);float x=vertexIndex-y*morphTargetTextureInfo.y;vec3 textureUV=vec3((x+0.5)/morphTargetTextureInfo.y,(y+0.5)/morphTargetTextureInfo.z,morphTargetTextureIndices[targetIndex]);return texture(morphTargets,textureUV);} #endif #endif `; if (!ShaderStore.IncludesShadersStore[name50]) { ShaderStore.IncludesShadersStore[name50] = shader50; } morphTargetsVertexGlobalDeclaration = { name: name50, shader: shader50 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexDeclaration.js var name51, shader51, morphTargetsVertexDeclaration; var init_morphTargetsVertexDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexDeclaration.js"() { init_shaderStore(); name51 = "morphTargetsVertexDeclaration"; shader51 = `#ifdef MORPHTARGETS #ifndef MORPHTARGETS_TEXTURE #ifdef MORPHTARGETS_POSITION attribute vec3 position{X}; #endif #ifdef MORPHTARGETS_NORMAL attribute vec3 normal{X}; #endif #ifdef MORPHTARGETS_TANGENT attribute vec3 tangent{X}; #endif #ifdef MORPHTARGETS_UV attribute vec2 uv_{X}; #endif #ifdef MORPHTARGETS_UV2 attribute vec2 uv2_{X}; #endif #ifdef MORPHTARGETS_COLOR attribute vec4 color{X}; #endif #elif {X}==0 uniform float morphTargetCount; #endif #endif `; if (!ShaderStore.IncludesShadersStore[name51]) { ShaderStore.IncludesShadersStore[name51] = shader51; } morphTargetsVertexDeclaration = { name: name51, shader: shader51 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneVertexDeclaration.js var name52, shader52, sceneVertexDeclaration; var init_sceneVertexDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneVertexDeclaration.js"() { init_shaderStore(); name52 = "sceneVertexDeclaration"; shader52 = `uniform mat4 viewProjection; #ifdef MULTIVIEW uniform mat4 viewProjectionR; #endif uniform mat4 view;uniform mat4 projection;uniform vec4 vEyePosition; `; if (!ShaderStore.IncludesShadersStore[name52]) { ShaderStore.IncludesShadersStore[name52] = shader52; } sceneVertexDeclaration = { name: name52, shader: shader52 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/meshVertexDeclaration.js var name53, shader53, meshVertexDeclaration; var init_meshVertexDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/meshVertexDeclaration.js"() { init_shaderStore(); name53 = "meshVertexDeclaration"; shader53 = `uniform mat4 world;uniform float visibility; `; if (!ShaderStore.IncludesShadersStore[name53]) { ShaderStore.IncludesShadersStore[name53] = shader53; } meshVertexDeclaration = { name: name53, shader: shader53 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexDeclaration.js var name54, shader54, shadowMapVertexDeclaration; var init_shadowMapVertexDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexDeclaration.js"() { init_shaderStore(); init_sceneVertexDeclaration(); init_meshVertexDeclaration(); name54 = "shadowMapVertexDeclaration"; shader54 = `#include #include `; if (!ShaderStore.IncludesShadersStore[name54]) { ShaderStore.IncludesShadersStore[name54] = shader54; } shadowMapVertexDeclaration = { name: name54, shader: shader54 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneUboDeclaration.js var name55, shader55, sceneUboDeclaration; var init_sceneUboDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/sceneUboDeclaration.js"() { init_shaderStore(); name55 = "sceneUboDeclaration"; shader55 = `layout(std140,column_major) uniform;uniform Scene {mat4 viewProjection; #ifdef MULTIVIEW mat4 viewProjectionR; #endif mat4 view;mat4 projection;vec4 vEyePosition;}; `; if (!ShaderStore.IncludesShadersStore[name55]) { ShaderStore.IncludesShadersStore[name55] = shader55; } sceneUboDeclaration = { name: name55, shader: shader55 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/meshUboDeclaration.js var name56, shader56, meshUboDeclaration; var init_meshUboDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/meshUboDeclaration.js"() { init_shaderStore(); name56 = "meshUboDeclaration"; shader56 = `#ifdef WEBGL2 uniform mat4 world;uniform float visibility; #else layout(std140,column_major) uniform;uniform Mesh {mat4 world;float visibility;}; #endif #define WORLD_UBO `; if (!ShaderStore.IncludesShadersStore[name56]) { ShaderStore.IncludesShadersStore[name56] = shader56; } meshUboDeclaration = { name: name56, shader: shader56 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapUboDeclaration.js var name57, shader57, shadowMapUboDeclaration; var init_shadowMapUboDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapUboDeclaration.js"() { init_shaderStore(); init_sceneUboDeclaration2(); init_meshUboDeclaration2(); name57 = "shadowMapUboDeclaration"; shader57 = `layout(std140,column_major) uniform; #include #include `; if (!ShaderStore.IncludesShadersStore[name57]) { ShaderStore.IncludesShadersStore[name57] = shader57; } shadowMapUboDeclaration = { name: name57, shader: shader57 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexExtraDeclaration.js var name58, shader58, shadowMapVertexExtraDeclaration; var init_shadowMapVertexExtraDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexExtraDeclaration.js"() { init_shaderStore(); name58 = "shadowMapVertexExtraDeclaration"; shader58 = `#if SM_NORMALBIAS==1 uniform vec3 lightDataSM; #endif uniform vec3 biasAndScaleSM;uniform vec2 depthValuesSM;varying float vDepthMetricSM; #if SM_USEDISTANCE==1 varying vec3 vPositionWSM; #endif #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 varying float zSM; #endif `; if (!ShaderStore.IncludesShadersStore[name58]) { ShaderStore.IncludesShadersStore[name58] = shader58; } shadowMapVertexExtraDeclaration = { name: name58, shader: shader58 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertexDeclaration.js var name59, shader59, clipPlaneVertexDeclaration; var init_clipPlaneVertexDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertexDeclaration.js"() { init_shaderStore(); name59 = "clipPlaneVertexDeclaration"; shader59 = `#ifdef CLIPPLANE uniform vec4 vClipPlane;varying float fClipDistance; #endif #ifdef CLIPPLANE2 uniform vec4 vClipPlane2;varying float fClipDistance2; #endif #ifdef CLIPPLANE3 uniform vec4 vClipPlane3;varying float fClipDistance3; #endif #ifdef CLIPPLANE4 uniform vec4 vClipPlane4;varying float fClipDistance4; #endif #ifdef CLIPPLANE5 uniform vec4 vClipPlane5;varying float fClipDistance5; #endif #ifdef CLIPPLANE6 uniform vec4 vClipPlane6;varying float fClipDistance6; #endif `; if (!ShaderStore.IncludesShadersStore[name59]) { ShaderStore.IncludesShadersStore[name59] = shader59; } clipPlaneVertexDeclaration = { name: name59, shader: shader59 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexGlobal.js var name60, shader60, morphTargetsVertexGlobal; var init_morphTargetsVertexGlobal2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertexGlobal.js"() { init_shaderStore(); name60 = "morphTargetsVertexGlobal"; shader60 = `#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE float vertexID; #endif #endif `; if (!ShaderStore.IncludesShadersStore[name60]) { ShaderStore.IncludesShadersStore[name60] = shader60; } morphTargetsVertexGlobal = { name: name60, shader: shader60 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertex.js var name61, shader61, morphTargetsVertex; var init_morphTargetsVertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/morphTargetsVertex.js"() { init_shaderStore(); name61 = "morphTargetsVertex"; shader61 = `#ifdef MORPHTARGETS #ifdef MORPHTARGETS_TEXTURE #if {X}==0 for (int i=0; i=morphTargetCount) break;vertexID=float(gl_VertexID)*morphTargetTextureInfo.x; #ifdef MORPHTARGETS_POSITION positionUpdated+=(readVector3FromRawSampler(i,vertexID)-position)*morphTargetInfluences[i]; #endif #ifdef MORPHTARGETTEXTURE_HASPOSITIONS vertexID+=1.0; #endif #ifdef MORPHTARGETS_NORMAL normalUpdated+=(readVector3FromRawSampler(i,vertexID) -normal)*morphTargetInfluences[i]; #endif #ifdef MORPHTARGETTEXTURE_HASNORMALS vertexID+=1.0; #endif #ifdef MORPHTARGETS_UV uvUpdated+=(readVector3FromRawSampler(i,vertexID).xy-uv)*morphTargetInfluences[i]; #endif #ifdef MORPHTARGETTEXTURE_HASUVS vertexID+=1.0; #endif #ifdef MORPHTARGETS_TANGENT tangentUpdated.xyz+=(readVector3FromRawSampler(i,vertexID) -tangent.xyz)*morphTargetInfluences[i]; #endif #ifdef MORPHTARGETTEXTURE_HASTANGENTS vertexID+=1.0; #endif #ifdef MORPHTARGETS_UV2 uv2Updated+=(readVector3FromRawSampler(i,vertexID).xy-uv2)*morphTargetInfluences[i]; #endif #ifdef MORPHTARGETTEXTURE_HASUV2S vertexID+=1.0; #endif #ifdef MORPHTARGETS_COLOR colorUpdated+=(readVector4FromRawSampler(i,vertexID)-color)*morphTargetInfluences[i]; #endif } #endif #else #ifdef MORPHTARGETS_POSITION positionUpdated+=(position{X}-position)*morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_NORMAL normalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_TANGENT tangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_UV uvUpdated+=(uv_{X}-uv)*morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_UV2 uv2Updated+=(uv2_{X}-uv2)*morphTargetInfluences[{X}]; #endif #ifdef MORPHTARGETS_COLOR colorUpdated+=(color{X}-color)*morphTargetInfluences[{X}]; #endif #endif #endif `; if (!ShaderStore.IncludesShadersStore[name61]) { ShaderStore.IncludesShadersStore[name61] = shader61; } morphTargetsVertex = { name: name61, shader: shader61 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/instancesVertex.js var name62, shader62, instancesVertex; var init_instancesVertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/instancesVertex.js"() { init_shaderStore(); name62 = "instancesVertex"; shader62 = `#ifdef INSTANCES mat4 finalWorld=mat4(world0,world1,world2,world3); #if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) mat4 finalPreviousWorld=mat4(previousWorld0,previousWorld1, previousWorld2,previousWorld3); #endif #ifdef THIN_INSTANCES finalWorld=world*finalWorld; #if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) finalPreviousWorld=previousWorld*finalPreviousWorld; #endif #endif #else mat4 finalWorld=world; #if defined(PREPASS_VELOCITY) || defined(VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) mat4 finalPreviousWorld=previousWorld; #endif #endif `; if (!ShaderStore.IncludesShadersStore[name62]) { ShaderStore.IncludesShadersStore[name62] = shader62; } instancesVertex = { name: name62, shader: shader62 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bonesVertex.js var name63, shader63, bonesVertex; var init_bonesVertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bonesVertex.js"() { init_shaderStore(); name63 = "bonesVertex"; shader63 = `#ifndef BAKED_VERTEX_ANIMATION_TEXTURE #if NUM_BONE_INFLUENCERS>0 mat4 influence; #ifdef BONETEXTURE influence=readMatrixFromRawSampler(boneSampler,matricesIndices[0])*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[1])*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[2])*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 influence+=readMatrixFromRawSampler(boneSampler,matricesIndices[3])*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[0])*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[1])*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[2])*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 influence+=readMatrixFromRawSampler(boneSampler,matricesIndicesExtra[3])*matricesWeightsExtra[3]; #endif #else influence=mBones[int(matricesIndices[0])]*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 influence+=mBones[int(matricesIndices[1])]*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 influence+=mBones[int(matricesIndices[2])]*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 influence+=mBones[int(matricesIndices[3])]*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 influence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 influence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 influence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 influence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; #endif #endif finalWorld=finalWorld*influence; #endif #endif `; if (!ShaderStore.IncludesShadersStore[name63]) { ShaderStore.IncludesShadersStore[name63] = shader63; } bonesVertex = { name: name63, shader: shader63 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bakedVertexAnimation.js var name64, shader64, bakedVertexAnimation; var init_bakedVertexAnimation2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bakedVertexAnimation.js"() { init_shaderStore(); name64 = "bakedVertexAnimation"; shader64 = `#ifdef BAKED_VERTEX_ANIMATION_TEXTURE { #ifdef INSTANCES #define BVASNAME bakedVertexAnimationSettingsInstanced #else #define BVASNAME bakedVertexAnimationSettings #endif float VATStartFrame=BVASNAME.x;float VATEndFrame=BVASNAME.y;float VATOffsetFrame=BVASNAME.z;float VATSpeed=BVASNAME.w;float totalFrames=VATEndFrame-VATStartFrame+1.0;float time=bakedVertexAnimationTime*VATSpeed/totalFrames;float frameCorrection=time<1.0 ? 0.0 : 1.0;float numOfFrames=totalFrames-frameCorrection;float VATFrameNum=fract(time)*numOfFrames;VATFrameNum=mod(VATFrameNum+VATOffsetFrame,numOfFrames);VATFrameNum=floor(VATFrameNum);VATFrameNum+=VATStartFrame+frameCorrection;mat4 VATInfluence;VATInfluence=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[0],VATFrameNum)*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[1],VATFrameNum)*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[2],VATFrameNum)*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndices[3],VATFrameNum)*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[0],VATFrameNum)*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[1],VATFrameNum)*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[2],VATFrameNum)*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 VATInfluence+=readMatrixFromRawSamplerVAT(bakedVertexAnimationTexture,matricesIndicesExtra[3],VATFrameNum)*matricesWeightsExtra[3]; #endif finalWorld=finalWorld*VATInfluence;} #endif `; if (!ShaderStore.IncludesShadersStore[name64]) { ShaderStore.IncludesShadersStore[name64] = shader64; } bakedVertexAnimation = { name: name64, shader: shader64 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexNormalBias.js var name65, shader65, shadowMapVertexNormalBias; var init_shadowMapVertexNormalBias2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexNormalBias.js"() { init_shaderStore(); name65 = "shadowMapVertexNormalBias"; shader65 = `#if SM_NORMALBIAS==1 #if SM_DIRECTIONINLIGHTDATA==1 vec3 worldLightDirSM=normalize(-lightDataSM.xyz); #else vec3 directionToLightSM=lightDataSM.xyz-worldPos.xyz;vec3 worldLightDirSM=normalize(directionToLightSM); #endif float ndlSM=dot(vNormalW,worldLightDirSM);float sinNLSM=sqrt(1.0-ndlSM*ndlSM);float normalBiasSM=biasAndScaleSM.y*sinNLSM;worldPos.xyz-=vNormalW*normalBiasSM; #endif `; if (!ShaderStore.IncludesShadersStore[name65]) { ShaderStore.IncludesShadersStore[name65] = shader65; } shadowMapVertexNormalBias = { name: name65, shader: shader65 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexMetric.js var name66, shader66, shadowMapVertexMetric; var init_shadowMapVertexMetric2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapVertexMetric.js"() { init_shaderStore(); name66 = "shadowMapVertexMetric"; shader66 = `#if SM_USEDISTANCE==1 vPositionWSM=worldPos.xyz; #endif #if SM_DEPTHTEXTURE==1 #ifdef IS_NDC_HALF_ZRANGE #define BIASFACTOR 0.5 #else #define BIASFACTOR 1.0 #endif #ifdef USE_REVERSE_DEPTHBUFFER gl_Position.z-=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; #else gl_Position.z+=biasAndScaleSM.x*gl_Position.w*BIASFACTOR; #endif #endif #if defined(SM_DEPTHCLAMP) && SM_DEPTHCLAMP==1 zSM=gl_Position.z;gl_Position.z=0.0; #elif SM_USEDISTANCE==0 #ifdef USE_REVERSE_DEPTHBUFFER vDepthMetricSM=(-gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #else vDepthMetricSM=(gl_Position.z+depthValuesSM.x)/depthValuesSM.y+biasAndScaleSM.x; #endif #endif `; if (!ShaderStore.IncludesShadersStore[name66]) { ShaderStore.IncludesShadersStore[name66] = shader66; } shadowMapVertexMetric = { name: name66, shader: shader66 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertex.js var name67, shader67, clipPlaneVertex; var init_clipPlaneVertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertex.js"() { init_shaderStore(); name67 = "clipPlaneVertex"; shader67 = `#ifdef CLIPPLANE fClipDistance=dot(worldPos,vClipPlane); #endif #ifdef CLIPPLANE2 fClipDistance2=dot(worldPos,vClipPlane2); #endif #ifdef CLIPPLANE3 fClipDistance3=dot(worldPos,vClipPlane3); #endif #ifdef CLIPPLANE4 fClipDistance4=dot(worldPos,vClipPlane4); #endif #ifdef CLIPPLANE5 fClipDistance5=dot(worldPos,vClipPlane5); #endif #ifdef CLIPPLANE6 fClipDistance6=dot(worldPos,vClipPlane6); #endif `; if (!ShaderStore.IncludesShadersStore[name67]) { ShaderStore.IncludesShadersStore[name67] = shader67; } clipPlaneVertex = { name: name67, shader: shader67 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/shadowMap.vertex.js var shadowMap_vertex_exports2 = {}; __export(shadowMap_vertex_exports2, { shadowMapVertexShader: () => shadowMapVertexShader }); var name68, shader68, shadowMapVertexShader; var init_shadowMap_vertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/shadowMap.vertex.js"() { init_shaderStore(); init_bonesDeclaration2(); init_bakedVertexAnimationDeclaration2(); init_morphTargetsVertexGlobalDeclaration2(); init_morphTargetsVertexDeclaration2(); init_helperFunctions2(); init_shadowMapVertexDeclaration(); init_shadowMapUboDeclaration(); init_shadowMapVertexExtraDeclaration2(); init_clipPlaneVertexDeclaration2(); init_morphTargetsVertexGlobal2(); init_morphTargetsVertex2(); init_instancesVertex2(); init_bonesVertex2(); init_bakedVertexAnimation2(); init_shadowMapVertexNormalBias2(); init_shadowMapVertexMetric2(); init_clipPlaneVertex2(); name68 = "shadowMapVertexShader"; shader68 = `attribute vec3 position; #ifdef NORMAL attribute vec3 normal; #endif #include #include #include #include[0..maxSimultaneousMorphTargets] #ifdef INSTANCES attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; #endif #include #include<__decl__shadowMapVertex> #ifdef ALPHATEXTURE varying vec2 vUV;uniform mat4 diffuseMatrix; #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #endif #include #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position; #ifdef UV1 vec2 uvUpdated=uv; #endif #ifdef UV2 vec2 uv2Updated=uv2; #endif #ifdef NORMAL vec3 normalUpdated=normal; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); #ifdef NORMAL mat3 normWorldSM=mat3(finalWorld); #if defined(INSTANCES) && defined(THIN_INSTANCES) vec3 vNormalW=normalUpdated/vec3(dot(normWorldSM[0],normWorldSM[0]),dot(normWorldSM[1],normWorldSM[1]),dot(normWorldSM[2],normWorldSM[2]));vNormalW=normalize(normWorldSM*vNormalW); #else #ifdef NONUNIFORMSCALING normWorldSM=transposeMat3(inverseMat3(normWorldSM)); #endif vec3 vNormalW=normalize(normWorldSM*normalUpdated); #endif #endif #include gl_Position=viewProjection*worldPos; #include #ifdef ALPHATEXTURE #ifdef UV1 vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef UV2 vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0)); #endif #endif #include }`; if (!ShaderStore.ShadersStore[name68]) { ShaderStore.ShadersStore[name68] = shader68; } shadowMapVertexShader = { name: name68, shader: shader68 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/depthBoxBlur.fragment.js var depthBoxBlur_fragment_exports2 = {}; __export(depthBoxBlur_fragment_exports2, { depthBoxBlurPixelShader: () => depthBoxBlurPixelShader }); var name69, shader69, depthBoxBlurPixelShader; var init_depthBoxBlur_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/depthBoxBlur.fragment.js"() { init_shaderStore(); name69 = "depthBoxBlurPixelShader"; shader69 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 colorDepth=vec4(0.0);for (int x=-OFFSET; x<=OFFSET; x++) for (int y=-OFFSET; y<=OFFSET; y++) colorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);gl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));}`; if (!ShaderStore.ShadersStore[name69]) { ShaderStore.ShadersStore[name69] = shader69; } depthBoxBlurPixelShader = { name: name69, shader: shader69 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js var shadowMapFragmentSoftTransparentShadow_exports2 = {}; __export(shadowMapFragmentSoftTransparentShadow_exports2, { shadowMapFragmentSoftTransparentShadow: () => shadowMapFragmentSoftTransparentShadow }); var name70, shader70, shadowMapFragmentSoftTransparentShadow; var init_shadowMapFragmentSoftTransparentShadow2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowMapFragmentSoftTransparentShadow.js"() { init_shaderStore(); name70 = "shadowMapFragmentSoftTransparentShadow"; shader70 = `#if SM_SOFTTRANSPARENTSHADOW==1 if ((bayerDither8(floor(mod(gl_FragCoord.xy,8.0))))/64.0>=softTransparentShadowSM.x*alpha) discard; #endif `; if (!ShaderStore.IncludesShadersStore[name70]) { ShaderStore.IncludesShadersStore[name70] = shader70; } shadowMapFragmentSoftTransparentShadow = { name: name70, shader: shader70 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/node.js var _InternalNodeDataInfo, Node; var init_node = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/node.js"() { init_tslib_es6(); init_math_vector(); init_decorators(); init_observable(); init_engineStore(); init_devTools(); init_decorators_serialization(); _InternalNodeDataInfo = class { static { __name(this, "_InternalNodeDataInfo"); } constructor() { this._doNotSerialize = false; this._isDisposed = false; this._sceneRootNodesIndex = -1; this._isEnabled = true; this._isParentEnabled = true; this._isReady = true; this._onEnabledStateChangedObservable = new Observable(); this._onClonedObservable = new Observable(); this._inheritVisibility = false; this._isVisible = true; } }; Node = class _Node { static { __name(this, "Node"); } /** * Add a new node constructor * @param type defines the type name of the node to construct * @param constructorFunc defines the constructor function */ static AddNodeConstructor(type, constructorFunc) { this._NodeConstructors[type] = constructorFunc; } /** * Returns a node constructor based on type name * @param type defines the type name * @param name defines the new node name * @param scene defines the hosting scene * @param options defines optional options to transmit to constructors * @returns the new constructor or null */ static Construct(type, name260, scene, options) { const constructorFunc = this._NodeConstructors[type]; if (!constructorFunc) { return null; } return constructorFunc(name260, scene, options); } /** * Gets or sets the accessibility tag to describe the node for accessibility purpose. */ set accessibilityTag(value) { this._accessibilityTag = value; this.onAccessibilityTagChangedObservable.notifyObservers(value); } get accessibilityTag() { return this._accessibilityTag; } /** * Gets or sets a boolean used to define if the node must be serialized */ get doNotSerialize() { if (this._nodeDataStorage._doNotSerialize) { return true; } if (this._parentNode) { return this._parentNode.doNotSerialize; } return false; } set doNotSerialize(value) { this._nodeDataStorage._doNotSerialize = value; } /** * Gets a boolean indicating if the node has been disposed * @returns true if the node was disposed */ isDisposed() { return this._nodeDataStorage._isDisposed; } /** * Gets or sets the parent of the node (without keeping the current position in the scene) * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/parent */ set parent(parent) { if (this._parentNode === parent) { return; } const previousParentNode = this._parentNode; if (this._parentNode && this._parentNode._children !== void 0 && this._parentNode._children !== null) { const index = this._parentNode._children.indexOf(this); if (index !== -1) { this._parentNode._children.splice(index, 1); } if (!parent && !this._nodeDataStorage._isDisposed) { this._addToSceneRootNodes(); } } this._parentNode = parent; this._isDirty = true; if (this._parentNode) { if (this._parentNode._children === void 0 || this._parentNode._children === null) { this._parentNode._children = new Array(); } this._parentNode._children.push(this); if (!previousParentNode) { this._removeFromSceneRootNodes(); } } this._syncParentEnabledState(); } get parent() { return this._parentNode; } /** * If set to true, this node, when renderable, will only be visible if its parent(s) are also visible. * @default false */ get inheritVisibility() { return this._nodeDataStorage._inheritVisibility; } set inheritVisibility(value) { this._nodeDataStorage._inheritVisibility = value; } /** * Gets or sets a boolean indicating whether this node is visible, either this node itself when it is renderable or its renderable child nodes when `inheritVisibility` is true. * @default true */ get isVisible() { if (this.inheritVisibility && this._parentNode && !this._parentNode.isVisible) { return false; } return this._nodeDataStorage._isVisible; } set isVisible(value) { this._nodeDataStorage._isVisible = value; } /** * @internal */ _serializeAsParent(serializationObject) { serializationObject.parentId = this.uniqueId; } /** @internal */ _addToSceneRootNodes() { if (this._nodeDataStorage._sceneRootNodesIndex === -1) { this._nodeDataStorage._sceneRootNodesIndex = this._scene.rootNodes.length; this._scene.rootNodes.push(this); } } /** @internal */ _removeFromSceneRootNodes() { if (this._nodeDataStorage._sceneRootNodesIndex !== -1) { const rootNodes = this._scene.rootNodes; const lastIdx = rootNodes.length - 1; rootNodes[this._nodeDataStorage._sceneRootNodesIndex] = rootNodes[lastIdx]; rootNodes[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex = this._nodeDataStorage._sceneRootNodesIndex; this._scene.rootNodes.pop(); this._nodeDataStorage._sceneRootNodesIndex = -1; } } /** * Gets or sets the animation properties override */ get animationPropertiesOverride() { if (!this._animationPropertiesOverride) { return this._scene.animationPropertiesOverride; } return this._animationPropertiesOverride; } set animationPropertiesOverride(value) { this._animationPropertiesOverride = value; } /** * Gets a string identifying the name of the class * @returns "Node" string */ getClassName() { return "Node"; } /** * Sets a callback that will be raised when the node will be disposed */ set onDispose(callback) { if (this._onDisposeObserver) { this.onDisposeObservable.remove(this._onDisposeObserver); } this._onDisposeObserver = this.onDisposeObservable.add(callback); } /** * An event triggered when the enabled state of the node changes */ get onEnabledStateChangedObservable() { return this._nodeDataStorage._onEnabledStateChangedObservable; } /** * An event triggered when the node is cloned */ get onClonedObservable() { return this._nodeDataStorage._onClonedObservable; } /** * Creates a new Node * @param name the name and id to be given to this node * @param scene the scene this node will be added to * @param isPure indicates this Node is just a Node, and not a derived class like Mesh or Camera */ constructor(name260, scene = null, isPure = true) { this._isDirty = false; this._nodeDataStorage = new _InternalNodeDataInfo(); this.state = ""; this.metadata = null; this.reservedDataStore = null; this._accessibilityTag = null; this.onAccessibilityTagChangedObservable = new Observable(); this._parentContainer = null; this.animations = []; this._ranges = {}; this.onReady = null; this._currentRenderId = -1; this._parentUpdateId = -1; this._childUpdateId = -1; this._waitingParentId = null; this._waitingParentInstanceIndex = null; this._waitingParsedUniqueId = null; this._cache = {}; this._parentNode = null; this._children = null; this._worldMatrix = Matrix.Identity(); this._worldMatrixDeterminant = 0; this._worldMatrixDeterminantIsDirty = true; this._animationPropertiesOverride = null; this._isNode = true; this.onDisposeObservable = new Observable(); this._onDisposeObserver = null; this._behaviors = new Array(); this.name = name260; this.id = name260; this._scene = scene || EngineStore.LastCreatedScene; this.uniqueId = this._scene.getUniqueId(); this._initCache(); if (isPure) { this._addToSceneRootNodes(); } } /** * Gets the scene of the node * @returns a scene */ getScene() { return this._scene; } /** * Gets the engine of the node * @returns a Engine */ getEngine() { return this._scene.getEngine(); } /** * Attach a behavior to the node * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors * @param behavior defines the behavior to attach * @param attachImmediately defines that the behavior must be attached even if the scene is still loading * @returns the current Node */ addBehavior(behavior, attachImmediately = false) { const index = this._behaviors.indexOf(behavior); if (index !== -1) { return this; } behavior.init(); if (this._scene.isLoading && !attachImmediately) { this._scene.onDataLoadedObservable.addOnce(() => { if (this._behaviors.includes(behavior)) { behavior.attach(this); } }); } else { behavior.attach(this); } this._behaviors.push(behavior); return this; } /** * Remove an attached behavior * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors * @param behavior defines the behavior to attach * @returns the current Node */ removeBehavior(behavior) { const index = this._behaviors.indexOf(behavior); if (index === -1) { return this; } this._behaviors[index].detach(); this._behaviors.splice(index, 1); return this; } /** * Gets the list of attached behaviors * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors */ get behaviors() { return this._behaviors; } /** * Gets an attached behavior by name * @param name defines the name of the behavior to look for * @see https://doc.babylonjs.com/features/featuresDeepDive/behaviors * @returns null if behavior was not found else the requested behavior */ getBehaviorByName(name260) { for (const behavior of this._behaviors) { if (behavior.name === name260) { return behavior; } } return null; } /** * Returns the latest update of the World matrix * @returns a Matrix */ getWorldMatrix() { if (this._currentRenderId !== this._scene.getRenderId()) { this.computeWorldMatrix(); } return this._worldMatrix; } /** @internal */ _getWorldMatrixDeterminant() { if (this._worldMatrixDeterminantIsDirty) { this._worldMatrixDeterminantIsDirty = false; this._worldMatrixDeterminant = this._worldMatrix.determinant(); } return this._worldMatrixDeterminant; } /** * Returns directly the latest state of the mesh World matrix. * A Matrix is returned. */ get worldMatrixFromCache() { return this._worldMatrix; } // override it in derived class if you add new variables to the cache // and call the parent class method /** @internal */ _initCache() { this._cache = {}; } /** * @internal */ updateCache(force) { if (!force && this.isSynchronized()) { return; } this._updateCache(); } /** * @internal */ _getActionManagerForTrigger(trigger, _initialCall = true) { if (!this.parent) { return null; } return this.parent._getActionManagerForTrigger(trigger, false); } // override it in derived class if you add new variables to the cache // and call the parent class method if !ignoreParentClass /** * @internal */ _updateCache(_ignoreParentClass) { } // override it in derived class if you add new variables to the cache /** @internal */ _isSynchronized() { return true; } /** @internal */ _markSyncedWithParent() { if (this._parentNode) { this._parentUpdateId = this._parentNode._childUpdateId; } } /** @internal */ isSynchronizedWithParent() { if (!this._parentNode) { return true; } if (this._parentNode._isDirty || this._parentUpdateId !== this._parentNode._childUpdateId) { return false; } return this._parentNode.isSynchronized(); } /** @internal */ isSynchronized() { if (this._parentNode && !this.isSynchronizedWithParent()) { return false; } return this._isSynchronized(); } /** * Is this node ready to be used/rendered * @param _completeCheck defines if a complete check (including materials and lights) has to be done (false by default) * @returns true if the node is ready */ isReady(_completeCheck = false) { return this._nodeDataStorage._isReady; } /** * Flag the node as dirty (Forcing it to update everything) * @param _property helps children apply precise "dirtyfication" * @returns this node */ markAsDirty(_property) { this._currentRenderId = Number.MAX_VALUE; this._isDirty = true; return this; } /** * Is this node enabled? * If the node has a parent, all ancestors will be checked and false will be returned if any are false (not enabled), otherwise will return true * @param checkAncestors indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors * @returns whether this node (and its parent) is enabled */ isEnabled(checkAncestors = true) { if (checkAncestors === false) { return this._nodeDataStorage._isEnabled; } if (!this._nodeDataStorage._isEnabled) { return false; } return this._nodeDataStorage._isParentEnabled; } /** @internal */ _syncParentEnabledState() { this._nodeDataStorage._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true; if (this._children) { for (const c of this._children) { c._syncParentEnabledState(); } } } /** * Set the enabled state of this node * @param value defines the new enabled state */ setEnabled(value) { if (this._nodeDataStorage._isEnabled === value) { return; } this._nodeDataStorage._isEnabled = value; this._syncParentEnabledState(); this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(value); } /** * Is this node a descendant of the given node? * The function will iterate up the hierarchy until the ancestor was found or no more parents defined * @param ancestor defines the parent node to inspect * @returns a boolean indicating if this node is a descendant of the given node */ isDescendantOf(ancestor) { if (this.parent) { if (this.parent === ancestor) { return true; } return this.parent.isDescendantOf(ancestor); } return false; } /** * @internal */ _getDescendants(results, directDescendantsOnly = false, predicate) { if (!this._children) { return; } for (let index = 0; index < this._children.length; index++) { const item = this._children[index]; if (!predicate || predicate(item)) { results.push(item); } if (!directDescendantsOnly) { item._getDescendants(results, false, predicate); } } } /** * Will return all nodes that have this node as ascendant * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored * @returns all children nodes of all types */ getDescendants(directDescendantsOnly, predicate) { const results = []; this._getDescendants(results, directDescendantsOnly, predicate); return results; } /** * Get all child-meshes of this node * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered (Default: false) * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored * @returns an array of AbstractMesh */ getChildMeshes(directDescendantsOnly, predicate) { const results = []; this._getDescendants(results, directDescendantsOnly, (node) => { return (!predicate || predicate(node)) && node.cullingStrategy !== void 0; }); return results; } /** * Get all direct children of this node * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered (Default: true) * @returns an array of Node */ getChildren(predicate, directDescendantsOnly = true) { return this.getDescendants(directDescendantsOnly, predicate); } /** * @internal */ _setReady(state) { if (state === this._nodeDataStorage._isReady) { return; } if (!state) { this._nodeDataStorage._isReady = false; return; } if (this.onReady) { this.onReady(this); } this._nodeDataStorage._isReady = true; } /** * Get an animation by name * @param name defines the name of the animation to look for * @returns null if not found else the requested animation */ getAnimationByName(name260) { for (let i = 0; i < this.animations.length; i++) { const animation = this.animations[i]; if (animation.name === name260) { return animation; } } return null; } /** * Creates an animation range for this node * @param name defines the name of the range * @param from defines the starting key * @param to defines the end key */ createAnimationRange(name260, from, to) { if (!this._ranges[name260]) { this._ranges[name260] = _Node._AnimationRangeFactory(name260, from, to); for (let i = 0, nAnimations = this.animations.length; i < nAnimations; i++) { if (this.animations[i]) { this.animations[i].createRange(name260, from, to); } } } } /** * Delete a specific animation range * @param name defines the name of the range to delete * @param deleteFrames defines if animation frames from the range must be deleted as well */ deleteAnimationRange(name260, deleteFrames = true) { for (let i = 0, nAnimations = this.animations.length; i < nAnimations; i++) { if (this.animations[i]) { this.animations[i].deleteRange(name260, deleteFrames); } } this._ranges[name260] = null; } /** * Get an animation range by name * @param name defines the name of the animation range to look for * @returns null if not found else the requested animation range */ getAnimationRange(name260) { return this._ranges[name260] || null; } /** * Clone the current node * @param name Name of the new clone * @param newParent New parent for the clone * @param doNotCloneChildren Do not clone children hierarchy * @returns the new transform node */ clone(name260, newParent, doNotCloneChildren) { const result = SerializationHelper.Clone(() => new _Node(name260, this.getScene()), this); if (newParent) { result.parent = newParent; } if (!doNotCloneChildren) { const directDescendants = this.getDescendants(true); for (let index = 0; index < directDescendants.length; index++) { const child = directDescendants[index]; child.clone(name260 + "." + child.name, result); } } return result; } /** * Gets the list of all animation ranges defined on this node * @returns an array */ getAnimationRanges() { const animationRanges = []; let name260; for (name260 in this._ranges) { animationRanges.push(this._ranges[name260]); } return animationRanges; } /** * Will start the animation sequence * @param name defines the range frames for animation sequence * @param loop defines if the animation should loop (false by default) * @param speedRatio defines the speed factor in which to run the animation (1 by default) * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default) * @returns the object created for this animation. If range does not exist, it will return null */ beginAnimation(name260, loop, speedRatio, onAnimationEnd) { const range = this.getAnimationRange(name260); if (!range) { return null; } return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd); } /** * Serialize animation ranges into a JSON compatible object * @returns serialization object */ serializeAnimationRanges() { const serializationRanges = []; for (const name260 in this._ranges) { const localRange = this._ranges[name260]; if (!localRange) { continue; } const range = {}; range.name = name260; range.from = localRange.from; range.to = localRange.to; serializationRanges.push(range); } return serializationRanges; } /** * 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 */ computeWorldMatrix(_force) { if (!this._worldMatrix) { this._worldMatrix = Matrix.Identity(); } return this._worldMatrix; } /** * 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) */ dispose(doNotRecurse, disposeMaterialAndTextures = false) { this._nodeDataStorage._isDisposed = true; if (!doNotRecurse) { const nodes = this.getDescendants(true); for (const node of nodes) { node.dispose(doNotRecurse, disposeMaterialAndTextures); } } if (!this.parent) { this._removeFromSceneRootNodes(); } else { this.parent = null; } this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); this.onEnabledStateChangedObservable.clear(); this.onClonedObservable.clear(); for (const behavior of this._behaviors) { behavior.detach(); } this._behaviors.length = 0; this.metadata = null; } /** * Parse animation range data from a serialization object and store them into a given node * @param node defines where to store the animation ranges * @param parsedNode defines the serialization object to read data from * @param _scene defines the hosting scene */ static ParseAnimationRanges(node, parsedNode, _scene) { if (parsedNode.ranges) { for (let index = 0; index < parsedNode.ranges.length; index++) { const data = parsedNode.ranges[index]; node.createAnimationRange(data.name, data.from, data.to); } } } /** * Return the minimum and maximum world vectors of the entire hierarchy under current node * @param includeDescendants Include bounding info from descendants as well (true by default) * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors * @returns the new bounding vectors */ getHierarchyBoundingVectors(includeDescendants = true, predicate = null) { this.getScene().incrementRenderId(); this.computeWorldMatrix(true); let min; let max; const thisAbstractMesh = this; if (thisAbstractMesh.getBoundingInfo && thisAbstractMesh.subMeshes) { const boundingInfo = thisAbstractMesh.getBoundingInfo(); min = boundingInfo.boundingBox.minimumWorld.clone(); max = boundingInfo.boundingBox.maximumWorld.clone(); } else { min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); } if (includeDescendants) { const descendants = this.getDescendants(false); for (const descendant of descendants) { const childMesh = descendant; childMesh.computeWorldMatrix(true); if (predicate && !predicate(childMesh)) { continue; } if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) { continue; } const childBoundingInfo = childMesh.getBoundingInfo(); const boundingBox = childBoundingInfo.boundingBox; const minBox = boundingBox.minimumWorld; const maxBox = boundingBox.maximumWorld; Vector3.CheckExtends(minBox, min, max); Vector3.CheckExtends(maxBox, min, max); } } return { min, max }; } }; Node._AnimationRangeFactory = (_name, _from, _to) => { throw _WarnImport("AnimationRange"); }; Node._NodeConstructors = {}; __decorate([ serialize() ], Node.prototype, "name", void 0); __decorate([ serialize() ], Node.prototype, "id", void 0); __decorate([ serialize() ], Node.prototype, "uniqueId", void 0); __decorate([ serialize() ], Node.prototype, "state", void 0); __decorate([ serialize() ], Node.prototype, "metadata", void 0); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/light.js var Light; var init_light = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/light.js"() { init_tslib_es6(); init_decorators(); init_math_vector(); init_math_color(); init_node(); init_uniformBuffer(); init_typeStore(); init_lightConstants(); init_decorators_serialization(); Light = class _Light extends Node { static { __name(this, "Light"); } /** * 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 range() { 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 range(value) { this._range = value; this._inverseSquaredRange = 1 / (this.range * this.range); } /** * 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 intensityMode() { 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 intensityMode(value) { this._intensityMode = value; this._computePhotometricScale(); } /** * Gets the light radius used by PBR Materials to simulate soft area lights. */ get radius() { return this._radius; } /** * sets the light radius used by PBR Materials to simulate soft area lights. */ set radius(value) { this._radius = value; this._computePhotometricScale(); } /** * Gets whether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching * the current shadow generator. */ get shadowEnabled() { return this._shadowEnabled; } /** * Sets whether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching * the current shadow generator. */ set shadowEnabled(value) { if (this._shadowEnabled === value) { return; } this._shadowEnabled = value; this._markMeshesAsLightDirty(); } /** * Gets the only meshes impacted by this light. */ get includedOnlyMeshes() { return this._includedOnlyMeshes; } /** * Sets the only meshes impacted by this light. */ set includedOnlyMeshes(value) { this._includedOnlyMeshes = value; this._hookArrayForIncludedOnly(value); } /** * Gets the meshes not impacted by this light. */ get excludedMeshes() { return this._excludedMeshes; } /** * Sets the meshes not impacted by this light. */ set excludedMeshes(value) { this._excludedMeshes = value; this._hookArrayForExcluded(value); } /** * Gets the layer id use to find what meshes are not impacted by the light. * Inactive if 0 */ get excludeWithLayerMask() { return this._excludeWithLayerMask; } /** * Sets the layer id use to find what meshes are not impacted by the light. * Inactive if 0 */ set excludeWithLayerMask(value) { this._excludeWithLayerMask = value; this._resyncMeshes(); } /** * Gets the layer id use to find what meshes are impacted by the light. * Inactive if 0 */ get includeOnlyWithLayerMask() { return this._includeOnlyWithLayerMask; } /** * Sets the layer id use to find what meshes are impacted by the light. * Inactive if 0 */ set includeOnlyWithLayerMask(value) { this._includeOnlyWithLayerMask = value; this._resyncMeshes(); } /** * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) */ get lightmapMode() { return this._lightmapMode; } /** * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x) */ set lightmapMode(value) { if (this._lightmapMode === value) { return; } this._lightmapMode = value; this._markMeshesAsLightDirty(); } /** * Returns the view matrix. * @param _faceIndex The index of the face for which we want to extract the view matrix. Only used for point light types. * @returns The view matrix. Can be null, if a view matrix cannot be defined for the type of light considered (as for a hemispherical light, for example). */ getViewMatrix(_faceIndex) { return null; } /** * Returns the projection matrix. * Note that viewMatrix and renderList are optional and are only used by lights that calculate the projection matrix from a list of meshes (e.g. directional lights with automatic extents calculation). * @param _viewMatrix The view transform matrix of the light (optional). * @param _renderList The list of meshes to take into account when calculating the projection matrix (optional). * @returns The projection matrix. Can be null, if a projection matrix cannot be defined for the type of light considered (as for a hemispherical light, for example). */ getProjectionMatrix(_viewMatrix, _renderList) { return null; } /** * Creates a Light object in the scene. * Documentation : https://doc.babylonjs.com/features/featuresDeepDive/lights/lights_introduction * @param name The friendly name of the light * @param scene The scene the light belongs too */ constructor(name260, scene) { super(name260, scene, false); this.diffuse = new Color3(1, 1, 1); this.specular = new Color3(1, 1, 1); this.falloffType = _Light.FALLOFF_DEFAULT; this.intensity = 1; this._range = Number.MAX_VALUE; this._inverseSquaredRange = 0; this._photometricScale = 1; this._intensityMode = _Light.INTENSITYMODE_AUTOMATIC; this._radius = 1e-5; this.renderPriority = 0; this._shadowEnabled = true; this._excludeWithLayerMask = 0; this._includeOnlyWithLayerMask = 0; this._lightmapMode = 0; this._shadowGenerators = null; this._excludedMeshesIds = new Array(); this._includedOnlyMeshesIds = new Array(); this._currentViewDepth = 0; this._isLight = true; this.getScene().addLight(this); this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), void 0, void 0, name260); this._buildUniformLayout(); this.includedOnlyMeshes = []; this.excludedMeshes = []; this._resyncMeshes(); } /** * 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 */ // eslint-disable-next-line @typescript-eslint/no-unused-vars transferTexturesToEffect(effect, lightIndex) { 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 receiveShadows Defines if the effect (mesh) we bind the light for receives shadows */ _bindLight(lightIndex, scene, effect, useSpecular, receiveShadows = true) { const iAsString = lightIndex.toString(); let needUpdate = false; this._uniformBuffer.bindToEffect(effect, "Light" + iAsString); if (this._renderId !== scene.getRenderId() || this._lastUseSpecular !== useSpecular || !this._uniformBuffer.useUbo) { this._renderId = scene.getRenderId(); this._lastUseSpecular = useSpecular; const scaledIntensity = this.getScaledIntensity(); this.transferToEffect(effect, iAsString); this.diffuse.scaleToRef(scaledIntensity, TmpColors.Color3[0]); this._uniformBuffer.updateColor4("vLightDiffuse", TmpColors.Color3[0], this.range, iAsString); if (useSpecular) { this.specular.scaleToRef(scaledIntensity, TmpColors.Color3[1]); this._uniformBuffer.updateColor4("vLightSpecular", TmpColors.Color3[1], this.radius, iAsString); } needUpdate = true; } this.transferTexturesToEffect(effect, iAsString); if (scene.shadowsEnabled && this.shadowEnabled && receiveShadows) { const shadowGenerator = this.getShadowGenerator(scene.activeCamera) ?? this.getShadowGenerator(); if (shadowGenerator) { shadowGenerator.bindShadowLight(iAsString, effect); needUpdate = true; } } if (needUpdate) { this._uniformBuffer.update(); } else { this._uniformBuffer.bindUniformBuffer(); } } /** * Returns the string "Light". * @returns the class name */ getClassName() { 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 */ toString(fullDetails) { let ret = "Name: " + this.name; ret += ", type: " + ["Point", "Directional", "Spot", "Hemispheric", "Clustered"][this.getTypeID()]; if (this.animations) { for (let i = 0; i < this.animations.length; i++) { ret += ", animation[0]: " + this.animations[i].toString(fullDetails); } } return ret; } /** @internal */ _syncParentEnabledState() { super._syncParentEnabledState(); if (!this.isDisposed()) { this._resyncMeshes(); } } /** * Set the enabled state of this node. * @param value - the new enabled state */ setEnabled(value) { super.setEnabled(value); this._resyncMeshes(); } /** * Returns the Light associated shadow generator if any. * @param camera Camera for which the shadow generator should be retrieved (default: null). If null, retrieves the default shadow generator * @returns the associated shadow generator. */ getShadowGenerator(camera = null) { if (this._shadowGenerators === null) { return null; } return this._shadowGenerators.get(camera) ?? null; } /** * Returns all the shadow generators associated to this light * @returns */ getShadowGenerators() { return this._shadowGenerators; } /** * Returns a Vector3, the absolute light position in the World. * @returns the world space position of the light */ getAbsolutePosition() { return Vector3.Zero(); } /** * Specifies if the light will affect the passed mesh. * @param mesh The mesh to test against the light * @returns true the mesh is affected otherwise, false. */ canAffectMesh(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; } /** * 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) */ dispose(doNotRecurse, disposeMaterialAndTextures = false) { if (this._shadowGenerators) { const iterator = this._shadowGenerators.values(); for (let key = iterator.next(); key.done !== true; key = iterator.next()) { const shadowGenerator = key.value; shadowGenerator.dispose(); } this._shadowGenerators = null; } this.getScene().stopAnimation(this); if (this._parentContainer) { const index = this._parentContainer.lights.indexOf(this); if (index > -1) { this._parentContainer.lights.splice(index, 1); } this._parentContainer = null; } for (const mesh of this.getScene().meshes) { mesh._removeLightSource(this, true); } this._uniformBuffer.dispose(); this.getScene().removeLight(this); super.dispose(doNotRecurse, disposeMaterialAndTextures); } /** * Returns the light type ID (integer). * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x */ // eslint-disable-next-line @typescript-eslint/naming-convention getTypeID() { 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 */ getScaledIntensity() { 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 */ clone(name260, newParent = null) { const constructor = _Light.GetConstructorFromName(this.getTypeID(), name260, this.getScene()); if (!constructor) { return null; } const clonedLight = SerializationHelper.Clone(constructor, this); if (name260) { clonedLight.name = name260; } if (newParent) { clonedLight.parent = newParent; } clonedLight.setEnabled(this.isEnabled()); this.onClonedObservable.notifyObservers(clonedLight); return clonedLight; } /** * Serializes the current light into a Serialization object. * @returns the serialized object. */ serialize() { const serializationObject = SerializationHelper.Serialize(this); serializationObject.uniqueId = this.uniqueId; serializationObject.type = this.getTypeID(); if (this.parent) { this.parent._serializeAsParent(serializationObject); } if (this.excludedMeshes.length > 0) { serializationObject.excludedMeshesIds = []; for (const mesh of this.excludedMeshes) { serializationObject.excludedMeshesIds.push(mesh.id); } } if (this.includedOnlyMeshes.length > 0) { serializationObject.includedOnlyMeshesIds = []; for (const mesh of this.includedOnlyMeshes) { serializationObject.includedOnlyMeshesIds.push(mesh.id); } } SerializationHelper.AppendSerializedAnimations(this, serializationObject); serializationObject.ranges = this.serializeAnimationRanges(); serializationObject.isEnabled = this.isEnabled(); 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 */ static GetConstructorFromName(type, name260, scene) { const constructorFunc = Node.Construct("Light_Type_" + type, name260, scene); if (constructorFunc) { return constructorFunc; } 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 */ static Parse(parsedLight, scene) { const constructor = _Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene); if (!constructor) { return null; } const light = SerializationHelper.Parse(constructor, parsedLight, scene); if (parsedLight.excludedMeshesIds) { light._excludedMeshesIds = parsedLight.excludedMeshesIds; } if (parsedLight.includedOnlyMeshesIds) { light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds; } if (parsedLight.parentId !== void 0) { light._waitingParentId = parsedLight.parentId; } if (parsedLight.parentInstanceIndex !== void 0) { light._waitingParentInstanceIndex = parsedLight.parentInstanceIndex; } if (parsedLight.falloffType !== void 0) { light.falloffType = parsedLight.falloffType; } if (parsedLight.lightmapMode !== void 0) { light.lightmapMode = parsedLight.lightmapMode; } if (parsedLight.animations) { for (let animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) { const parsedAnimation = parsedLight.animations[animationIndex]; const internalClass = GetClass("BABYLON.Animation"); if (internalClass) { light.animations.push(internalClass.Parse(parsedAnimation)); } } Node.ParseAnimationRanges(light, parsedLight, scene); } if (parsedLight.autoAnimate) { scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1); } if (parsedLight.isEnabled !== void 0) { light.setEnabled(parsedLight.isEnabled); } return light; } _hookArrayForExcluded(array) { const oldPush = array.push; array.push = (...items) => { const result = oldPush.apply(array, items); for (const item of items) { item._resyncLightSource(this); } return result; }; const oldSplice = array.splice; array.splice = (index, deleteCount) => { const deleted = oldSplice.apply(array, [index, deleteCount]); for (const item of deleted) { item._resyncLightSource(this); } return deleted; }; for (const item of array) { item._resyncLightSource(this); } } _hookArrayForIncludedOnly(array) { const oldPush = array.push; array.push = (...items) => { const result = oldPush.apply(array, items); this._resyncMeshes(); return result; }; const oldSplice = array.splice; array.splice = (index, deleteCount) => { const deleted = oldSplice.apply(array, [index, deleteCount]); this._resyncMeshes(); return deleted; }; this._resyncMeshes(); } _resyncMeshes() { for (const mesh of this.getScene().meshes) { mesh._resyncLightSource(this); } } /** * Forces the meshes to update their light related information in their rendering used effects * @internal Internal Use Only */ _markMeshesAsLightDirty() { for (const mesh of this.getScene().meshes) { if (mesh.lightSources.indexOf(this) !== -1) { mesh._markSubMeshesAsLightDirty(); } } } /** * Recomputes the cached photometric scale if needed. */ _computePhotometricScale() { this._photometricScale = this._getPhotometricScale(); this.getScene().resetCachedMaterial(); } /** * @returns the Photometric Scale according to the light type and intensity mode. */ _getPhotometricScale() { let photometricScale = 0; const lightTypeID = this.getTypeID(); let photometricMode = this.intensityMode; if (photometricMode === _Light.INTENSITYMODE_AUTOMATIC) { if (lightTypeID === _Light.LIGHTTYPEID_DIRECTIONALLIGHT) { photometricMode = _Light.INTENSITYMODE_ILLUMINANCE; } else { photometricMode = _Light.INTENSITYMODE_LUMINOUSINTENSITY; } } switch (lightTypeID) { case _Light.LIGHTTYPEID_POINTLIGHT: case _Light.LIGHTTYPEID_SPOTLIGHT: switch (photometricMode) { case _Light.INTENSITYMODE_LUMINOUSPOWER: photometricScale = 1 / (4 * Math.PI); break; case _Light.INTENSITYMODE_LUMINOUSINTENSITY: photometricScale = 1; break; case _Light.INTENSITYMODE_LUMINANCE: photometricScale = this.radius * this.radius; break; } break; case _Light.LIGHTTYPEID_DIRECTIONALLIGHT: switch (photometricMode) { case _Light.INTENSITYMODE_ILLUMINANCE: photometricScale = 1; break; case _Light.INTENSITYMODE_LUMINANCE: { let apexAngleRadians = this.radius; apexAngleRadians = Math.max(apexAngleRadians, 1e-3); const solidAngle = 2 * Math.PI * (1 - Math.cos(apexAngleRadians)); photometricScale = solidAngle; break; } } break; case _Light.LIGHTTYPEID_HEMISPHERICLIGHT: photometricScale = 1; break; } return photometricScale; } /** * Reorder the light in the scene according to their defined priority. * @internal Internal Use Only */ _reorderLightsInScene() { const scene = this.getScene(); if (this._renderPriority != 0) { scene.requireLightSorting = true; } this.getScene().sortLightsByPriority(); } /** * @internal */ _isReady() { return true; } }; Light.FALLOFF_DEFAULT = LightConstants.FALLOFF_DEFAULT; Light.FALLOFF_PHYSICAL = LightConstants.FALLOFF_PHYSICAL; Light.FALLOFF_GLTF = LightConstants.FALLOFF_GLTF; Light.FALLOFF_STANDARD = LightConstants.FALLOFF_STANDARD; Light.LIGHTMAP_DEFAULT = LightConstants.LIGHTMAP_DEFAULT; Light.LIGHTMAP_SPECULAR = LightConstants.LIGHTMAP_SPECULAR; Light.LIGHTMAP_SHADOWSONLY = LightConstants.LIGHTMAP_SHADOWSONLY; Light.INTENSITYMODE_AUTOMATIC = LightConstants.INTENSITYMODE_AUTOMATIC; Light.INTENSITYMODE_LUMINOUSPOWER = LightConstants.INTENSITYMODE_LUMINOUSPOWER; Light.INTENSITYMODE_LUMINOUSINTENSITY = LightConstants.INTENSITYMODE_LUMINOUSINTENSITY; Light.INTENSITYMODE_ILLUMINANCE = LightConstants.INTENSITYMODE_ILLUMINANCE; Light.INTENSITYMODE_LUMINANCE = LightConstants.INTENSITYMODE_LUMINANCE; Light.LIGHTTYPEID_POINTLIGHT = LightConstants.LIGHTTYPEID_POINTLIGHT; Light.LIGHTTYPEID_DIRECTIONALLIGHT = LightConstants.LIGHTTYPEID_DIRECTIONALLIGHT; Light.LIGHTTYPEID_SPOTLIGHT = LightConstants.LIGHTTYPEID_SPOTLIGHT; Light.LIGHTTYPEID_HEMISPHERICLIGHT = LightConstants.LIGHTTYPEID_HEMISPHERICLIGHT; Light.LIGHTTYPEID_RECT_AREALIGHT = LightConstants.LIGHTTYPEID_RECT_AREALIGHT; __decorate([ serializeAsColor3() ], Light.prototype, "diffuse", void 0); __decorate([ serializeAsColor3() ], Light.prototype, "specular", void 0); __decorate([ serialize() ], Light.prototype, "falloffType", void 0); __decorate([ serialize() ], Light.prototype, "intensity", void 0); __decorate([ serialize() ], Light.prototype, "range", null); __decorate([ serialize() ], Light.prototype, "intensityMode", null); __decorate([ serialize() ], Light.prototype, "radius", null); __decorate([ serialize() ], Light.prototype, "_renderPriority", void 0); __decorate([ expandToProperty("_reorderLightsInScene") ], Light.prototype, "renderPriority", void 0); __decorate([ serialize("shadowEnabled") ], Light.prototype, "_shadowEnabled", void 0); __decorate([ serialize("excludeWithLayerMask") ], Light.prototype, "_excludeWithLayerMask", void 0); __decorate([ serialize("includeOnlyWithLayerMask") ], Light.prototype, "_includeOnlyWithLayerMask", void 0); __decorate([ serialize("lightmapMode") ], Light.prototype, "_lightmapMode", void 0); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurVaryingDeclaration.js var name71, shader71, kernelBlurVaryingDeclarationWGSL; var init_kernelBlurVaryingDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurVaryingDeclaration.js"() { init_shaderStore(); name71 = "kernelBlurVaryingDeclaration"; shader71 = `varying sampleCoord{X}: vec2f;`; if (!ShaderStore.IncludesShadersStoreWGSL[name71]) { ShaderStore.IncludesShadersStoreWGSL[name71] = shader71; } kernelBlurVaryingDeclarationWGSL = { name: name71, shader: shader71 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurFragment.js var name72, shader72, kernelBlurFragmentWGSL; var init_kernelBlurFragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurFragment.js"() { init_shaderStore(); name72 = "kernelBlurFragment"; shader72 = `#ifdef DOF factor=sampleCoC(fragmentInputs.sampleCoord{X}); computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; #else computedWeight=KERNEL_WEIGHT{X}; #endif #ifdef PACKEDFLOAT blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X}))*computedWeight; #else blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCoord{X})*computedWeight; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name72]) { ShaderStore.IncludesShadersStoreWGSL[name72] = shader72; } kernelBlurFragmentWGSL = { name: name72, shader: shader72 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurFragment2.js var name73, shader73, kernelBlurFragment2WGSL; var init_kernelBlurFragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurFragment2.js"() { init_shaderStore(); name73 = "kernelBlurFragment2"; shader73 = `#ifdef DOF factor=sampleCoC(fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; #else computedWeight=KERNEL_DEP_WEIGHT{X}; #endif #ifdef PACKEDFLOAT blend+=unpack(textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X}))*computedWeight; #else blend+=textureSample(textureSampler,textureSamplerSampler,fragmentInputs.sampleCenter+uniforms.delta*KERNEL_DEP_OFFSET{X})*computedWeight; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name73]) { ShaderStore.IncludesShadersStoreWGSL[name73] = shader73; } kernelBlurFragment2WGSL = { name: name73, shader: shader73 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/kernelBlur.fragment.js var kernelBlur_fragment_exports = {}; __export(kernelBlur_fragment_exports, { kernelBlurPixelShaderWGSL: () => kernelBlurPixelShaderWGSL }); var name74, shader74, kernelBlurPixelShaderWGSL; var init_kernelBlur_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/kernelBlur.fragment.js"() { init_shaderStore(); init_kernelBlurVaryingDeclaration(); init_packingFunctions(); init_kernelBlurFragment(); init_kernelBlurFragment2(); name74 = "kernelBlurPixelShader"; shader74 = `var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform delta: vec2f;varying sampleCenter: vec2f; #ifdef DOF var circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d;fn sampleCoC(offset: vec2f)->f32 {var coc: f32=textureSample(circleOfConfusionSampler,circleOfConfusionSamplerSampler,offset).r;return coc; } #endif #include[0..varyingCount] #ifdef PACKEDFLOAT #include #endif #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var computedWeight: f32=0.0; #ifdef PACKEDFLOAT var blend: f32=0.; #else var blend: vec4f= vec4f(0.); #endif #ifdef DOF var sumOfWeights: f32=CENTER_WEIGHT; var factor: f32=0.0; #ifdef PACKEDFLOAT blend+=unpack(textureSample(textureSampler,textureSamplerSampler,input.sampleCenter))*CENTER_WEIGHT; #else blend+=textureSample(textureSampler,textureSamplerSampler,input.sampleCenter)*CENTER_WEIGHT; #endif #endif #include[0..varyingCount] #include[0..depCount] #ifdef PACKEDFLOAT fragmentOutputs.color=pack(blend); #else fragmentOutputs.color=blend; #endif #ifdef DOF fragmentOutputs.color/=sumOfWeights; #endif }`; if (!ShaderStore.ShadersStoreWGSL[name74]) { ShaderStore.ShadersStoreWGSL[name74] = shader74; } kernelBlurPixelShaderWGSL = { name: name74, shader: shader74 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurVertex.js var name75, shader75, kernelBlurVertexWGSL; var init_kernelBlurVertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/kernelBlurVertex.js"() { init_shaderStore(); name75 = "kernelBlurVertex"; shader75 = `vertexOutputs.sampleCoord{X}=vertexOutputs.sampleCenter+uniforms.delta*KERNEL_OFFSET{X};`; if (!ShaderStore.IncludesShadersStoreWGSL[name75]) { ShaderStore.IncludesShadersStoreWGSL[name75] = shader75; } kernelBlurVertexWGSL = { name: name75, shader: shader75 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/kernelBlur.vertex.js var kernelBlur_vertex_exports = {}; __export(kernelBlur_vertex_exports, { kernelBlurVertexShaderWGSL: () => kernelBlurVertexShaderWGSL }); var name76, shader76, kernelBlurVertexShaderWGSL; var init_kernelBlur_vertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/kernelBlur.vertex.js"() { init_shaderStore(); init_kernelBlurVaryingDeclaration(); init_kernelBlurVertex(); name76 = "kernelBlurVertexShader"; shader76 = `attribute position: vec2f;uniform delta: vec2f;varying sampleCenter: vec2f; #include[0..varyingCount] #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5); #define CUSTOM_VERTEX_MAIN_BEGIN vertexOutputs.sampleCenter=(input.position*madd+madd); #include[0..varyingCount] vertexOutputs.position= vec4f(input.position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`; if (!ShaderStore.ShadersStoreWGSL[name76]) { ShaderStore.ShadersStoreWGSL[name76] = shader76; } kernelBlurVertexShaderWGSL = { name: name76, shader: shader76 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurVaryingDeclaration.js var name77, shader77, kernelBlurVaryingDeclaration; var init_kernelBlurVaryingDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurVaryingDeclaration.js"() { init_shaderStore(); name77 = "kernelBlurVaryingDeclaration"; shader77 = `varying vec2 sampleCoord{X};`; if (!ShaderStore.IncludesShadersStore[name77]) { ShaderStore.IncludesShadersStore[name77] = shader77; } kernelBlurVaryingDeclaration = { name: name77, shader: shader77 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurFragment.js var name78, shader78, kernelBlurFragment; var init_kernelBlurFragment3 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurFragment.js"() { init_shaderStore(); name78 = "kernelBlurFragment"; shader78 = `#ifdef DOF factor=sampleCoC(sampleCoord{X}); computedWeight=KERNEL_WEIGHT{X}*factor;sumOfWeights+=computedWeight; #else computedWeight=KERNEL_WEIGHT{X}; #endif #ifdef PACKEDFLOAT blend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight; #else blend+=texture2D(textureSampler,sampleCoord{X})*computedWeight; #endif `; if (!ShaderStore.IncludesShadersStore[name78]) { ShaderStore.IncludesShadersStore[name78] = shader78; } kernelBlurFragment = { name: name78, shader: shader78 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurFragment2.js var name79, shader79, kernelBlurFragment2; var init_kernelBlurFragment22 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurFragment2.js"() { init_shaderStore(); name79 = "kernelBlurFragment2"; shader79 = `#ifdef DOF factor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});computedWeight=KERNEL_DEP_WEIGHT{X}*factor;sumOfWeights+=computedWeight; #else computedWeight=KERNEL_DEP_WEIGHT{X}; #endif #ifdef PACKEDFLOAT blend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight; #else blend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight; #endif `; if (!ShaderStore.IncludesShadersStore[name79]) { ShaderStore.IncludesShadersStore[name79] = shader79; } kernelBlurFragment2 = { name: name79, shader: shader79 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/kernelBlur.fragment.js var kernelBlur_fragment_exports2 = {}; __export(kernelBlur_fragment_exports2, { kernelBlurPixelShader: () => kernelBlurPixelShader }); var name80, shader80, kernelBlurPixelShader; var init_kernelBlur_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/kernelBlur.fragment.js"() { init_shaderStore(); init_kernelBlurVaryingDeclaration2(); init_packingFunctions2(); init_kernelBlurFragment3(); init_kernelBlurFragment22(); name80 = "kernelBlurPixelShader"; shader80 = `uniform sampler2D textureSampler;uniform vec2 delta;varying vec2 sampleCenter; #ifdef DOF uniform sampler2D circleOfConfusionSampler;float sampleCoC(in vec2 offset) {float coc=texture2D(circleOfConfusionSampler,offset).r;return coc; } #endif #include[0..varyingCount] #ifdef PACKEDFLOAT #include #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {float computedWeight=0.0; #ifdef PACKEDFLOAT float blend=0.; #else vec4 blend=vec4(0.); #endif #ifdef DOF float sumOfWeights=CENTER_WEIGHT; float factor=0.0; #ifdef PACKEDFLOAT blend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT; #else blend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT; #endif #endif #include[0..varyingCount] #include[0..depCount] #ifdef PACKEDFLOAT gl_FragColor=pack(blend); #else gl_FragColor=blend; #endif #ifdef DOF gl_FragColor/=sumOfWeights; #endif }`; if (!ShaderStore.ShadersStore[name80]) { ShaderStore.ShadersStore[name80] = shader80; } kernelBlurPixelShader = { name: name80, shader: shader80 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurVertex.js var name81, shader81, kernelBlurVertex; var init_kernelBlurVertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/kernelBlurVertex.js"() { init_shaderStore(); name81 = "kernelBlurVertex"; shader81 = `sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};`; if (!ShaderStore.IncludesShadersStore[name81]) { ShaderStore.IncludesShadersStore[name81] = shader81; } kernelBlurVertex = { name: name81, shader: shader81 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/kernelBlur.vertex.js var kernelBlur_vertex_exports2 = {}; __export(kernelBlur_vertex_exports2, { kernelBlurVertexShader: () => kernelBlurVertexShader }); var name82, shader82, kernelBlurVertexShader; var init_kernelBlur_vertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/kernelBlur.vertex.js"() { init_shaderStore(); init_kernelBlurVaryingDeclaration2(); init_kernelBlurVertex2(); name82 = "kernelBlurVertexShader"; shader82 = `attribute vec2 position;uniform vec2 delta;varying vec2 sampleCenter; #include[0..varyingCount] const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN sampleCenter=(position*madd+madd); #include[0..varyingCount] gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`; if (!ShaderStore.ShadersStore[name82]) { ShaderStore.ShadersStore[name82] = shader82; } kernelBlurVertexShader = { name: name82, shader: shader82 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinBlurPostProcess.js var ThinBlurPostProcess; var init_thinBlurPostProcess = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinBlurPostProcess.js"() { init_effectRenderer(); init_engine(); ThinBlurPostProcess = class _ThinBlurPostProcess extends EffectWrapper { static { __name(this, "ThinBlurPostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.all([Promise.resolve().then(() => (init_kernelBlur_fragment(), kernelBlur_fragment_exports)), Promise.resolve().then(() => (init_kernelBlur_vertex(), kernelBlur_vertex_exports))])); } else { list.push(Promise.all([Promise.resolve().then(() => (init_kernelBlur_fragment2(), kernelBlur_fragment_exports2)), Promise.resolve().then(() => (init_kernelBlur_vertex2(), kernelBlur_vertex_exports2))])); } } /** * Constructs a new blur post process * @param name Name of the effect * @param engine Engine to use to render the effect. If not provided, the last created engine will be used * @param direction Direction in which to apply the blur * @param kernel Kernel size of the blur * @param options Options to configure the effect */ constructor(name260, engine = null, direction, kernel, options) { const blockCompilationFinal = !!options?.blockCompilation; super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinBlurPostProcess.FragmentUrl, uniforms: _ThinBlurPostProcess.Uniforms, samplers: _ThinBlurPostProcess.Samplers, vertexUrl: _ThinBlurPostProcess.VertexUrl, blockCompilation: true }); this._packedFloat = false; this._staticDefines = ""; this.textureWidth = 0; this.textureHeight = 0; this._staticDefines = options ? Array.isArray(options.defines) ? options.defines.join("\n") : options.defines || "" : ""; this.options.blockCompilation = blockCompilationFinal; if (direction !== void 0) { this.direction = direction; } if (kernel !== void 0) { this.kernel = kernel; } } /** * Sets the length in pixels of the blur sample region */ set kernel(v) { if (this._idealKernel === v) { return; } v = Math.max(v, 1); this._idealKernel = v; this._kernel = this._nearestBestKernel(v); if (!this.options.blockCompilation) { this._updateParameters(); } } /** * Gets the length in pixels of the blur sample region */ get kernel() { return this._idealKernel; } /** * Sets whether or not the blur needs to unpack/repack floats */ set packedFloat(v) { if (this._packedFloat === v) { return; } this._packedFloat = v; if (!this.options.blockCompilation) { this._updateParameters(); } } /** * Gets whether or not the blur is unpacking/repacking floats */ get packedFloat() { return this._packedFloat; } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); this._drawWrapper.effect.setFloat2("delta", 1 / this.textureWidth * this.direction.x, 1 / this.textureHeight * this.direction.y); } /** @internal */ _updateParameters(onCompiled, onError) { const n = this._kernel; const centerIndex = (n - 1) / 2; let offsets = []; let weights = []; let totalWeight = 0; for (let i = 0; i < n; i++) { const u = i / (n - 1); const w = this._gaussianWeight(u * 2 - 1); offsets[i] = i - centerIndex; weights[i] = w; totalWeight += w; } for (let i = 0; i < weights.length; i++) { weights[i] /= totalWeight; } const linearSamplingWeights = []; const linearSamplingOffsets = []; const linearSamplingMap = []; for (let i = 0; i <= centerIndex; i += 2) { const j = Math.min(i + 1, Math.floor(centerIndex)); const singleCenterSample = i === j; if (singleCenterSample) { linearSamplingMap.push({ o: offsets[i], w: weights[i] }); } else { const sharedCell = j === centerIndex; const weightLinear = weights[i] + weights[j] * (sharedCell ? 0.5 : 1); const offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]); if (offsetLinear === 0) { linearSamplingMap.push({ o: offsets[i], w: weights[i] }); linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] }); } else { linearSamplingMap.push({ o: offsetLinear, w: weightLinear }); linearSamplingMap.push({ o: -offsetLinear, w: weightLinear }); } } } for (let i = 0; i < linearSamplingMap.length; i++) { linearSamplingOffsets[i] = linearSamplingMap[i].o; linearSamplingWeights[i] = linearSamplingMap[i].w; } offsets = linearSamplingOffsets; weights = linearSamplingWeights; const maxVaryingRows = this.options.engine.getCaps().maxVaryingVectors - (this.options.shaderLanguage === 1 ? 1 : 0); const freeVaryingVec2 = Math.max(maxVaryingRows, 0) - 1; let varyingCount = Math.min(offsets.length, freeVaryingVec2); let defines = ""; defines += this._staticDefines; if (this._staticDefines.indexOf("DOF") != -1) { defines += `#define CENTER_WEIGHT ${this._glslFloat(weights[varyingCount - 1])} `; varyingCount--; } for (let i = 0; i < varyingCount; i++) { defines += `#define KERNEL_OFFSET${i} ${this._glslFloat(offsets[i])} `; defines += `#define KERNEL_WEIGHT${i} ${this._glslFloat(weights[i])} `; } let depCount = 0; for (let i = freeVaryingVec2; i < offsets.length; i++) { defines += `#define KERNEL_DEP_OFFSET${depCount} ${this._glslFloat(offsets[i])} `; defines += `#define KERNEL_DEP_WEIGHT${depCount} ${this._glslFloat(weights[i])} `; depCount++; } if (this.packedFloat) { defines += `#define PACKEDFLOAT 1`; } this.options.blockCompilation = false; this.updateEffect(defines, null, null, { varyingCount, depCount }, onCompiled, onError); } /** * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard. * The gaps between physical kernels are compensated for in the weighting of the samples * @param idealKernel Ideal blur kernel. * @returns Nearest best kernel. */ _nearestBestKernel(idealKernel) { const v = Math.round(idealKernel); for (const k of [v, v - 1, v + 1, v - 2, v + 2]) { if (k % 2 !== 0 && Math.floor(k / 2) % 2 === 0 && k > 0) { return Math.max(k, 3); } } return Math.max(v, 3); } /** * Calculates the value of a Gaussian distribution with sigma 3 at a given point. * @param x The point on the Gaussian distribution to sample. * @returns the value of the Gaussian function at x. */ _gaussianWeight(x) { const sigma = 1 / 3; const denominator = Math.sqrt(2 * Math.PI) * sigma; const exponent = -(x * x / (2 * sigma * sigma)); const weight = 1 / denominator * Math.exp(exponent); return weight; } /** * Generates a string that can be used as a floating point number in GLSL. * @param x Value to print. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s). * @returns GLSL float string. */ _glslFloat(x, decimalFigures = 8) { return x.toFixed(decimalFigures).replace(/0+$/, ""); } }; ThinBlurPostProcess.VertexUrl = "kernelBlur"; ThinBlurPostProcess.FragmentUrl = "kernelBlur"; ThinBlurPostProcess.Uniforms = ["delta", "direction"]; ThinBlurPostProcess.Samplers = ["circleOfConfusionSampler"]; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/blurPostProcess.js var BlurPostProcess; var init_blurPostProcess = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/blurPostProcess.js"() { init_tslib_es6(); init_postProcess(); init_texture(); init_typeStore(); init_decorators(); init_decorators_serialization(); init_thinBlurPostProcess(); BlurPostProcess = class _BlurPostProcess extends PostProcess { static { __name(this, "BlurPostProcess"); } /** The direction in which to blur the image. */ get direction() { return this._effectWrapper.direction; } set direction(value) { this._effectWrapper.direction = value; } /** * Sets the length in pixels of the blur sample region */ set kernel(v) { this._effectWrapper.kernel = v; } /** * Gets the length in pixels of the blur sample region */ get kernel() { return this._effectWrapper.kernel; } /** * Sets whether or not the blur needs to unpack/repack floats */ set packedFloat(v) { this._effectWrapper.packedFloat = v; } /** * Gets whether or not the blur is unpacking/repacking floats */ get packedFloat() { return this._effectWrapper.packedFloat; } /** * Gets a string identifying the name of the class * @returns "BlurPostProcess" string */ getClassName() { return "BlurPostProcess"; } /** * Creates a new instance BlurPostProcess * @param name The name of the effect. * @param direction The direction in which to blur the image. * @param kernel The size of the kernel to be used when computing the blur. eg. Size of 3 will blur the center pixel by 2 pixels surrounding it. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size) * @param camera The camera to apply the render pass to. * @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 defines * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA) */ constructor(name260, direction, kernel, options, camera = null, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = 0, defines = "", blockCompilation = false, textureFormat = 5) { const blockCompilationFinal = typeof options === "number" ? blockCompilation : !!options.blockCompilation; const localOptions = { uniforms: ThinBlurPostProcess.Uniforms, samplers: ThinBlurPostProcess.Samplers, size: typeof options === "number" ? options : void 0, camera, samplingMode, engine, reusable, textureType, vertexUrl: ThinBlurPostProcess.VertexUrl, indexParameters: { varyingCount: 0, depCount: 0 }, textureFormat, defines, ...options, blockCompilation: true }; super(name260, ThinBlurPostProcess.FragmentUrl, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinBlurPostProcess(name260, engine, void 0, void 0, localOptions) : void 0, ...localOptions }); this._effectWrapper.options.blockCompilation = blockCompilationFinal; this.direction = direction; this.onApplyObservable.add(() => { this._effectWrapper.textureWidth = this._outputTexture ? this._outputTexture.width : this.width; this._effectWrapper.textureHeight = this._outputTexture ? this._outputTexture.height : this.height; }); this.kernel = kernel; } updateEffect(_defines = null, _uniforms = null, _samplers = null, _indexParameters, onCompiled, onError) { this._effectWrapper._updateParameters(onCompiled, onError); } /** * @internal */ static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { return SerializationHelper.Parse(() => { return new _BlurPostProcess(parsedPostProcess.name, parsedPostProcess.direction, parsedPostProcess.kernel, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, void 0, false); }, parsedPostProcess, scene, rootUrl); } }; __decorate([ serializeAsVector2() ], BlurPostProcess.prototype, "direction", null); __decorate([ serialize() ], BlurPostProcess.prototype, "kernel", null); __decorate([ serialize() ], BlurPostProcess.prototype, "packedFloat", null); RegisterClass("BABYLON.BlurPostProcess", BlurPostProcess); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effectFallbacks.js var EffectFallbacks; var init_effectFallbacks = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/effectFallbacks.js"() { EffectFallbacks = class { static { __name(this, "EffectFallbacks"); } constructor() { this._defines = {}; this._currentRank = 32; this._maxRank = -1; this._mesh = null; } /** * Removes the fallback from the bound mesh. */ unBindMesh() { this._mesh = null; } /** * Adds a fallback on the specified property. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first) * @param define The name of the define in the shader */ addFallback(rank, define) { if (!this._defines[rank]) { if (rank < this._currentRank) { this._currentRank = rank; } if (rank > this._maxRank) { this._maxRank = rank; } this._defines[rank] = new Array(); } this._defines[rank].push(define); } /** * Sets the mesh to use CPU skinning when needing to fallback. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first) * @param mesh The mesh to use the fallbacks. */ addCPUSkinningFallback(rank, mesh) { this._mesh = mesh; if (rank < this._currentRank) { this._currentRank = rank; } if (rank > this._maxRank) { this._maxRank = rank; } } /** * Checks to see if more fallbacks are still available. */ get hasMoreFallbacks() { return this._currentRank <= this._maxRank; } /** * Removes the defines that should be removed when falling back. * @param currentDefines defines the current define statements for the shader. * @param effect defines the current effect we try to compile * @returns The resulting defines with defines of the current rank removed. */ reduce(currentDefines, effect) { if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) { this._mesh.computeBonesUsingShaders = false; currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0"); effect._bonesComputationForcedToCPU = true; const scene = this._mesh.getScene(); for (let index = 0; index < scene.meshes.length; index++) { const otherMesh = scene.meshes[index]; if (!otherMesh.material) { if (!this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) { otherMesh.computeBonesUsingShaders = false; } continue; } if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) { continue; } if (otherMesh.material.getEffect() === effect) { otherMesh.computeBonesUsingShaders = false; } else if (otherMesh.subMeshes) { for (const subMesh of otherMesh.subMeshes) { const subMeshEffect = subMesh.effect; if (subMeshEffect === effect) { otherMesh.computeBonesUsingShaders = false; break; } } } } } else { const currentFallbacks = this._defines[this._currentRank]; if (currentFallbacks) { for (let index = 0; index < currentFallbacks.length; index++) { currentDefines = currentDefines.replace("#define " + currentFallbacks[index], ""); } } this._currentRank++; } return currentDefines; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/clipPlaneMaterialHelper.js function AddClipPlaneUniforms(uniforms) { if (uniforms.indexOf("vClipPlane") === -1) { uniforms.push("vClipPlane"); } if (uniforms.indexOf("vClipPlane2") === -1) { uniforms.push("vClipPlane2"); } if (uniforms.indexOf("vClipPlane3") === -1) { uniforms.push("vClipPlane3"); } if (uniforms.indexOf("vClipPlane4") === -1) { uniforms.push("vClipPlane4"); } if (uniforms.indexOf("vClipPlane5") === -1) { uniforms.push("vClipPlane5"); } if (uniforms.indexOf("vClipPlane6") === -1) { uniforms.push("vClipPlane6"); } } function PrepareStringDefinesForClipPlanes(primaryHolder, secondaryHolder, defines) { const clipPlane = !!(primaryHolder.clipPlane ?? secondaryHolder.clipPlane); const clipPlane2 = !!(primaryHolder.clipPlane2 ?? secondaryHolder.clipPlane2); const clipPlane3 = !!(primaryHolder.clipPlane3 ?? secondaryHolder.clipPlane3); const clipPlane4 = !!(primaryHolder.clipPlane4 ?? secondaryHolder.clipPlane4); const clipPlane5 = !!(primaryHolder.clipPlane5 ?? secondaryHolder.clipPlane5); const clipPlane6 = !!(primaryHolder.clipPlane6 ?? secondaryHolder.clipPlane6); if (clipPlane) { defines.push("#define CLIPPLANE"); } if (clipPlane2) { defines.push("#define CLIPPLANE2"); } if (clipPlane3) { defines.push("#define CLIPPLANE3"); } if (clipPlane4) { defines.push("#define CLIPPLANE4"); } if (clipPlane5) { defines.push("#define CLIPPLANE5"); } if (clipPlane6) { defines.push("#define CLIPPLANE6"); } } function PrepareDefinesForClipPlanes(primaryHolder, secondaryHolder, defines) { let changed = false; const clipPlane = !!(primaryHolder.clipPlane ?? secondaryHolder.clipPlane); const clipPlane2 = !!(primaryHolder.clipPlane2 ?? secondaryHolder.clipPlane2); const clipPlane3 = !!(primaryHolder.clipPlane3 ?? secondaryHolder.clipPlane3); const clipPlane4 = !!(primaryHolder.clipPlane4 ?? secondaryHolder.clipPlane4); const clipPlane5 = !!(primaryHolder.clipPlane5 ?? secondaryHolder.clipPlane5); const clipPlane6 = !!(primaryHolder.clipPlane6 ?? secondaryHolder.clipPlane6); if (defines["CLIPPLANE"] !== clipPlane) { defines["CLIPPLANE"] = clipPlane; changed = true; } if (defines["CLIPPLANE2"] !== clipPlane2) { defines["CLIPPLANE2"] = clipPlane2; changed = true; } if (defines["CLIPPLANE3"] !== clipPlane3) { defines["CLIPPLANE3"] = clipPlane3; changed = true; } if (defines["CLIPPLANE4"] !== clipPlane4) { defines["CLIPPLANE4"] = clipPlane4; changed = true; } if (defines["CLIPPLANE5"] !== clipPlane5) { defines["CLIPPLANE5"] = clipPlane5; changed = true; } if (defines["CLIPPLANE6"] !== clipPlane6) { defines["CLIPPLANE6"] = clipPlane6; changed = true; } return changed; } function BindClipPlane(effect, primaryHolder, secondaryHolder) { let clipPlane = primaryHolder.clipPlane ?? secondaryHolder.clipPlane; SetClipPlane(effect, "vClipPlane", clipPlane); clipPlane = primaryHolder.clipPlane2 ?? secondaryHolder.clipPlane2; SetClipPlane(effect, "vClipPlane2", clipPlane); clipPlane = primaryHolder.clipPlane3 ?? secondaryHolder.clipPlane3; SetClipPlane(effect, "vClipPlane3", clipPlane); clipPlane = primaryHolder.clipPlane4 ?? secondaryHolder.clipPlane4; SetClipPlane(effect, "vClipPlane4", clipPlane); clipPlane = primaryHolder.clipPlane5 ?? secondaryHolder.clipPlane5; SetClipPlane(effect, "vClipPlane5", clipPlane); clipPlane = primaryHolder.clipPlane6 ?? secondaryHolder.clipPlane6; SetClipPlane(effect, "vClipPlane6", clipPlane); } function SetClipPlane(effect, uniformName, clipPlane) { if (clipPlane) { effect.setFloat4(uniformName, clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d); } } var init_clipPlaneMaterialHelper = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/clipPlaneMaterialHelper.js"() { __name(AddClipPlaneUniforms, "AddClipPlaneUniforms"); __name(PrepareStringDefinesForClipPlanes, "PrepareStringDefinesForClipPlanes"); __name(PrepareDefinesForClipPlanes, "PrepareDefinesForClipPlanes"); __name(BindClipPlane, "BindClipPlane"); __name(SetClipPlane, "SetClipPlane"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialFlags.js var MaterialFlags; var init_materialFlags = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialFlags.js"() { init_abstractEngine(); MaterialFlags = class { static { __name(this, "MaterialFlags"); } /** * Are diffuse textures enabled in the application. */ static get DiffuseTextureEnabled() { return this._DiffuseTextureEnabled; } static set DiffuseTextureEnabled(value) { if (this._DiffuseTextureEnabled === value) { return; } this._DiffuseTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Is the OpenPBR Base Weight texture enabled in the application. */ static get BaseWeightTextureEnabled() { return this._BaseWeightTextureEnabled; } static set BaseWeightTextureEnabled(value) { if (this._BaseWeightTextureEnabled === value) { return; } this._BaseWeightTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Is the OpenPBR Base Diffuse Roughness texture enabled in the application. */ static get BaseDiffuseRoughnessTextureEnabled() { return this._BaseDiffuseRoughnessTextureEnabled; } static set BaseDiffuseRoughnessTextureEnabled(value) { if (this._BaseDiffuseRoughnessTextureEnabled === value) { return; } this._BaseDiffuseRoughnessTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are detail textures enabled in the application. */ static get DetailTextureEnabled() { return this._DetailTextureEnabled; } static set DetailTextureEnabled(value) { if (this._DetailTextureEnabled === value) { return; } this._DetailTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are decal maps enabled in the application. */ static get DecalMapEnabled() { return this._DecalMapEnabled; } static set DecalMapEnabled(value) { if (this._DecalMapEnabled === value) { return; } this._DecalMapEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are ambient textures enabled in the application. */ static get AmbientTextureEnabled() { return this._AmbientTextureEnabled; } static set AmbientTextureEnabled(value) { if (this._AmbientTextureEnabled === value) { return; } this._AmbientTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are opacity textures enabled in the application. */ static get OpacityTextureEnabled() { return this._OpacityTextureEnabled; } static set OpacityTextureEnabled(value) { if (this._OpacityTextureEnabled === value) { return; } this._OpacityTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are reflection textures enabled in the application. */ static get ReflectionTextureEnabled() { return this._ReflectionTextureEnabled; } static set ReflectionTextureEnabled(value) { if (this._ReflectionTextureEnabled === value) { return; } this._ReflectionTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are emissive textures enabled in the application. */ static get EmissiveTextureEnabled() { return this._EmissiveTextureEnabled; } static set EmissiveTextureEnabled(value) { if (this._EmissiveTextureEnabled === value) { return; } this._EmissiveTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are specular textures enabled in the application. */ static get SpecularTextureEnabled() { return this._SpecularTextureEnabled; } static set SpecularTextureEnabled(value) { if (this._SpecularTextureEnabled === value) { return; } this._SpecularTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are bump textures enabled in the application. */ static get BumpTextureEnabled() { return this._BumpTextureEnabled; } static set BumpTextureEnabled(value) { if (this._BumpTextureEnabled === value) { return; } this._BumpTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are lightmap textures enabled in the application. */ static get LightmapTextureEnabled() { return this._LightmapTextureEnabled; } static set LightmapTextureEnabled(value) { if (this._LightmapTextureEnabled === value) { return; } this._LightmapTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are refraction textures enabled in the application. */ static get RefractionTextureEnabled() { return this._RefractionTextureEnabled; } static set RefractionTextureEnabled(value) { if (this._RefractionTextureEnabled === value) { return; } this._RefractionTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are color grading textures enabled in the application. */ static get ColorGradingTextureEnabled() { return this._ColorGradingTextureEnabled; } static set ColorGradingTextureEnabled(value) { if (this._ColorGradingTextureEnabled === value) { return; } this._ColorGradingTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are fresnels enabled in the application. */ static get FresnelEnabled() { return this._FresnelEnabled; } static set FresnelEnabled(value) { if (this._FresnelEnabled === value) { return; } this._FresnelEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(4); } /** * Are clear coat textures enabled in the application. */ static get ClearCoatTextureEnabled() { return this._ClearCoatTextureEnabled; } static set ClearCoatTextureEnabled(value) { if (this._ClearCoatTextureEnabled === value) { return; } this._ClearCoatTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are clear coat bump textures enabled in the application. */ static get ClearCoatBumpTextureEnabled() { return this._ClearCoatBumpTextureEnabled; } static set ClearCoatBumpTextureEnabled(value) { if (this._ClearCoatBumpTextureEnabled === value) { return; } this._ClearCoatBumpTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are clear coat tint textures enabled in the application. */ static get ClearCoatTintTextureEnabled() { return this._ClearCoatTintTextureEnabled; } static set ClearCoatTintTextureEnabled(value) { if (this._ClearCoatTintTextureEnabled === value) { return; } this._ClearCoatTintTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are sheen textures enabled in the application. */ static get SheenTextureEnabled() { return this._SheenTextureEnabled; } static set SheenTextureEnabled(value) { if (this._SheenTextureEnabled === value) { return; } this._SheenTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are anisotropic textures enabled in the application. */ static get AnisotropicTextureEnabled() { return this._AnisotropicTextureEnabled; } static set AnisotropicTextureEnabled(value) { if (this._AnisotropicTextureEnabled === value) { return; } this._AnisotropicTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are thickness textures enabled in the application. */ static get ThicknessTextureEnabled() { return this._ThicknessTextureEnabled; } static set ThicknessTextureEnabled(value) { if (this._ThicknessTextureEnabled === value) { return; } this._ThicknessTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are refraction intensity textures enabled in the application. */ static get RefractionIntensityTextureEnabled() { return this._ThicknessTextureEnabled; } static set RefractionIntensityTextureEnabled(value) { if (this._RefractionIntensityTextureEnabled === value) { return; } this._RefractionIntensityTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are translucency intensity textures enabled in the application. */ static get TranslucencyIntensityTextureEnabled() { return this._TranslucencyIntensityTextureEnabled; } static set TranslucencyIntensityTextureEnabled(value) { if (this._TranslucencyIntensityTextureEnabled === value) { return; } this._TranslucencyIntensityTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are translucency tint textures enabled in the application. */ static get TranslucencyColorTextureEnabled() { return this._TranslucencyColorTextureEnabled; } static set TranslucencyColorTextureEnabled(value) { if (this._TranslucencyColorTextureEnabled === value) { return; } this._TranslucencyColorTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } /** * Are translucency intensity textures enabled in the application. */ static get IridescenceTextureEnabled() { return this._IridescenceTextureEnabled; } static set IridescenceTextureEnabled(value) { if (this._IridescenceTextureEnabled === value) { return; } this._IridescenceTextureEnabled = value; AbstractEngine.MarkAllMaterialsAsDirty(1); } }; MaterialFlags._DiffuseTextureEnabled = true; MaterialFlags._BaseWeightTextureEnabled = true; MaterialFlags._BaseDiffuseRoughnessTextureEnabled = true; MaterialFlags._DetailTextureEnabled = true; MaterialFlags._DecalMapEnabled = true; MaterialFlags._AmbientTextureEnabled = true; MaterialFlags._OpacityTextureEnabled = true; MaterialFlags._ReflectionTextureEnabled = true; MaterialFlags._EmissiveTextureEnabled = true; MaterialFlags._SpecularTextureEnabled = true; MaterialFlags._BumpTextureEnabled = true; MaterialFlags._LightmapTextureEnabled = true; MaterialFlags._RefractionTextureEnabled = true; MaterialFlags._ColorGradingTextureEnabled = true; MaterialFlags._FresnelEnabled = true; MaterialFlags._ClearCoatTextureEnabled = true; MaterialFlags._ClearCoatBumpTextureEnabled = true; MaterialFlags._ClearCoatTintTextureEnabled = true; MaterialFlags._SheenTextureEnabled = true; MaterialFlags._AnisotropicTextureEnabled = true; MaterialFlags._ThicknessTextureEnabled = true; MaterialFlags._RefractionIntensityTextureEnabled = true; MaterialFlags._TranslucencyIntensityTextureEnabled = true; MaterialFlags._TranslucencyColorTextureEnabled = true; MaterialFlags._IridescenceTextureEnabled = true; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialHelper.functions.pure.js function BindLogDepth(defines, effect, scene) { if (!defines || defines["LOGARITHMICDEPTH"] || defines.indexOf && defines.indexOf("LOGARITHMICDEPTH") >= 0) { const camera = scene.activeCamera; if (camera.mode === 1) { Logger.Error("Logarithmic depth is not compatible with orthographic cameras!", 20); } effect.setFloat("logarithmicDepthConstant", 2 / (Math.log(camera.maxZ + 1) / Math.LN2)); } } var init_materialHelper_functions_pure = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialHelper.functions.pure.js"() { init_logger(); __name(BindLogDepth, "BindLogDepth"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialHelper.functions.js function BindFogParameters(scene, mesh, effect, linearSpace = false) { if (effect && scene.fogEnabled && (!mesh || mesh.applyFog) && scene.fogMode !== 0) { effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity); if (linearSpace) { scene.fogColor.toLinearSpaceToRef(TempFogColor, scene.getEngine().useExactSrgbConversions); effect.setColor3("vFogColor", TempFogColor); } else { effect.setColor3("vFogColor", scene.fogColor); } } } function PrepareDefinesAndAttributesForMorphTargets(morphTargetManager, defines, attribs, mesh, usePositionMorph, useNormalMorph, useTangentMorph, useUVMorph, useUV2Morph, useColorMorph) { const numMorphInfluencers = morphTargetManager.numMaxInfluencers || morphTargetManager.numInfluencers; if (numMorphInfluencers <= 0) { return 0; } defines.push("#define MORPHTARGETS"); if (morphTargetManager.hasPositions) { defines.push("#define MORPHTARGETTEXTURE_HASPOSITIONS"); } if (morphTargetManager.hasNormals) { defines.push("#define MORPHTARGETTEXTURE_HASNORMALS"); } if (morphTargetManager.hasTangents) { defines.push("#define MORPHTARGETTEXTURE_HASTANGENTS"); } if (morphTargetManager.hasUVs) { defines.push("#define MORPHTARGETTEXTURE_HASUVS"); } if (morphTargetManager.hasUV2s) { defines.push("#define MORPHTARGETTEXTURE_HASUV2S"); } if (morphTargetManager.hasColors) { defines.push("#define MORPHTARGETTEXTURE_HASCOLORS"); } if (morphTargetManager.supportsPositions && usePositionMorph) { defines.push("#define MORPHTARGETS_POSITION"); } if (morphTargetManager.supportsNormals && useNormalMorph) { defines.push("#define MORPHTARGETS_NORMAL"); } if (morphTargetManager.supportsTangents && useTangentMorph) { defines.push("#define MORPHTARGETS_TANGENT"); } if (morphTargetManager.supportsUVs && useUVMorph) { defines.push("#define MORPHTARGETS_UV"); } if (morphTargetManager.supportsUV2s && useUV2Morph) { defines.push("#define MORPHTARGETS_UV2"); } if (morphTargetManager.supportsColors && useColorMorph) { defines.push("#define MORPHTARGETS_COLOR"); } defines.push("#define NUM_MORPH_INFLUENCERS " + numMorphInfluencers); if (morphTargetManager.isUsingTextureForTargets) { defines.push("#define MORPHTARGETS_TEXTURE"); } TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = numMorphInfluencers; TmpMorphInfluencers.NORMAL = useNormalMorph; TmpMorphInfluencers.TANGENT = useTangentMorph; TmpMorphInfluencers.UV = useUVMorph; TmpMorphInfluencers.UV2 = useUV2Morph; TmpMorphInfluencers.COLOR = useColorMorph; PrepareAttributesForMorphTargets(attribs, mesh, TmpMorphInfluencers, usePositionMorph); return numMorphInfluencers; } function PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, influencers) { TmpMorphInfluencers.NUM_MORPH_INFLUENCERS = influencers; TmpMorphInfluencers.NORMAL = false; TmpMorphInfluencers.TANGENT = false; TmpMorphInfluencers.UV = false; TmpMorphInfluencers.UV2 = false; TmpMorphInfluencers.COLOR = false; PrepareAttributesForMorphTargets(attribs, mesh, TmpMorphInfluencers, true); } function PrepareAttributesForMorphTargets(attribs, mesh, defines, usePositionMorph = true) { const influencers = defines["NUM_MORPH_INFLUENCERS"]; if (influencers > 0 && EngineStore.LastCreatedEngine) { const maxAttributesCount = EngineStore.LastCreatedEngine.getCaps().maxVertexAttribs; const manager = mesh.morphTargetManager; if (manager?.isUsingTextureForTargets) { return; } const position = manager && manager.supportsPositions && usePositionMorph; const normal = manager && manager.supportsNormals && defines["NORMAL"]; const tangent = manager && manager.supportsTangents && defines["TANGENT"]; const uv = manager && manager.supportsUVs && defines["UV1"]; const uv2 = manager && manager.supportsUV2s && defines["UV2"]; const color = manager && manager.supportsColors && defines["VERTEXCOLOR"]; for (let index = 0; index < influencers; index++) { if (position) { attribs.push(`position` + index); } if (normal) { attribs.push(`normal` + index); } if (tangent) { attribs.push(`tangent` + index); } if (uv) { attribs.push(`uv_` + index); } if (uv2) { attribs.push(`uv2_` + index); } if (color) { attribs.push(`color` + index); } if (attribs.length > maxAttributesCount) { Logger.Error("Cannot add more vertex attributes for mesh " + mesh.name); } } } } function PushAttributesForInstances(attribs, needsPreviousMatrices = false) { attribs.push("world0"); attribs.push("world1"); attribs.push("world2"); attribs.push("world3"); if (needsPreviousMatrices) { attribs.push("previousWorld0"); attribs.push("previousWorld1"); attribs.push("previousWorld2"); attribs.push("previousWorld3"); } } function BindMorphTargetParameters(abstractMesh, effect) { const manager = abstractMesh.morphTargetManager; if (!abstractMesh || !manager) { return; } effect.setFloatArray("morphTargetInfluences", manager.influences); } function BindSceneUniformBuffer(effect, sceneUbo) { sceneUbo.bindToEffect(effect, "Scene"); } function BindIBLParameters(scene, defines, ubo, reflectionColor, reflectionTexture = null, realTimeFiltering = false, supportTextureInfo = false, supportLocalProjection = false, usePBR = false, supportSH = false, useColor = false, reflectionBlur = 0) { if (scene.texturesEnabled) { if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { ubo.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix()); ubo.updateFloat2("vReflectionInfos", reflectionTexture.level * scene.iblIntensity, reflectionBlur); if (supportLocalProjection && reflectionTexture.boundingBoxSize) { const cubeTexture = reflectionTexture; ubo.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition); ubo.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize); } if (realTimeFiltering) { const width = reflectionTexture.getSize().width; ubo.updateFloat2("vReflectionFilteringInfo", width, Math.log2(width)); } if (supportSH && !defines.USEIRRADIANCEMAP) { const polynomials = reflectionTexture.sphericalPolynomial; if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) { if (defines.SPHERICAL_HARMONICS) { const preScaledHarmonics = polynomials.preScaledHarmonics; ubo.updateVector3("vSphericalL00", preScaledHarmonics.l00); ubo.updateVector3("vSphericalL1_1", preScaledHarmonics.l1_1); ubo.updateVector3("vSphericalL10", preScaledHarmonics.l10); ubo.updateVector3("vSphericalL11", preScaledHarmonics.l11); ubo.updateVector3("vSphericalL2_2", preScaledHarmonics.l2_2); ubo.updateVector3("vSphericalL2_1", preScaledHarmonics.l2_1); ubo.updateVector3("vSphericalL20", preScaledHarmonics.l20); ubo.updateVector3("vSphericalL21", preScaledHarmonics.l21); ubo.updateVector3("vSphericalL22", preScaledHarmonics.l22); } else { ubo.updateFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z); ubo.updateFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z); ubo.updateFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z); ubo.updateFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z); ubo.updateFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z); ubo.updateFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z); ubo.updateFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z); ubo.updateFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z); ubo.updateFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z); } } } else if (usePBR) { if (defines.USEIRRADIANCEMAP && defines.USE_IRRADIANCE_DOMINANT_DIRECTION) { ubo.updateVector3("vReflectionDominantDirection", reflectionTexture.irradianceTexture._dominantDirection); } } if (supportTextureInfo) { ubo.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset); } } } if (useColor) { ubo.updateColor3("vReflectionColor", reflectionColor); } } function BindIBLSamplers(scene, defines, ubo, reflectionTexture = null, realTimeFiltering = false) { if (reflectionTexture && 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); } const cdfGenerator = scene.iblCdfGenerator; if (realTimeFiltering && cdfGenerator) { ubo.setTexture("icdfSampler", cdfGenerator.getIcdfTexture()); } } } function PrepareDefinesForMergedUV(texture, defines, key) { defines._needUVs = true; defines[key] = true; if (texture.optimizeUVAllocation && texture.getTextureMatrix().isIdentityAs3x2()) { defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1; defines["MAINUV" + (texture.coordinatesIndex + 1)] = true; } else { defines[key + "DIRECTUV"] = 0; } } function BindTextureMatrix(texture, uniformBuffer, key) { const matrix = texture.getTextureMatrix(); uniformBuffer.updateMatrix(key + "Matrix", matrix); } function PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines) { const enabled = defines["BAKED_VERTEX_ANIMATION_TEXTURE"] && defines["INSTANCES"]; if (enabled) { attribs.push("bakedVertexAnimationSettingsInstanced"); } } function CopyBonesTransformationMatrices(source, target) { target.set(source); return target; } function BindBonesParameters(mesh, effect, prePassConfiguration) { if (!effect || !mesh) { return; } if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) { mesh.computeBonesUsingShaders = false; } if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { const skeleton = mesh.skeleton; if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) { const boneTexture = skeleton.getTransformMatrixTexture(mesh); effect.setTexture("boneSampler", boneTexture); effect.setFloat("boneTextureWidth", 4 * (skeleton.bones.length + 1)); } else { const matrices = skeleton.getTransformMatrices(mesh); if (matrices) { effect.setMatrices("mBones", matrices); if (prePassConfiguration && mesh.getScene().prePassRenderer && mesh.getScene().prePassRenderer.getIndex(2)) { if (!prePassConfiguration.previousBones[mesh.uniqueId]) { prePassConfiguration.previousBones[mesh.uniqueId] = matrices.slice(); } effect.setMatrices("mPreviousBones", prePassConfiguration.previousBones[mesh.uniqueId]); CopyBonesTransformationMatrices(matrices, prePassConfiguration.previousBones[mesh.uniqueId]); } } } } } function BindLightProperties(light, effect, lightIndex) { light.transferToEffect(effect, lightIndex + ""); } function BindLight(light, lightIndex, scene, effect, useSpecular, receiveShadows = true) { light._bindLight(lightIndex, scene, effect, useSpecular, receiveShadows); } function BindLights(scene, mesh, effect, defines, maxSimultaneousLights = 4) { const len = Math.min(mesh.lightSources.length, maxSimultaneousLights); for (let i = 0; i < len; i++) { const light = mesh.lightSources[i]; BindLight(light, i, scene, effect, typeof defines === "boolean" ? defines : defines["SPECULARTERM"], mesh.receiveShadows); } } function PrepareAttributesForBones(attribs, mesh, defines, fallbacks) { if (defines["NUM_BONE_INFLUENCERS"] > 0) { fallbacks.addCPUSkinningFallback(0, mesh); attribs.push(`matricesIndices`); attribs.push(`matricesWeights`); if (defines["NUM_BONE_INFLUENCERS"] > 4) { attribs.push(`matricesIndicesExtra`); attribs.push(`matricesWeightsExtra`); } } } function PrepareAttributesForInstances(attribs, defines) { if (defines["INSTANCES"] || defines["THIN_INSTANCES"]) { PushAttributesForInstances(attribs, !!defines["PREPASS_VELOCITY"]); } if (defines.INSTANCESCOLOR) { attribs.push(`instanceColor`); } } function HandleFallbacksForShadows(defines, fallbacks, maxSimultaneousLights = 4, rank = 0) { let lightFallbackRank = 0; for (let lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) { if (!defines["LIGHT" + lightIndex]) { break; } if (lightIndex > 0) { lightFallbackRank = rank + lightIndex; fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex); } if (!defines["SHADOWS"]) { if (defines["SHADOW" + lightIndex]) { fallbacks.addFallback(rank, "SHADOW" + lightIndex); } if (defines["SHADOWPCF" + lightIndex]) { fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex); } if (defines["SHADOWPCSS" + lightIndex]) { fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex); } if (defines["SHADOWPOISSON" + lightIndex]) { fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex); } if (defines["SHADOWESM" + lightIndex]) { fallbacks.addFallback(rank, "SHADOWESM" + lightIndex); } if (defines["SHADOWCLOSEESM" + lightIndex]) { fallbacks.addFallback(rank, "SHADOWCLOSEESM" + lightIndex); } } } return lightFallbackRank++; } function GetFogState(mesh, scene) { return scene.fogEnabled && mesh.applyFog && scene.fogMode !== 0; } function PrepareDefinesForMisc(mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines, applyDecalAfterDetail = false, useVertexPulling = false, renderingMesh, setVertexOutputInvariant) { if (defines._areMiscDirty) { defines["LOGARITHMICDEPTH"] = useLogarithmicDepth; defines["POINTSIZE"] = pointsCloud; defines["FOG"] = fogEnabled && GetFogState(mesh, scene); defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling; defines["ALPHATEST"] = alphaTest; defines["DECAL_AFTER_DETAIL"] = applyDecalAfterDetail; defines["USE_VERTEX_PULLING"] = useVertexPulling; const indexBuffer = renderingMesh?.geometry?.getIndexBuffer(); defines["VERTEX_PULLING_USE_INDEX_BUFFER"] = !!indexBuffer; defines["VERTEX_PULLING_INDEX_BUFFER_32BITS"] = indexBuffer ? indexBuffer.is32Bits : false; defines["VERTEXOUTPUT_INVARIANT"] = !!setVertexOutputInvariant; } } function PrepareDefinesForLights(scene, mesh, defines, specularSupported, maxSimultaneousLights = 4, disableLighting = false) { if (!defines._areLightsDirty) { return defines._needNormals; } let lightIndex = 0; const state = { needNormals: defines._needNormals, // prevents overriding previous reflection or other needs for normals needRebuild: false, lightmapMode: false, shadowEnabled: false, specularEnabled: false }; if (scene.lightsEnabled && !disableLighting) { for (const light of mesh.lightSources) { PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state); lightIndex++; if (lightIndex === maxSimultaneousLights) { break; } } } defines["SPECULARTERM"] = state.specularEnabled; defines["SHADOWS"] = state.shadowEnabled; const maxLightCount = Math.max(maxSimultaneousLights, defines["MAXLIGHTCOUNT"] || 0); for (let index = lightIndex; index < maxLightCount; index++) { if (defines["LIGHT" + index] !== void 0) { defines["LIGHT" + index] = false; defines["HEMILIGHT" + index] = false; defines["POINTLIGHT" + index] = false; defines["DIRLIGHT" + index] = false; defines["SPOTLIGHT" + index] = false; defines["AREALIGHT" + index] = false; defines["CLUSTLIGHT" + index] = false; defines["SHADOW" + index] = false; defines["SHADOWCSM" + index] = false; defines["SHADOWCSMDEBUG" + index] = false; defines["SHADOWCSMNUM_CASCADES" + index] = false; defines["SHADOWCSMUSESHADOWMAXZ" + index] = false; defines["SHADOWCSMNOBLEND" + index] = false; defines["SHADOWCSM_RIGHTHANDED" + index] = false; defines["SHADOWPCF" + index] = false; defines["SHADOWPCSS" + index] = false; defines["SHADOWPOISSON" + index] = false; defines["SHADOWESM" + index] = false; defines["SHADOWCLOSEESM" + index] = false; defines["SHADOWCUBE" + index] = false; defines["SHADOWLOWQUALITY" + index] = false; defines["SHADOWMEDIUMQUALITY" + index] = false; } } defines["MAXLIGHTCOUNT"] = maxSimultaneousLights; const caps = scene.getEngine().getCaps(); if (defines["SHADOWFLOAT"] === void 0) { state.needRebuild = true; } defines["SHADOWFLOAT"] = state.shadowEnabled && (caps.textureFloatRender && caps.textureFloatLinearFiltering || caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering); defines["LIGHTMAPEXCLUDED"] = state.lightmapMode; if (state.needRebuild) { defines.rebuild(); } return state.needNormals; } function PrepareDefinesForIBL(scene, reflectionTexture, defines, realTimeFiltering = false, realTimeFilteringQuality = 8, forceSHInVertex = false) { if (reflectionTexture && MaterialFlags.ReflectionTextureEnabled) { if (!reflectionTexture.isReadyOrNotBlocking()) { return false; } defines._needNormals = true; defines.REFLECTION = true; defines.GAMMAREFLECTION = reflectionTexture.gammaSpace; defines.RGBDREFLECTION = reflectionTexture.isRGBD; defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha; defines.LINEARSPECULARREFLECTION = reflectionTexture.linearSpecularLOD; defines.USEIRRADIANCEMAP = false; const engine = scene.getEngine(); if (realTimeFiltering && realTimeFilteringQuality > 0) { defines.NUM_SAMPLES = "" + realTimeFilteringQuality; if (engine._features.needTypeSuffixInShaderConstants) { defines.NUM_SAMPLES = defines.NUM_SAMPLES + "u"; } defines.REALTIME_FILTERING = true; if (scene.iblCdfGenerator) { defines.IBL_CDF_FILTERING = true; } } else { defines.REALTIME_FILTERING = false; } defines.INVERTCUBICMAP = reflectionTexture.coordinatesMode === Texture.INVCUBIC_MODE; defines.REFLECTIONMAP_3D = reflectionTexture.isCube; defines.REFLECTIONMAP_OPPOSITEZ = defines.REFLECTIONMAP_3D && scene.useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ; 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 Texture.EXPLICIT_MODE: defines.REFLECTIONMAP_EXPLICIT = true; break; case Texture.PLANAR_MODE: defines.REFLECTIONMAP_PLANAR = true; break; case Texture.PROJECTION_MODE: defines.REFLECTIONMAP_PROJECTION = true; break; case Texture.SKYBOX_MODE: defines.REFLECTIONMAP_SKYBOX = true; break; case Texture.SPHERICAL_MODE: defines.REFLECTIONMAP_SPHERICAL = true; break; case Texture.EQUIRECTANGULAR_MODE: defines.REFLECTIONMAP_EQUIRECTANGULAR = true; break; case Texture.FIXED_EQUIRECTANGULAR_MODE: defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true; break; case Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE: defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true; break; case Texture.CUBIC_MODE: case Texture.INVCUBIC_MODE: default: defines.REFLECTIONMAP_CUBIC = true; defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false; break; } if (reflectionTexture.coordinatesMode !== Texture.SKYBOX_MODE) { if (reflectionTexture.irradianceTexture) { defines.USEIRRADIANCEMAP = true; defines.USESPHERICALFROMREFLECTIONMAP = false; defines.USESPHERICALINVERTEX = false; if (reflectionTexture.irradianceTexture._dominantDirection) { defines.USE_IRRADIANCE_DOMINANT_DIRECTION = true; } } else if (reflectionTexture.isCube) { defines.USESPHERICALFROMREFLECTIONMAP = true; defines.USEIRRADIANCEMAP = false; defines.USE_IRRADIANCE_DOMINANT_DIRECTION = false; defines.USESPHERICALINVERTEX = forceSHInVertex; } } } 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.USE_IRRADIANCE_DOMINANT_DIRECTION = false; defines.USESPHERICALINVERTEX = false; defines.REFLECTIONMAP_OPPOSITEZ = false; defines.LODINREFLECTIONALPHA = false; defines.GAMMAREFLECTION = false; defines.RGBDREFLECTION = false; defines.LINEARSPECULARREFLECTION = false; } return true; } function PrepareDefinesForLight(scene, mesh, light, lightIndex, defines, specularSupported, state) { state.needNormals = true; if (defines["LIGHT" + lightIndex] === void 0) { state.needRebuild = true; } defines["LIGHT" + lightIndex] = true; defines["SPOTLIGHT" + lightIndex] = false; defines["HEMILIGHT" + lightIndex] = false; defines["POINTLIGHT" + lightIndex] = false; defines["DIRLIGHT" + lightIndex] = false; defines["AREALIGHT" + lightIndex] = false; defines["CLUSTLIGHT" + lightIndex] = false; light.prepareLightSpecificDefines(defines, lightIndex); defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false; defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false; defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false; switch (light.falloffType) { case LightConstants.FALLOFF_GLTF: defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true; break; case LightConstants.FALLOFF_PHYSICAL: defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true; break; case LightConstants.FALLOFF_STANDARD: defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true; break; } if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) { state.specularEnabled = true; } defines["SHADOW" + lightIndex] = false; defines["SHADOWCSM" + lightIndex] = false; defines["SHADOWCSMDEBUG" + lightIndex] = false; defines["SHADOWCSMNUM_CASCADES" + lightIndex] = false; defines["SHADOWCSMUSESHADOWMAXZ" + lightIndex] = false; defines["SHADOWCSMNOBLEND" + lightIndex] = false; defines["SHADOWCSM_RIGHTHANDED" + lightIndex] = false; defines["SHADOWPCF" + lightIndex] = false; defines["SHADOWPCSS" + lightIndex] = false; defines["SHADOWPOISSON" + lightIndex] = false; defines["SHADOWESM" + lightIndex] = false; defines["SHADOWCLOSEESM" + lightIndex] = false; defines["SHADOWCUBE" + lightIndex] = false; defines["SHADOWLOWQUALITY" + lightIndex] = false; defines["SHADOWMEDIUMQUALITY" + lightIndex] = false; if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) { const shadowGenerator = light.getShadowGenerator(scene.activeCamera) ?? light.getShadowGenerator(); if (shadowGenerator) { const shadowMap = shadowGenerator.getShadowMap(); if (shadowMap) { if (shadowMap.renderList && shadowMap.renderList.length > 0) { state.shadowEnabled = true; shadowGenerator.prepareDefines(defines, lightIndex); } } } } if (light.lightmapMode != LightConstants.LIGHTMAP_DEFAULT) { state.lightmapMode = true; defines["LIGHTMAPEXCLUDED" + lightIndex] = true; defines["LIGHTMAPNOSPECULAR" + lightIndex] = light.lightmapMode == LightConstants.LIGHTMAP_SHADOWSONLY; } else { defines["LIGHTMAPEXCLUDED" + lightIndex] = false; defines["LIGHTMAPNOSPECULAR" + lightIndex] = false; } } function PrepareDefinesForFrameBoundValues(scene, engine, material, defines, useInstances, useClipPlane = null, useThinInstances = false) { let changed = PrepareDefinesForCamera(scene, defines); if (useClipPlane !== false) { changed = PrepareDefinesForClipPlanes(material, scene, defines); } if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) { defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"]; changed = true; } if (defines["INSTANCES"] !== useInstances) { defines["INSTANCES"] = useInstances; changed = true; } if (defines["THIN_INSTANCES"] !== useThinInstances) { defines["THIN_INSTANCES"] = useThinInstances; changed = true; } if (changed) { defines.markAsUnprocessed(); } } function PrepareDefinesForBones(mesh, defines) { if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers; const materialSupportsBoneTexture = defines["BONETEXTURE"] !== void 0; if (mesh.skeleton.isUsingTextureForMatrices && materialSupportsBoneTexture) { defines["BONETEXTURE"] = true; } else { defines["BonesPerMesh"] = mesh.skeleton.bones.length + 1; defines["BONETEXTURE"] = materialSupportsBoneTexture ? false : void 0; const prePassRenderer = mesh.getScene().prePassRenderer; if (prePassRenderer && prePassRenderer.enabled) { const nonExcluded = prePassRenderer.excludedSkinnedMesh.indexOf(mesh) === -1; defines["BONES_VELOCITY_ENABLED"] = nonExcluded; } } } else { defines["NUM_BONE_INFLUENCERS"] = 0; defines["BonesPerMesh"] = 0; if (defines["BONETEXTURE"] !== void 0) { defines["BONETEXTURE"] = false; } } } function PrepareDefinesForMorphTargets(mesh, defines) { const manager = mesh.morphTargetManager; if (manager) { defines["MORPHTARGETS_UV"] = manager.supportsUVs && defines["UV1"]; defines["MORPHTARGETS_UV2"] = manager.supportsUV2s && defines["UV2"]; defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"]; defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"]; defines["MORPHTARGETS_POSITION"] = manager.supportsPositions; defines["MORPHTARGETS_COLOR"] = manager.supportsColors; defines["MORPHTARGETTEXTURE_HASUVS"] = manager.hasUVs; defines["MORPHTARGETTEXTURE_HASUV2S"] = manager.hasUV2s; defines["MORPHTARGETTEXTURE_HASTANGENTS"] = manager.hasTangents; defines["MORPHTARGETTEXTURE_HASNORMALS"] = manager.hasNormals; defines["MORPHTARGETTEXTURE_HASPOSITIONS"] = manager.hasPositions; defines["MORPHTARGETTEXTURE_HASCOLORS"] = manager.hasColors; defines["NUM_MORPH_INFLUENCERS"] = manager.numMaxInfluencers || manager.numInfluencers; defines["MORPHTARGETS"] = defines["NUM_MORPH_INFLUENCERS"] > 0; defines["MORPHTARGETS_TEXTURE"] = manager.isUsingTextureForTargets; } else { defines["MORPHTARGETS_UV"] = false; defines["MORPHTARGETS_UV2"] = false; defines["MORPHTARGETS_TANGENT"] = false; defines["MORPHTARGETS_NORMAL"] = false; defines["MORPHTARGETS_POSITION"] = false; defines["MORPHTARGETS_COLOR"] = false; defines["MORPHTARGETTEXTURE_HASUVS"] = false; defines["MORPHTARGETTEXTURE_HASUV2S"] = false; defines["MORPHTARGETTEXTURE_HASTANGENTS"] = false; defines["MORPHTARGETTEXTURE_HASNORMALS"] = false; defines["MORPHTARGETTEXTURE_HASPOSITIONS"] = false; defines["MORPHTARGETTEXTURE_HAS_COLORS"] = false; defines["MORPHTARGETS"] = false; defines["NUM_MORPH_INFLUENCERS"] = 0; } } function PrepareDefinesForBakedVertexAnimation(mesh, defines) { const manager = mesh.bakedVertexAnimationManager; defines["BAKED_VERTEX_ANIMATION_TEXTURE"] = manager && manager.isEnabled ? true : false; } function PrepareDefinesForAttributes(mesh, defines, useVertexColor, useBones, useMorphTargets = false, useVertexAlpha = true, useBakedVertexAnimation = true) { if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) { return false; } defines._normals = defines._needNormals; defines._uvs = defines._needUVs; defines["NORMAL"] = defines._needNormals && mesh.isVerticesDataPresent(`normal`); if (defines._needNormals && mesh.isVerticesDataPresent(`tangent`)) { defines["TANGENT"] = true; } for (let i = 1; i <= 6; ++i) { defines["UV" + i] = defines._needUVs ? mesh.isVerticesDataPresent(`uv${i === 1 ? "" : i}`) : false; } if (useVertexColor) { const hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(`color`); defines["VERTEXCOLOR"] = hasVertexColors; defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha; } if (mesh.isVerticesDataPresent(`instanceColor`) && (mesh.hasInstances || mesh.hasThinInstances)) { defines["INSTANCESCOLOR"] = true; } if (useBones) { PrepareDefinesForBones(mesh, defines); } if (useMorphTargets) { PrepareDefinesForMorphTargets(mesh, defines); } if (useBakedVertexAnimation) { PrepareDefinesForBakedVertexAnimation(mesh, defines); } return true; } function PrepareDefinesForMultiview(scene, defines) { if (scene.activeCamera) { const previousMultiview = defines.MULTIVIEW; defines.MULTIVIEW = scene.activeCamera.outputRenderTarget !== null && scene.activeCamera.outputRenderTarget.getViewCount() > 1; if (defines.MULTIVIEW != previousMultiview) { defines.markAsUnprocessed(); } } } function PrepareDefinesForOIT(scene, defines, needAlphaBlending) { const previousDefine = defines.ORDER_INDEPENDENT_TRANSPARENCY; const previousDefine16Bits = defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS; defines.ORDER_INDEPENDENT_TRANSPARENCY = scene.useOrderIndependentTransparency && needAlphaBlending; defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = !scene.getEngine().getCaps().textureFloatLinearFiltering; if (previousDefine !== defines.ORDER_INDEPENDENT_TRANSPARENCY || previousDefine16Bits !== defines.ORDER_INDEPENDENT_TRANSPARENCY_16BITS) { defines.markAsUnprocessed(); } } function PrepareDefinesForPrePass(scene, defines, canRenderToMRT) { const previousPrePass = defines.PREPASS; if (!defines._arePrePassDirty) { return; } const texturesList = [ { type: 1, define: "PREPASS_POSITION", index: "PREPASS_POSITION_INDEX" }, { type: 9, define: "PREPASS_LOCAL_POSITION", index: "PREPASS_LOCAL_POSITION_INDEX" }, { type: 2, define: "PREPASS_VELOCITY", index: "PREPASS_VELOCITY_INDEX" }, { type: 11, define: "PREPASS_VELOCITY_LINEAR", index: "PREPASS_VELOCITY_LINEAR_INDEX" }, { type: 3, define: "PREPASS_REFLECTIVITY", index: "PREPASS_REFLECTIVITY_INDEX" }, { type: 0, define: "PREPASS_IRRADIANCE", index: "PREPASS_IRRADIANCE_INDEX" }, { type: 7, define: "PREPASS_ALBEDO_SQRT", index: "PREPASS_ALBEDO_SQRT_INDEX" }, { type: 5, define: "PREPASS_DEPTH", index: "PREPASS_DEPTH_INDEX" }, { type: 10, define: "PREPASS_SCREENSPACE_DEPTH", index: "PREPASS_SCREENSPACE_DEPTH_INDEX" }, { type: 6, define: "PREPASS_NORMAL", index: "PREPASS_NORMAL_INDEX" }, { type: 8, define: "PREPASS_WORLD_NORMAL", index: "PREPASS_WORLD_NORMAL_INDEX" } ]; if (scene.prePassRenderer && scene.prePassRenderer.enabled && canRenderToMRT) { defines.PREPASS = true; defines.SCENE_MRT_COUNT = scene.prePassRenderer.mrtCount; defines.PREPASS_NORMAL_WORLDSPACE = scene.prePassRenderer.generateNormalsInWorldSpace; defines.PREPASS_COLOR = true; defines.PREPASS_COLOR_INDEX = 0; for (let i = 0; i < texturesList.length; i++) { const index = scene.prePassRenderer.getIndex(texturesList[i].type); if (index !== -1) { defines[texturesList[i].define] = true; defines[texturesList[i].index] = index; } else { defines[texturesList[i].define] = false; } } } else { defines.PREPASS = false; for (let i = 0; i < texturesList.length; i++) { defines[texturesList[i].define] = false; } } if (defines.PREPASS != previousPrePass) { defines.markAsUnprocessed(); defines.markAsImageProcessingDirty(); } } function PrepareDefinesForCamera(scene, defines) { let changed = false; if (scene.activeCamera) { const wasOrtho = defines["CAMERA_ORTHOGRAPHIC"] ? 1 : 0; const wasPersp = defines["CAMERA_PERSPECTIVE"] ? 1 : 0; const isOrtho = scene.activeCamera.mode === 1 ? 1 : 0; const isPersp = scene.activeCamera.mode === 0 ? 1 : 0; if (wasOrtho ^ isOrtho || wasPersp ^ isPersp) { defines["CAMERA_ORTHOGRAPHIC"] = isOrtho === 1; defines["CAMERA_PERSPECTIVE"] = isPersp === 1; changed = true; } } return changed; } function PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, projectedLightTexture, uniformBuffersList = null, updateOnlyBuffersList = false, iesLightTexture = false, clusteredLightTextures = false) { if (uniformBuffersList) { uniformBuffersList.push("Light" + lightIndex); } if (updateOnlyBuffersList) { return; } uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightWidth" + lightIndex, "vLightHeight" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "vSliceData" + lightIndex, "vSliceRanges" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex); samplersList.push("shadowTexture" + lightIndex); samplersList.push("depthTexture" + lightIndex); uniformsList.push("viewFrustumZ" + lightIndex, "cascadeBlendFactor" + lightIndex, "lightSizeUVCorrection" + lightIndex, "depthCorrection" + lightIndex, "penumbraDarkness" + lightIndex, "frustumLengths" + lightIndex); if (projectedLightTexture) { samplersList.push("projectionLightTexture" + lightIndex); uniformsList.push("textureProjectionMatrix" + lightIndex); } if (iesLightTexture) { samplersList.push("iesLightTexture" + lightIndex); } if (clusteredLightTextures) { samplersList.push("lightDataTexture" + lightIndex); samplersList.push("tileMaskTexture" + lightIndex); } } function PrepareUniformsAndSamplersForIBL(uniformsList, samplersList, useSH) { const iblUniforms = [ "vReflectionMicrosurfaceInfos", "vReflectionDominantDirection", "reflectionMatrix", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vReflectionColor", "vReflectionFilteringInfo" ]; if (useSH) { iblUniforms.push("vSphericalX", "vSphericalY", "vSphericalZ", "vSphericalXX_ZZ", "vSphericalYY_ZZ", "vSphericalZZ", "vSphericalXY", "vSphericalYZ", "vSphericalZX", "vSphericalL00", "vSphericalL1_1", "vSphericalL10", "vSphericalL11", "vSphericalL2_2", "vSphericalL2_1", "vSphericalL20", "vSphericalL21", "vSphericalL22"); } uniformsList.push(...iblUniforms); const iblSamplers = ["reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh", "irradianceSampler", "icdfSampler"]; samplersList.push(...iblSamplers); } function PrepareUniformsAndSamplersList(uniformsListOrOptions, samplersList, defines, maxSimultaneousLights = 4) { let uniformsList; let uniformBuffersList; if (uniformsListOrOptions.uniformsNames) { const options = uniformsListOrOptions; uniformsList = options.uniformsNames; uniformBuffersList = options.uniformBuffersNames; samplersList = options.samplers; defines = options.defines; maxSimultaneousLights = options.maxSimultaneousLights || 0; } else { uniformsList = uniformsListOrOptions; if (!samplersList) { samplersList = []; } } for (let lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) { if (!defines["LIGHT" + lightIndex]) { break; } PrepareUniformsAndSamplersForLight(lightIndex, uniformsList, samplersList, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffersList, false, defines["IESLIGHTTEXTURE" + lightIndex], defines["CLUSTLIGHT" + lightIndex]); } if (defines["NUM_MORPH_INFLUENCERS"]) { uniformsList.push("morphTargetInfluences"); uniformsList.push("morphTargetCount"); } if (defines["BAKED_VERTEX_ANIMATION_TEXTURE"]) { uniformsList.push("bakedVertexAnimationSettings"); uniformsList.push("bakedVertexAnimationTextureSizeInverted"); uniformsList.push("bakedVertexAnimationTime"); samplersList.push("bakedVertexAnimationTexture"); } } function PrepareUniformLayoutForIBL(ubo, supportTextureInfo = false, supportLocalProjection = false, usePBR = false, supportSH = false, useColor = false) { ubo.addUniform("vReflectionInfos", 2); ubo.addUniform("reflectionMatrix", 16); if (supportTextureInfo) { ubo.addUniform("vReflectionMicrosurfaceInfos", 3); } if (supportLocalProjection) { ubo.addUniform("vReflectionPosition", 3); ubo.addUniform("vReflectionSize", 3); } if (usePBR) { ubo.addUniform("vReflectionFilteringInfo", 2); ubo.addUniform("vReflectionDominantDirection", 3); } if (useColor) { ubo.addUniform("vReflectionColor", 3); } if (supportSH) { ubo.addUniform("vSphericalL00", 3); ubo.addUniform("vSphericalL1_1", 3); ubo.addUniform("vSphericalL10", 3); ubo.addUniform("vSphericalL11", 3); ubo.addUniform("vSphericalL2_2", 3); ubo.addUniform("vSphericalL2_1", 3); ubo.addUniform("vSphericalL20", 3); ubo.addUniform("vSphericalL21", 3); ubo.addUniform("vSphericalL22", 3); ubo.addUniform("vSphericalX", 3); ubo.addUniform("vSphericalY", 3); ubo.addUniform("vSphericalZ", 3); ubo.addUniform("vSphericalXX_ZZ", 3); ubo.addUniform("vSphericalYY_ZZ", 3); ubo.addUniform("vSphericalZZ", 3); ubo.addUniform("vSphericalXY", 3); ubo.addUniform("vSphericalYZ", 3); ubo.addUniform("vSphericalZX", 3); } } var TempFogColor, TmpMorphInfluencers; var init_materialHelper_functions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialHelper.functions.js"() { init_logger(); init_engineStore(); init_lightConstants(); init_clipPlaneMaterialHelper(); init_materialFlags(); init_texture(); init_materialHelper_functions_pure(); TempFogColor = { r: 0, g: 0, b: 0 }; TmpMorphInfluencers = { NUM_MORPH_INFLUENCERS: 0, NORMAL: false, TANGENT: false, UV: false, UV2: false, COLOR: false }; __name(BindFogParameters, "BindFogParameters"); __name(PrepareDefinesAndAttributesForMorphTargets, "PrepareDefinesAndAttributesForMorphTargets"); __name(PrepareAttributesForMorphTargetsInfluencers, "PrepareAttributesForMorphTargetsInfluencers"); __name(PrepareAttributesForMorphTargets, "PrepareAttributesForMorphTargets"); __name(PushAttributesForInstances, "PushAttributesForInstances"); __name(BindMorphTargetParameters, "BindMorphTargetParameters"); __name(BindSceneUniformBuffer, "BindSceneUniformBuffer"); __name(BindIBLParameters, "BindIBLParameters"); __name(BindIBLSamplers, "BindIBLSamplers"); __name(PrepareDefinesForMergedUV, "PrepareDefinesForMergedUV"); __name(BindTextureMatrix, "BindTextureMatrix"); __name(PrepareAttributesForBakedVertexAnimation, "PrepareAttributesForBakedVertexAnimation"); __name(CopyBonesTransformationMatrices, "CopyBonesTransformationMatrices"); __name(BindBonesParameters, "BindBonesParameters"); __name(BindLightProperties, "BindLightProperties"); __name(BindLight, "BindLight"); __name(BindLights, "BindLights"); __name(PrepareAttributesForBones, "PrepareAttributesForBones"); __name(PrepareAttributesForInstances, "PrepareAttributesForInstances"); __name(HandleFallbacksForShadows, "HandleFallbacksForShadows"); __name(GetFogState, "GetFogState"); __name(PrepareDefinesForMisc, "PrepareDefinesForMisc"); __name(PrepareDefinesForLights, "PrepareDefinesForLights"); __name(PrepareDefinesForIBL, "PrepareDefinesForIBL"); __name(PrepareDefinesForLight, "PrepareDefinesForLight"); __name(PrepareDefinesForFrameBoundValues, "PrepareDefinesForFrameBoundValues"); __name(PrepareDefinesForBones, "PrepareDefinesForBones"); __name(PrepareDefinesForMorphTargets, "PrepareDefinesForMorphTargets"); __name(PrepareDefinesForBakedVertexAnimation, "PrepareDefinesForBakedVertexAnimation"); __name(PrepareDefinesForAttributes, "PrepareDefinesForAttributes"); __name(PrepareDefinesForMultiview, "PrepareDefinesForMultiview"); __name(PrepareDefinesForOIT, "PrepareDefinesForOIT"); __name(PrepareDefinesForPrePass, "PrepareDefinesForPrePass"); __name(PrepareDefinesForCamera, "PrepareDefinesForCamera"); __name(PrepareUniformsAndSamplersForLight, "PrepareUniformsAndSamplersForLight"); __name(PrepareUniformsAndSamplersForIBL, "PrepareUniformsAndSamplersForIBL"); __name(PrepareUniformsAndSamplersList, "PrepareUniformsAndSamplersList"); __name(PrepareUniformLayoutForIBL, "PrepareUniformLayoutForIBL"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/Shadows/shadowGenerator.js var ShadowGenerator; var init_shadowGenerator = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/Shadows/shadowGenerator.js"() { init_math_vector(); init_math_color(); init_buffer(); init_light(); init_texture(); init_renderTargetTexture(); init_postProcess(); init_blurPostProcess(); init_observable(); init_devTools(); init_effectFallbacks(); init_renderingManager(); init_drawWrapper(); init_clipPlaneMaterialHelper(); init_materialHelper_functions(); ShadowGenerator = class _ShadowGenerator { static { __name(this, "ShadowGenerator"); } /** * Gets the bias: offset applied on the depth preventing acnea (in light direction). */ get bias() { return this._bias; } /** * Sets the bias: offset applied on the depth preventing acnea (in light direction). */ set bias(bias) { this._bias = bias; } /** * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportional to the light/normal angle). */ get normalBias() { return this._normalBias; } /** * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportional to the light/normal angle). */ set normalBias(normalBias) { this._normalBias = normalBias; } /** * Gets the blur box offset: offset applied during the blur pass. * Only useful if useKernelBlur = false */ get blurBoxOffset() { return this._blurBoxOffset; } /** * Sets the blur box offset: offset applied during the blur pass. * Only useful if useKernelBlur = false */ set blurBoxOffset(value) { if (this._blurBoxOffset === value) { return; } this._blurBoxOffset = value; this._disposeBlurPostProcesses(); } /** * Gets the blur scale: scale of the blurred texture compared to the main shadow map. * 2 means half of the size. */ get blurScale() { 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 blurScale(value) { if (this._blurScale === value) { return; } this._blurScale = value; this._disposeBlurPostProcesses(); } /** * Gets the blur kernel: kernel size of the blur pass. * Only useful if useKernelBlur = true */ get blurKernel() { return this._blurKernel; } /** * Sets the blur kernel: kernel size of the blur pass. * Only useful if useKernelBlur = true */ set blurKernel(value) { if (this._blurKernel === value) { return; } this._blurKernel = value; this._disposeBlurPostProcesses(); } /** * Gets whether the blur pass is a kernel blur (if true) or box blur. * Only useful in filtered mode (useBlurExponentialShadowMap...) */ get useKernelBlur() { return this._useKernelBlur; } /** * Sets whether the blur pass is a kernel blur (if true) or box blur. * Only useful in filtered mode (useBlurExponentialShadowMap...) */ set useKernelBlur(value) { if (this._useKernelBlur === value) { return; } this._useKernelBlur = value; this._disposeBlurPostProcesses(); } /** * Gets the depth scale used in ESM mode. */ get depthScale() { return this._depthScale !== void 0 ? this._depthScale : this._light.getDepthScale(); } /** * Sets the depth scale used in ESM mode. * This can override the scale stored on the light. */ set depthScale(value) { this._depthScale = value; } _validateFilter(filter) { return 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 filter() { 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 filter(value) { value = this._validateFilter(value); if (this._light.needCube()) { if (value === _ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) { this.useExponentialShadowMap = true; return; } else if (value === _ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) { this.useCloseExponentialShadowMap = true; return; } else if (value === _ShadowGenerator.FILTER_PCF || value === _ShadowGenerator.FILTER_PCSS) { this.usePoissonSampling = true; return; } } if (value === _ShadowGenerator.FILTER_PCF || value === _ShadowGenerator.FILTER_PCSS) { if (!this._scene.getEngine()._features.supportShadowSamplers) { this.usePoissonSampling = true; return; } } if (this._filter === value) { return; } this._filter = value; this._disposeBlurPostProcesses(); this._applyFilterValues(); this._light._markMeshesAsLightDirty(); } /** * Gets if the current filter is set to Poisson Sampling. */ get usePoissonSampling() { return this.filter === _ShadowGenerator.FILTER_POISSONSAMPLING; } /** * Sets the current filter to Poisson Sampling. */ set usePoissonSampling(value) { const filter = this._validateFilter(_ShadowGenerator.FILTER_POISSONSAMPLING); if (!value && this.filter !== _ShadowGenerator.FILTER_POISSONSAMPLING) { return; } this.filter = value ? filter : _ShadowGenerator.FILTER_NONE; } /** * Gets if the current filter is set to ESM. */ get useExponentialShadowMap() { return this.filter === _ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP; } /** * Sets the current filter is to ESM. */ set useExponentialShadowMap(value) { const filter = this._validateFilter(_ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP); if (!value && this.filter !== _ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) { return; } this.filter = value ? filter : _ShadowGenerator.FILTER_NONE; } /** * Gets if the current filter is set to filtered ESM. */ get useBlurExponentialShadowMap() { return this.filter === _ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP; } /** * Gets if the current filter is set to filtered ESM. */ set useBlurExponentialShadowMap(value) { const filter = this._validateFilter(_ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP); if (!value && this.filter !== _ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) { return; } this.filter = value ? filter : _ShadowGenerator.FILTER_NONE; } /** * Gets if the current filter is set to "close ESM" (using the inverse of the * exponential to prevent steep falloff artifacts). */ get useCloseExponentialShadowMap() { 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 useCloseExponentialShadowMap(value) { const filter = this._validateFilter(_ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP); if (!value && this.filter !== _ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) { return; } this.filter = value ? filter : _ShadowGenerator.FILTER_NONE; } /** * Gets if the current filter is set to filtered "close ESM" (using the inverse of the * exponential to prevent steep falloff artifacts). */ get useBlurCloseExponentialShadowMap() { 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 useBlurCloseExponentialShadowMap(value) { const filter = this._validateFilter(_ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP); if (!value && this.filter !== _ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) { return; } this.filter = value ? filter : _ShadowGenerator.FILTER_NONE; } /** * Gets if the current filter is set to "PCF" (percentage closer filtering). */ get usePercentageCloserFiltering() { return this.filter === _ShadowGenerator.FILTER_PCF; } /** * Sets the current filter to "PCF" (percentage closer filtering). */ set usePercentageCloserFiltering(value) { const filter = this._validateFilter(_ShadowGenerator.FILTER_PCF); if (!value && this.filter !== _ShadowGenerator.FILTER_PCF) { return; } this.filter = value ? filter : _ShadowGenerator.FILTER_NONE; } /** * Gets the PCF or PCSS Quality. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. */ get filteringQuality() { return this._filteringQuality; } /** * Sets the PCF or PCSS Quality. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true. */ set filteringQuality(filteringQuality) { if (this._filteringQuality === filteringQuality) { return; } this._filteringQuality = filteringQuality; this._disposeBlurPostProcesses(); this._applyFilterValues(); this._light._markMeshesAsLightDirty(); } /** * Gets if the current filter is set to "PCSS" (contact hardening). */ get useContactHardeningShadow() { return this.filter === _ShadowGenerator.FILTER_PCSS; } /** * Sets the current filter to "PCSS" (contact hardening). */ set useContactHardeningShadow(value) { const filter = this._validateFilter(_ShadowGenerator.FILTER_PCSS); if (!value && this.filter !== _ShadowGenerator.FILTER_PCSS) { return; } this.filter = value ? filter : _ShadowGenerator.FILTER_NONE; } /** * 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 contactHardeningLightSizeUVRatio() { 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 contactHardeningLightSizeUVRatio(contactHardeningLightSizeUVRatio) { this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio; } /** Gets or sets the actual darkness of a shadow */ get darkness() { return this._darkness; } set darkness(value) { this.setDarkness(value); } /** * 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. */ getDarkness() { 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. */ setDarkness(darkness) { if (darkness >= 1) { this._darkness = 1; } else if (darkness <= 0) { this._darkness = 0; } else { this._darkness = darkness; } return this; } /** Gets or sets the ability to have transparent shadow */ get transparencyShadow() { return this._transparencyShadow; } set transparencyShadow(value) { this.setTransparencyShadow(value); } /** * Sets the ability to have transparent shadow (boolean). * @param transparent True if transparent else False * @returns the shadow generator allowing fluent coding */ setTransparencyShadow(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 */ getShadowMap() { 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 */ getShadowMapForRendering() { if (this._shadowMap2) { return this._shadowMap2; } return this._shadowMap; } /** * Gets the class name of that object * @returns "ShadowGenerator" */ getClassName() { 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 */ addShadowCaster(mesh, includeDescendants = true) { if (!this._shadowMap) { return this; } if (!this._shadowMap.renderList) { this._shadowMap.renderList = []; } if (this._shadowMap.renderList.indexOf(mesh) === -1) { this._shadowMap.renderList.push(mesh); } if (includeDescendants) { for (const childMesh of mesh.getChildMeshes()) { if (this._shadowMap.renderList.indexOf(childMesh) === -1) { this._shadowMap.renderList.push(childMesh); } } } 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 */ removeShadowCaster(mesh, includeDescendants = true) { if (!this._shadowMap || !this._shadowMap.renderList) { return this; } const index = this._shadowMap.renderList.indexOf(mesh); if (index !== -1) { this._shadowMap.renderList.splice(index, 1); } if (includeDescendants) { for (const child of mesh.getChildren()) { this.removeShadowCaster(child); } } return this; } /** * Returns the associated light object. * @returns the light generating the shadow */ getLight() { return this._light; } /** * Gets the shader language used in this generator. */ get shaderLanguage() { return this._shaderLanguage; } _getCamera() { return this._camera ?? this._scene.activeCamera; } /** * Gets or sets the size of the texture what stores the shadows */ get mapSize() { return this._mapSize; } set mapSize(size) { this._mapSize = size; this._light._markMeshesAsLightDirty(); this.recreateShadowMap(); } /** * 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/features/featuresDeepDive/lights/shadows * @param mapSize The size of the texture what stores the shadows. Example : 1024. * @param light The light object generating the shadows. * @param usefullFloatFirst 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. * @param camera Camera associated with this shadow generator (default: null). If null, takes the scene active camera at the time we need to access it * @param useRedTextureType Forces the generator to use a Red instead of a RGBA type for the shadow map texture format (default: false) * @param forceGLSL defines a boolean indicating if the shader must be compiled in GLSL even if we are using WebGPU */ constructor(mapSize, light, usefullFloatFirst, camera, useRedTextureType, forceGLSL = false) { this.onBeforeShadowMapRenderObservable = new Observable(); this.onAfterShadowMapRenderObservable = new Observable(); this.onBeforeShadowMapRenderMeshObservable = new Observable(); this.onAfterShadowMapRenderMeshObservable = new Observable(); this.doNotSerialize = false; this._bias = 5e-5; 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; this.enableSoftTransparentShadow = false; this.useOpacityTextureForTransparentShadow = false; this.frustumEdgeFalloff = 0; this._shaderLanguage = 0; this.forceBackFacesOnly = false; this._lightDirection = Vector3.Zero(); this._viewMatrix = Matrix.Zero(); this._projectionMatrix = Matrix.Zero(); this._transformMatrix = Matrix.Zero(); this._cachedPosition = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._cachedDirection = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._currentFaceIndex = 0; this._currentFaceIndexCache = 0; this._defaultTextureMatrix = Matrix.Identity(); this._shadersLoaded = false; this._mapSize = mapSize; this._light = light; this._scene = light.getScene(); this._camera = camera ?? null; this._useRedTextureType = !!useRedTextureType; this._initShaderSourceAsync(forceGLSL); let shadowGenerators = light._shadowGenerators; if (!shadowGenerators) { shadowGenerators = light._shadowGenerators = /* @__PURE__ */ new Map(); } shadowGenerators.set(this._camera, this); this.id = light.id; this._useUBO = this._scene.getEngine().supportsUniformBuffers; if (this._useUBO) { this._sceneUBOs = []; this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for Shadow Generator (light "${this._light.name}")`)); } _ShadowGenerator._SceneComponentInitialization(this._scene); const caps = this._scene.getEngine().getCaps(); if (!usefullFloatFirst) { if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { this._textureType = 2; } else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { this._textureType = 1; } else { this._textureType = 0; } } else { if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { this._textureType = 1; } else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { this._textureType = 2; } else { this._textureType = 0; } } this._initializeGenerator(); this._applyFilterValues(); } _initializeGenerator() { this._light._markMeshesAsLightDirty(); this._initializeShadowMap(); } _createTargetRenderTexture() { const engine = this._scene.getEngine(); this._shadowMap?.dispose(); if (engine._features.supportDepthStencilTexture) { this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), void 0, false, false, void 0, this._useRedTextureType ? 6 : 5); this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? 516 : 513, true, void 0, void 0, void 0, `DepthStencilForShadowGenerator-${this._light.name}`); } else { this._shadowMap = new RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube()); } this._shadowMap.noPrePassRenderer = true; } _initializeShadowMap() { this._createTargetRenderTexture(); if (this._shadowMap === null) { return; } this._shadowMap.wrapU = Texture.CLAMP_ADDRESSMODE; this._shadowMap.wrapV = Texture.CLAMP_ADDRESSMODE; this._shadowMap.anisotropicFilteringLevel = 1; this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE); this._shadowMap.renderParticles = false; this._shadowMap.ignoreCameraViewport = true; if (this._storedUniqueId) { this._shadowMap.uniqueId = this._storedUniqueId; } this._shadowMap.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => this._renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes); this._shadowMap.customIsReadyFunction = (mesh, _refreshRate, preWarm) => { if (!preWarm || !mesh.subMeshes) { return true; } let isReady = true; for (const subMesh of mesh.subMeshes) { const renderingMesh = subMesh.getRenderingMesh(); const scene = this._scene; const engine2 = scene.getEngine(); const material = subMesh.getMaterial(); if (!material || subMesh.verticesCount === 0 || this.customAllowRendering && !this.customAllowRendering(subMesh)) { continue; } const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); if (batch.mustReturn) { continue; } const hardwareInstancedRendering = engine2.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== void 0 || renderingMesh.hasThinInstances); const isTransparent = material.needAlphaBlendingForMesh(renderingMesh); isReady = this.isReady(subMesh, hardwareInstancedRendering, isTransparent) && isReady; } return isReady; }; const engine = this._scene.getEngine(); this._shadowMap.onBeforeBindObservable.add(() => { this._currentSceneUBO = this._scene.getSceneUniformBuffer(); engine._debugPushGroup?.(`shadow map generation for pass id ${engine.currentRenderPassId}`, 1); }); this._shadowMap.onBeforeRenderObservable.add((faceIndex) => { if (this._sceneUBOs) { this._scene.setSceneUniformBuffer(this._sceneUBOs[0]); } this._currentFaceIndex = faceIndex; if (this._filter === _ShadowGenerator.FILTER_PCF) { engine.setColorWrite(false); } this.getTransformMatrix(); this._scene.setTransformMatrix(this._viewMatrix, this._projectionMatrix); if (this._useUBO) { this._scene.getSceneUniformBuffer().unbindEffect(); this._scene.finalizeSceneUbo(); } }); this._shadowMap.onAfterUnbindObservable.add(() => { if (this._sceneUBOs) { this._scene.setSceneUniformBuffer(this._currentSceneUBO); } this._scene.updateTransformMatrix(); if (this._filter === _ShadowGenerator.FILTER_PCF) { engine.setColorWrite(true); } if (!this.useBlurExponentialShadowMap && !this.useBlurCloseExponentialShadowMap) { engine._debugPopGroup?.(1); return; } const shadowMap = this.getShadowMapForRendering(); if (shadowMap) { this._scene.postProcessManager.directRender(this._blurPostProcesses, shadowMap.renderTarget, true); engine.unBindFramebuffer(shadowMap.renderTarget, true); } engine._debugPopGroup?.(1); }); const clearZero = new Color4(0, 0, 0, 0); const clearOne = new Color4(1, 1, 1, 1); this._shadowMap.onClearObservable.add((engine2) => { if (this._filter === _ShadowGenerator.FILTER_PCF) { engine2.clear(clearOne, false, true, false); } else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) { engine2.clear(clearZero, true, true, false); } else { engine2.clear(clearOne, true, true, false); } }); this._shadowMap.onResizeObservable.add((rtt) => { this._storedUniqueId = this._shadowMap.uniqueId; this._mapSize = rtt.getRenderSize(); this._light._markMeshesAsLightDirty(); this.recreateShadowMap(); }); for (let i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) { this._shadowMap.setRenderingAutoClearDepthStencil(i, false); } } async _initShaderSourceAsync(forceGLSL = false) { const engine = this._scene.getEngine(); if (engine.isWebGPU && !forceGLSL && !_ShadowGenerator.ForceGLSL) { this._shaderLanguage = 1; await Promise.all([ Promise.resolve().then(() => (init_shadowMap_fragment(), shadowMap_fragment_exports)), Promise.resolve().then(() => (init_shadowMap_vertex(), shadowMap_vertex_exports)), Promise.resolve().then(() => (init_depthBoxBlur_fragment(), depthBoxBlur_fragment_exports)), Promise.resolve().then(() => (init_shadowMapFragmentSoftTransparentShadow(), shadowMapFragmentSoftTransparentShadow_exports)) ]); } else { await Promise.all([ Promise.resolve().then(() => (init_shadowMap_fragment2(), shadowMap_fragment_exports2)), Promise.resolve().then(() => (init_shadowMap_vertex2(), shadowMap_vertex_exports2)), Promise.resolve().then(() => (init_depthBoxBlur_fragment2(), depthBoxBlur_fragment_exports2)), Promise.resolve().then(() => (init_shadowMapFragmentSoftTransparentShadow2(), shadowMapFragmentSoftTransparentShadow_exports2)) ]); } this._shadersLoaded = true; } _initializeBlurRTTAndPostProcesses() { const engine = this._scene.getEngine(); const targetSize = this._mapSize / this.blurScale; if (!this.useKernelBlur || this.blurScale !== 1) { this._shadowMap2 = new RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType, void 0, void 0, false); this._shadowMap2.wrapU = Texture.CLAMP_ADDRESSMODE; this._shadowMap2.wrapV = Texture.CLAMP_ADDRESSMODE; this._shadowMap2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE); } if (this.useKernelBlur) { this._kernelBlurXPostprocess = new BlurPostProcess(this._light.name + "KernelBlurX", new Vector2(1, 0), this.blurKernel, 1, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType); this._kernelBlurXPostprocess.width = targetSize; this._kernelBlurXPostprocess.height = targetSize; this._kernelBlurXPostprocess.externalTextureSamplerBinding = true; this._kernelBlurXPostprocess.onApplyObservable.add((effect) => { effect.setTexture("textureSampler", this._shadowMap); }); this._kernelBlurYPostprocess = new BlurPostProcess(this._light.name + "KernelBlurY", new Vector2(0, 1), this.blurKernel, 1, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType); this._kernelBlurXPostprocess.autoClear = false; this._kernelBlurYPostprocess.autoClear = false; if (this._textureType === 0) { this._kernelBlurXPostprocess.packedFloat = true; this._kernelBlurYPostprocess.packedFloat = true; } this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess]; } else { this._boxBlurPostprocess = new PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType, void 0, void 0, void 0, void 0, this._shaderLanguage); this._boxBlurPostprocess.externalTextureSamplerBinding = true; this._boxBlurPostprocess.onApplyObservable.add((effect) => { effect.setFloat2("screenSize", targetSize, targetSize); effect.setTexture("textureSampler", this._shadowMap); }); this._boxBlurPostprocess.autoClear = false; this._blurPostProcesses = [this._boxBlurPostprocess]; } } _renderForShadowMap(opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) { let index; if (depthOnlySubMeshes.length) { for (index = 0; index < depthOnlySubMeshes.length; index++) { this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]); } } 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; } } } // eslint-disable-next-line @typescript-eslint/no-unused-vars _bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, mesh) { effect.setMatrix("viewProjection", this.getTransformMatrix()); } _renderSubMeshForShadowMap(subMesh, isTransparent = false) { const renderingMesh = subMesh.getRenderingMesh(); const effectiveMesh = subMesh.getEffectiveMesh(); const scene = this._scene; const engine = scene.getEngine(); const material = subMesh.getMaterial(); effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; if (!material || subMesh.verticesCount === 0 || subMesh._renderId === scene.getRenderId()) { return; } const useRHS = scene.useRightHandedSystem; const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0; let sideOrientation = material._getEffectiveOrientation(renderingMesh); if (detNeg && !useRHS || !detNeg && useRHS) { sideOrientation = sideOrientation === 0 ? 1 : 0; } const reverseSideOrientation = sideOrientation === 0; engine.setState(material.backFaceCulling, void 0, void 0, reverseSideOrientation, material.cullBackFaces); const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); if (batch.mustReturn) { return; } const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== void 0 || renderingMesh.hasThinInstances); if (this.customAllowRendering && !this.customAllowRendering(subMesh)) { return; } if (this.isReady(subMesh, hardwareInstancedRendering, isTransparent)) { subMesh._renderId = scene.getRenderId(); const shadowDepthWrapper = material.shadowDepthWrapper; const drawWrapper = shadowDepthWrapper?.getEffect(subMesh, this, engine.currentRenderPassId) ?? subMesh._getDrawWrapper(); const effect = DrawWrapper.GetEffect(drawWrapper); engine.enableEffect(drawWrapper); if (!hardwareInstancedRendering) { renderingMesh._bind(subMesh, effect, material.fillMode); } this.getTransformMatrix(); effect.setFloat3("biasAndScaleSM", this.bias, this.normalBias, this.depthScale); if (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT) { effect.setVector3("lightDataSM", this._cachedDirection); } else { effect.setVector3("lightDataSM", this._cachedPosition); } const camera = this._getCamera(); effect.setFloat2("depthValuesSM", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera)); if (isTransparent && this.enableSoftTransparentShadow) { effect.setFloat2("softTransparentShadowSM", effectiveMesh.visibility * material.alpha, this._opacityTexture?.getAlphaFromRGB ? 1 : 0); } if (shadowDepthWrapper) { subMesh._setMainDrawWrapperOverride(drawWrapper); if (shadowDepthWrapper.standalone) { shadowDepthWrapper.baseMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh); } else { material.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh); } subMesh._setMainDrawWrapperOverride(null); } else { if (this._opacityTexture) { effect.setTexture("diffuseSampler", this._opacityTexture); effect.setMatrix("diffuseMatrix", this._opacityTexture.getTextureMatrix() || this._defaultTextureMatrix); } if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) { const skeleton = renderingMesh.skeleton; if (skeleton.isUsingTextureForMatrices) { const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh); if (!boneTexture) { return; } effect.setTexture("boneSampler", boneTexture); effect.setFloat("boneTextureWidth", 4 * (skeleton.bones.length + 1)); } else { effect.setMatrices("mBones", skeleton.getTransformMatrices(renderingMesh)); } } BindMorphTargetParameters(renderingMesh, effect); if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { renderingMesh.morphTargetManager._bind(effect); } const bvaManager = subMesh.getMesh().bakedVertexAnimationManager; if (bvaManager && bvaManager.isEnabled) { bvaManager.bind(effect, hardwareInstancedRendering); } BindClipPlane(effect, material, scene); } if (!this._useUBO && !shadowDepthWrapper) { this._bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect, effectiveMesh); } BindSceneUniformBuffer(effect, this._scene.getSceneUniformBuffer()); this._scene.getSceneUniformBuffer().bindUniformBuffer(); const world = effectiveMesh.getWorldMatrix(); if (hardwareInstancedRendering) { effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); effectiveMesh.transferToEffect(world); } if (this.forceBackFacesOnly) { engine.setState(true, 0, false, true, material.cullBackFaces); } this.onBeforeShadowMapRenderMeshObservable.notifyObservers(renderingMesh); this.onBeforeShadowMapRenderObservable.notifyObservers(effect); renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, worldOverride) => { if (effectiveMesh !== renderingMesh && !isInstance) { renderingMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); renderingMesh.transferToEffect(worldOverride); } else { effectiveMesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); effectiveMesh.transferToEffect(isInstance ? worldOverride : world); } }); if (this.forceBackFacesOnly) { engine.setState(true, 0, false, false, material.cullBackFaces); } this.onAfterShadowMapRenderObservable.notifyObservers(effect); this.onAfterShadowMapRenderMeshObservable.notifyObservers(renderingMesh); } else { if (this._shadowMap) { this._shadowMap.resetRefreshCounter(); } } } _applyFilterValues() { if (!this._shadowMap) { return; } if (this.filter === _ShadowGenerator.FILTER_NONE || this.filter === _ShadowGenerator.FILTER_PCSS) { this._shadowMap.updateSamplingMode(Texture.NEAREST_SAMPLINGMODE); } else { this._shadowMap.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE); } } /** * Forces all the attached effect to compile to enable rendering only once ready vs. lazily 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 */ forceCompilation(onCompiled, options) { const localOptions = { useInstances: false, ...options }; const shadowMap = this.getShadowMap(); if (!shadowMap) { if (onCompiled) { onCompiled(this); } return; } const renderList = shadowMap.renderList; if (!renderList) { if (onCompiled) { onCompiled(this); } return; } const subMeshes = []; for (const mesh of renderList) { subMeshes.push(...mesh.subMeshes); } if (subMeshes.length === 0) { if (onCompiled) { onCompiled(this); } return; } let currentIndex = 0; const checkReady = /* @__PURE__ */ __name(() => { if (!this._scene || !this._scene.getEngine()) { return; } while (this.isReady(subMeshes[currentIndex], localOptions.useInstances, subMeshes[currentIndex].getMaterial()?.needAlphaBlendingForMesh(subMeshes[currentIndex].getMesh()) ?? false)) { currentIndex++; if (currentIndex >= subMeshes.length) { if (onCompiled) { onCompiled(this); } return; } } setTimeout(checkReady, 16); }, "checkReady"); checkReady(); } /** * Forces all the attached effect to compile to enable rendering only once ready vs. lazily compiling effects. * @param options Sets of optional options forcing the compilation with different modes * @returns A promise that resolves when the compilation completes */ async forceCompilationAsync(options) { return await new Promise((resolve) => { this.forceCompilation(() => { resolve(); }, options); }); } // eslint-disable-next-line @typescript-eslint/no-unused-vars _isReadyCustomDefines(defines, subMesh, useInstances) { } _prepareShadowDefines(subMesh, useInstances, defines, isTransparent) { defines.push("#define SM_LIGHTTYPE_" + this._light.getClassName().toUpperCase()); defines.push("#define SM_FLOAT " + (this._textureType !== 0 ? "1" : "0")); defines.push("#define SM_ESM " + (this.useExponentialShadowMap || this.useBlurExponentialShadowMap ? "1" : "0")); defines.push("#define SM_DEPTHTEXTURE " + (this.usePercentageCloserFiltering || this.useContactHardeningShadow ? "1" : "0")); const mesh = subMesh.getMesh(); defines.push("#define SM_NORMALBIAS " + (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind) ? "1" : "0")); defines.push("#define SM_DIRECTIONINLIGHTDATA " + (this.getLight().getTypeID() === Light.LIGHTTYPEID_DIRECTIONALLIGHT ? "1" : "0")); defines.push("#define SM_USEDISTANCE " + (this._light.needCube() ? "1" : "0")); defines.push("#define SM_SOFTTRANSPARENTSHADOW " + (this.enableSoftTransparentShadow && isTransparent ? "1" : "0")); this._isReadyCustomDefines(defines, subMesh, useInstances); return defines; } /** * Determine whether 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 whether will draw in the map using instances * @param isTransparent Indicates that isReady is called for a transparent subMesh * @returns true if ready otherwise, false */ isReady(subMesh, useInstances, isTransparent) { if (!this._shadersLoaded) { return false; } const material = subMesh.getMaterial(), shadowDepthWrapper = material?.shadowDepthWrapper; this._opacityTexture = null; if (!material) { return false; } const defines = []; this._prepareShadowDefines(subMesh, useInstances, defines, isTransparent); if (shadowDepthWrapper) { if (!shadowDepthWrapper.isReadyForSubMesh(subMesh, defines, this, useInstances, this._scene.getEngine().currentRenderPassId)) { return false; } } else { const subMeshEffect = subMesh._getDrawWrapper(void 0, true); let effect = subMeshEffect.effect; let cachedDefines = subMeshEffect.defines; const attribs = [VertexBuffer.PositionKind]; const mesh = subMesh.getMesh(); let useNormal = false; let uv1 = false; let uv2 = false; const color = false; if (this.normalBias && mesh.isVerticesDataPresent(VertexBuffer.NormalKind)) { attribs.push(VertexBuffer.NormalKind); defines.push("#define NORMAL"); useNormal = true; if (mesh.nonUniformScaling) { defines.push("#define NONUNIFORMSCALING"); } } const needAlphaTesting = material.needAlphaTestingForMesh(mesh); if (needAlphaTesting || material.needAlphaBlendingForMesh(mesh)) { if (this.useOpacityTextureForTransparentShadow) { this._opacityTexture = material.opacityTexture; } else { this._opacityTexture = material.getAlphaTestTexture(); } if (this._opacityTexture) { if (!this._opacityTexture.isReady()) { return false; } const alphaCutOff = material.alphaCutOff ?? _ShadowGenerator.DEFAULT_ALPHA_CUTOFF; defines.push("#define ALPHATEXTURE"); if (needAlphaTesting) { defines.push(`#define ALPHATESTVALUE ${alphaCutOff}${alphaCutOff % 1 === 0 ? "." : ""}`); } if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { attribs.push(VertexBuffer.UVKind); defines.push("#define UV1"); uv1 = true; } if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) { if (this._opacityTexture.coordinatesIndex === 1) { attribs.push(VertexBuffer.UV2Kind); defines.push("#define UV2"); uv2 = true; } } } } const fallbacks = new EffectFallbacks(); if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { attribs.push(VertexBuffer.MatricesIndicesKind); attribs.push(VertexBuffer.MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(VertexBuffer.MatricesIndicesExtraKind); attribs.push(VertexBuffer.MatricesWeightsExtraKind); } const 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"); } const numMorphInfluencers = mesh.morphTargetManager ? PrepareDefinesAndAttributesForMorphTargets( mesh.morphTargetManager, defines, attribs, mesh, true, // usePositionMorph useNormal, // useNormalMorph false, // useTangentMorph uv1, // useUVMorph uv2, // useUV2Morph color // useColorMorph ) : 0; PrepareStringDefinesForClipPlanes(material, this._scene, defines); if (useInstances) { defines.push("#define INSTANCES"); PushAttributesForInstances(attribs); if (subMesh.getRenderingMesh().hasThinInstances) { defines.push("#define THIN_INSTANCES"); } } if (this.customShaderOptions) { if (this.customShaderOptions.defines) { for (const define of this.customShaderOptions.defines) { if (defines.indexOf(define) === -1) { defines.push(define); } } } } const bvaManager = mesh.bakedVertexAnimationManager; if (bvaManager && bvaManager.isEnabled) { defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"); if (useInstances) { attribs.push("bakedVertexAnimationSettingsInstanced"); } } const join = defines.join("\n"); if (cachedDefines !== join) { cachedDefines = join; let shaderName = "shadowMap"; const uniforms = [ "world", "mBones", "viewProjection", "diffuseMatrix", "lightDataSM", "depthValuesSM", "biasAndScaleSM", "morphTargetInfluences", "morphTargetCount", "boneTextureWidth", "softTransparentShadowSM", "morphTargetTextureInfo", "morphTargetTextureIndices", "bakedVertexAnimationSettings", "bakedVertexAnimationTextureSizeInverted", "bakedVertexAnimationTime", "bakedVertexAnimationTexture" ]; const samplers = ["diffuseSampler", "boneSampler", "morphTargets", "bakedVertexAnimationTexture"]; const uniformBuffers = ["Scene", "Mesh"]; AddClipPlaneUniforms(uniforms); if (this.customShaderOptions) { shaderName = this.customShaderOptions.shaderName; if (this.customShaderOptions.attributes) { for (const attrib of this.customShaderOptions.attributes) { if (attribs.indexOf(attrib) === -1) { attribs.push(attrib); } } } if (this.customShaderOptions.uniforms) { for (const uniform of this.customShaderOptions.uniforms) { if (uniforms.indexOf(uniform) === -1) { uniforms.push(uniform); } } } if (this.customShaderOptions.samplers) { for (const sampler of this.customShaderOptions.samplers) { if (samplers.indexOf(sampler) === -1) { samplers.push(sampler); } } } } const engine = this._scene.getEngine(); effect = engine.createEffect(shaderName, { attributes: attribs, uniformsNames: uniforms, uniformBuffersNames: uniformBuffers, samplers, defines: join, fallbacks, onCompiled: null, onError: null, indexParameters: { maxSimultaneousMorphTargets: numMorphInfluencers }, shaderLanguage: this._shaderLanguage }, engine); subMeshEffect.setEffect(effect, cachedDefines); } if (!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 */ prepareDefines(defines, lightIndex) { const scene = this._scene; const 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 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 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 binding the information for */ bindShadowLight(lightIndex, effect) { const light = this._light; const scene = this._scene; if (!scene.shadowsEnabled || !light.shadowEnabled) { return; } const camera = this._getCamera(); const shadowMap = this.getShadowMap(); if (!shadowMap) { return; } if (!light.needCube()) { effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix()); } const shadowMapForRendering = this.getShadowMapForRendering(); if (this._filter === _ShadowGenerator.FILTER_PCF) { effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMapForRendering); 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("shadowTexture" + lightIndex, shadowMapForRendering); effect.setTexture("depthTexture" + lightIndex, shadowMapForRendering); light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex); } else { effect.setTexture("shadowTexture" + lightIndex, shadowMapForRendering); 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 view matrix used to render the shadow map. */ get viewMatrix() { return this._viewMatrix; } /** * Gets the projection matrix used to render the shadow map. */ get projectionMatrix() { return this._projectionMatrix; } /** * Gets the transformation matrix used to project the meshes into the map from the light point of view. * (eq to shadow projection matrix * light transform matrix) * @returns The transform matrix used to create the shadow map */ getTransformMatrix() { const scene = this._scene; if (this._currentRenderId === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) { return this._transformMatrix; } this._currentRenderId = scene.getRenderId(); this._currentFaceIndexCache = this._currentFaceIndex; let lightPosition = this._light.position; if (this._light.computeTransformedInformation()) { lightPosition = this._light.transformedPosition; } Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection); if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1) { this._lightDirection.z = 1e-13; } 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); Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), Vector3.Up(), this._viewMatrix); const shadowMap = this.getShadowMap(); if (shadowMap) { const 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. */ recreateShadowMap() { const shadowMap = this._shadowMap; if (!shadowMap) { return; } const renderList = shadowMap.renderList; this._disposeRTTandPostProcesses(); this._initializeGenerator(); this.filter = this._filter; this._applyFilterValues(); if (renderList) { if (!this._shadowMap.renderList) { this._shadowMap.renderList = []; } for (const mesh of renderList) { this._shadowMap.renderList.push(mesh); } } else { this._shadowMap.renderList = null; } } _disposeBlurPostProcesses() { 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 = []; } _disposeRTTandPostProcesses() { if (this._shadowMap) { this._shadowMap.dispose(); this._shadowMap = null; } this._disposeBlurPostProcesses(); } _disposeSceneUBOs() { if (this._sceneUBOs) { for (const ubo of this._sceneUBOs) { ubo.dispose(); } this._sceneUBOs = []; } } /** * Disposes the ShadowGenerator. * Returns nothing. */ dispose() { this._disposeRTTandPostProcesses(); this._disposeSceneUBOs(); if (this._light) { if (this._light._shadowGenerators) { const iterator = this._light._shadowGenerators.entries(); for (let entry = iterator.next(); entry.done !== true; entry = iterator.next()) { const [camera, shadowGenerator] = entry.value; if (shadowGenerator === this) { this._light._shadowGenerators.delete(camera); } } if (this._light._shadowGenerators.size === 0) { this._light._shadowGenerators = 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 */ serialize() { const serializationObject = {}; const shadowMap = this.getShadowMap(); if (!shadowMap) { return serializationObject; } serializationObject.className = this.getClassName(); serializationObject.lightId = this._light.id; serializationObject.cameraId = this._camera?.id; serializationObject.id = this.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 (let meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) { const 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 */ static Parse(parsedShadowGenerator, scene, constr) { const light = scene.getLightById(parsedShadowGenerator.lightId); const camera = parsedShadowGenerator.cameraId !== void 0 ? scene.getCameraById(parsedShadowGenerator.cameraId) : null; const shadowGenerator = constr ? constr(parsedShadowGenerator.mapSize, light, camera) : new _ShadowGenerator(parsedShadowGenerator.mapSize, light, void 0, camera); const shadowMap = shadowGenerator.getShadowMap(); if (parsedShadowGenerator.renderList.length && shadowMap) { const renderSet = new Set(parsedShadowGenerator.renderList); let renderList = shadowMap.renderList; if (!renderList) { renderList = shadowMap.renderList = []; } const meshes = scene.meshes; for (const mesh of meshes) { if (renderSet.has(mesh.id)) { renderList.push(mesh); } } } if (parsedShadowGenerator.id !== void 0) { shadowGenerator.id = parsedShadowGenerator.id; } shadowGenerator.forceBackFacesOnly = !!parsedShadowGenerator.forceBackFacesOnly; if (parsedShadowGenerator.darkness !== void 0) { shadowGenerator.setDarkness(parsedShadowGenerator.darkness); } if (parsedShadowGenerator.transparencyShadow) { shadowGenerator.setTransparencyShadow(true); } if (parsedShadowGenerator.frustumEdgeFalloff !== void 0) { shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff; } if (parsedShadowGenerator.bias !== void 0) { shadowGenerator.bias = parsedShadowGenerator.bias; } if (parsedShadowGenerator.normalBias !== void 0) { 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 if (parsedShadowGenerator.useVarianceShadowMap) { shadowGenerator.useExponentialShadowMap = true; } else if (parsedShadowGenerator.useBlurVarianceShadowMap) { shadowGenerator.useBlurExponentialShadowMap = true; } if (parsedShadowGenerator.contactHardeningLightSizeUVRatio !== void 0) { shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio; } if (parsedShadowGenerator.filteringQuality !== void 0) { 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; } }; ShadowGenerator.CLASSNAME = "ShadowGenerator"; ShadowGenerator.ForceGLSL = false; ShadowGenerator.FILTER_NONE = 0; ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1; ShadowGenerator.FILTER_POISSONSAMPLING = 2; ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3; ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4; ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5; ShadowGenerator.FILTER_PCF = 6; ShadowGenerator.FILTER_PCSS = 7; ShadowGenerator.QUALITY_HIGH = 0; ShadowGenerator.QUALITY_MEDIUM = 1; ShadowGenerator.QUALITY_LOW = 2; ShadowGenerator.DEFAULT_ALPHA_CUTOFF = 0.5; ShadowGenerator._SceneComponentInitialization = (_) => { throw _WarnImport("ShadowGeneratorSceneComponent"); }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Culling/boundingBox.js var BoundingBox; var init_boundingBox = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Culling/boundingBox.js"() { init_arrayTools(); init_math_vector(); init_math_constants(); BoundingBox = class _BoundingBox { static { __name(this, "BoundingBox"); } /** * 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 */ constructor(min, max, worldMatrix) { this.vectors = BuildArray(8, Vector3.Zero); this.center = Vector3.Zero(); this.centerWorld = Vector3.Zero(); this.extendSize = Vector3.Zero(); this.extendSizeWorld = Vector3.Zero(); this.directions = BuildArray(3, Vector3.Zero); this.vectorsWorld = BuildArray(8, Vector3.Zero); this.minimumWorld = Vector3.Zero(); this.maximumWorld = Vector3.Zero(); this.minimum = Vector3.Zero(); this.maximum = Vector3.Zero(); this._drawWrapperFront = null; this._drawWrapperBack = null; 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 */ reConstruct(min, max, worldMatrix) { const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; const 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); max.addToRef(min, this.center).scaleInPlace(0.5); max.subtractToRef(min, this.extendSize).scaleInPlace(0.5); this._worldMatrix = worldMatrix || 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 */ scale(factor) { const tmpVectors = _BoundingBox._TmpVector3; const diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]); const len = diff.length(); diff.normalizeFromLength(len); const distance = len * factor; const newRadius = diff.scaleInPlace(distance * 0.5); const min = this.center.subtractToRef(newRadius, tmpVectors[1]); const 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 */ getWorldMatrix() { return this._worldMatrix; } /** * @internal */ _update(world) { const minWorld = this.minimumWorld; const maxWorld = this.maximumWorld; const directions = this.directions; const vectorsWorld = this.vectorsWorld; const vectors = this.vectors; if (!world.isIdentity()) { minWorld.setAll(Number.MAX_VALUE); maxWorld.setAll(-Number.MAX_VALUE); for (let index = 0; index < 8; ++index) { const v = vectorsWorld[index]; Vector3.TransformCoordinatesToRef(vectors[index], world, v); minWorld.minimizeInPlace(v); maxWorld.maximizeInPlace(v); } 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 (let index = 0; index < 8; ++index) { vectorsWorld[index].copyFrom(vectors[index]); } this.extendSizeWorld.copyFrom(this.extendSize); this.centerWorld.copyFrom(this.center); } Vector3.FromArrayToRef(world.m, 0, directions[0]); Vector3.FromArrayToRef(world.m, 4, directions[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 */ isInFrustum(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 */ isCompletelyInFrustum(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 */ intersectsPoint(point) { const min = this.minimumWorld; const max = this.maximumWorld; const minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z; const pointX = point.x, pointY = point.y, pointZ = point.z; const delta = -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 */ intersectsSphere(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 */ intersectsMinMax(min, max) { const myMin = this.minimumWorld; const myMax = this.maximumWorld; const myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z; const 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; } /** * Disposes the resources of the class */ dispose() { this._drawWrapperFront?.dispose(); this._drawWrapperBack?.dispose(); } // 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 */ static Intersects(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 */ static IntersectsSphere(minPoint, maxPoint, sphereCenter, sphereRadius) { const vector = _BoundingBox._TmpVector3[0]; Vector3.ClampToRef(sphereCenter, minPoint, maxPoint, vector); const num = 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 * @returns true if there is an inclusion */ static IsCompletelyInFrustum(boundingVectors, frustumPlanes) { for (let p = 0; p < 6; ++p) { const frustumPlane = frustumPlanes[p]; for (let 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 * @returns true if there is an intersection */ static IsInFrustum(boundingVectors, frustumPlanes) { for (let p = 0; p < 6; ++p) { let canReturnFalse = true; const frustumPlane = frustumPlanes[p]; for (let i = 0; i < 8; ++i) { if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) { canReturnFalse = false; break; } } if (canReturnFalse) { return false; } } return true; } }; BoundingBox._TmpVector3 = BuildArray(3, Vector3.Zero); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Culling/boundingSphere.js var BoundingSphere; var init_boundingSphere = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Culling/boundingSphere.js"() { init_arrayTools(); init_math_vector(); BoundingSphere = class _BoundingSphere { static { __name(this, "BoundingSphere"); } /** * 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 */ constructor(min, max, worldMatrix) { this.center = Vector3.Zero(); this.centerWorld = Vector3.Zero(); this.minimum = Vector3.Zero(); this.maximum = 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 */ reConstruct(min, max, worldMatrix) { this.minimum.copyFrom(min); this.maximum.copyFrom(max); const distance = Vector3.Distance(min, max); max.addToRef(min, this.center).scaleInPlace(0.5); this.radius = distance * 0.5; this._update(worldMatrix || 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 */ scale(factor) { const newRadius = this.radius * factor; const tmpVectors = _BoundingSphere._TmpVector3; const tempRadiusVector = tmpVectors[0].setAll(newRadius); const min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]); const 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 */ getWorldMatrix() { return this._worldMatrix; } // Methods /** * @internal */ _update(worldMatrix) { if (!worldMatrix.isIdentity()) { Vector3.TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld); const tempVector = _BoundingSphere._TmpVector3[0]; Vector3.TransformNormalFromFloatsToRef(1, 1, 1, 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 */ isInFrustum(frustumPlanes) { const center = this.centerWorld; const radius = this.radiusWorld; for (let 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 */ isCenterInFrustum(frustumPlanes) { const center = this.centerWorld; for (let 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 */ intersectsPoint(point) { const squareDistance = Vector3.DistanceSquared(this.centerWorld, point); if (this.radiusWorld * this.radiusWorld < squareDistance) { return false; } return true; } // Statics /** * Checks if two sphere intersect * @param sphere0 sphere 0 * @param sphere1 sphere 1 * @returns true if the spheres intersect */ static Intersects(sphere0, sphere1) { const squareDistance = Vector3.DistanceSquared(sphere0.centerWorld, sphere1.centerWorld); const radiusSum = sphere0.radiusWorld + sphere1.radiusWorld; if (radiusSum * radiusSum < squareDistance) { return false; } return true; } /** * Creates a sphere from a center and a radius * @param center The center * @param radius radius * @param matrix Optional worldMatrix * @returns The sphere */ static CreateFromCenterAndRadius(center, radius, matrix) { this._TmpVector3[0].copyFrom(center); this._TmpVector3[1].copyFromFloats(0, 0, radius); this._TmpVector3[2].copyFrom(center); this._TmpVector3[0].addInPlace(this._TmpVector3[1]); this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]); const sphere = new _BoundingSphere(this._TmpVector3[0], this._TmpVector3[2]); if (matrix) { sphere._worldMatrix = matrix; } else { sphere._worldMatrix = Matrix.Identity(); } return sphere; } }; BoundingSphere._TmpVector3 = BuildArray(3, Vector3.Zero); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Culling/boundingInfo.js var _Result0, _Result1, ComputeBoxExtents, AxisOverlap, BoundingInfo; var init_boundingInfo = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Culling/boundingInfo.js"() { init_arrayTools(); init_math_vector(); init_boundingBox(); init_boundingSphere(); _Result0 = { min: 0, max: 0 }; _Result1 = { min: 0, max: 0 }; ComputeBoxExtents = /* @__PURE__ */ __name((axis, box, result) => { const p = Vector3.Dot(box.centerWorld, axis); const r0 = Math.abs(Vector3.Dot(box.directions[0], axis)) * box.extendSize.x; const r1 = Math.abs(Vector3.Dot(box.directions[1], axis)) * box.extendSize.y; const r2 = Math.abs(Vector3.Dot(box.directions[2], axis)) * box.extendSize.z; const r = r0 + r1 + r2; result.min = p - r; result.max = p + r; }, "ComputeBoxExtents"); AxisOverlap = /* @__PURE__ */ __name((axis, box0, box1) => { ComputeBoxExtents(axis, box0, _Result0); ComputeBoxExtents(axis, box1, _Result1); return !(_Result0.min > _Result1.max || _Result1.min > _Result0.max); }, "AxisOverlap"); BoundingInfo = class _BoundingInfo { static { __name(this, "BoundingInfo"); } /** * 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 */ constructor(minimum, maximum, worldMatrix) { this._isLocked = false; this.boundingBox = new BoundingBox(minimum, maximum, worldMatrix); this.boundingSphere = new 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 */ reConstruct(min, max, worldMatrix) { this.boundingBox.reConstruct(min, max, worldMatrix); this.boundingSphere.reConstruct(min, max, worldMatrix); } /** * min vector of the bounding box/sphere */ get minimum() { return this.boundingBox.minimum; } /** * max vector of the bounding box/sphere */ get maximum() { return this.boundingBox.maximum; } /** * If the info is locked and won't be updated to avoid perf overhead */ get isLocked() { return this._isLocked; } set isLocked(value) { this._isLocked = value; } // Methods /** * Updates the bounding sphere and box * @param world world matrix to be used to update */ update(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 */ centerOn(center, extend) { const minimum = _BoundingInfo._TmpVector3[0].copyFrom(center).subtractInPlace(extend); const 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; } /** * Grows the bounding info to include the given point. * @param point The point that will be included in the current bounding info (in local space) * @returns the current bounding info */ encapsulate(point) { const minimum = Vector3.Minimize(this.minimum, point); const maximum = Vector3.Maximize(this.maximum, point); this.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix()); return this; } /** * Grows the bounding info to encapsulate the given bounding info. * @param toEncapsulate The bounding info that will be encapsulated in the current bounding info * @returns the current bounding info */ encapsulateBoundingInfo(toEncapsulate) { const invw = TmpVectors.Matrix[0]; this.boundingBox.getWorldMatrix().invertToRef(invw); const v = TmpVectors.Vector3[0]; Vector3.TransformCoordinatesToRef(toEncapsulate.boundingBox.minimumWorld, invw, v); this.encapsulate(v); Vector3.TransformCoordinatesToRef(toEncapsulate.boundingBox.maximumWorld, invw, v); this.encapsulate(v); 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 */ scale(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) * The different strategies available are: * * BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD most accurate but slower @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_STANDARD * * BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY faster but less accurate @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY * * BABYLON.AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION can be faster if always visible @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_OPTIMISTIC_INCLUSION * * BABYLON.AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY can be faster if always visible @see https://doc.babylonjs.com/typedoc/classes/BABYLON.AbstractMesh#CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY * @returns true if the bounding info is in the frustum planes */ isInFrustum(frustumPlanes, strategy = 0) { const inclusionTest = strategy === 2 || strategy === 3; if (inclusionTest) { if (this.boundingSphere.isCenterInFrustum(frustumPlanes)) { return true; } } if (!this.boundingSphere.isInFrustum(frustumPlanes)) { return false; } const bSphereOnlyTest = strategy === 1 || strategy === 3; if (bSphereOnlyTest) { return true; } return this.boundingBox.isInFrustum(frustumPlanes); } /** * Gets the world distance between the min and max points of the bounding box */ get diagonalLength() { const boundingBox = this.boundingBox; const diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, _BoundingInfo._TmpVector3[0]); return diag.length(); } /** * Checks if a cullable object (mesh...) is in the camera frustum * Unlike isInFrustum this checks the full bounding box * @param frustumPlanes Camera near/planes * @returns true if the object is in frustum otherwise false */ isCompletelyInFrustum(frustumPlanes) { return this.boundingBox.isCompletelyInFrustum(frustumPlanes); } /** * @internal */ _checkCollision(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/features/featuresDeepDive/mesh/interactions/mesh_intersect * @param point the point to check intersection with * @returns if the point intersects */ intersectsPoint(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/features/featuresDeepDive/mesh/interactions/mesh_intersect * @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 */ intersects(boundingInfo, precise) { if (!BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) { return false; } if (!BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) { return false; } if (!precise) { return true; } const box0 = this.boundingBox; const 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(Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1)) { return false; } if (!AxisOverlap(Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1)) { return false; } if (!AxisOverlap(Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1)) { return false; } if (!AxisOverlap(Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1)) { return false; } if (!AxisOverlap(Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1)) { return false; } if (!AxisOverlap(Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1)) { return false; } if (!AxisOverlap(Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1)) { return false; } if (!AxisOverlap(Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1)) { return false; } if (!AxisOverlap(Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1)) { return false; } return true; } }; BoundingInfo._TmpVector3 = BuildArray(2, Vector3.Zero); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesDeclaration.js var name83, shader83, instancesDeclarationWGSL; var init_instancesDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/instancesDeclaration.js"() { init_shaderStore(); name83 = "instancesDeclaration"; shader83 = `#ifdef INSTANCES attribute world0 : vec4;attribute world1 : vec4;attribute world2 : vec4;attribute world3 : vec4; #ifdef INSTANCESCOLOR attribute instanceColor : vec4; #endif #if defined(THIN_INSTANCES) && !defined(WORLD_UBO) uniform world : mat4x4; #endif #if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) attribute previousWorld0 : vec4;attribute previousWorld1 : vec4;attribute previousWorld2 : vec4;attribute previousWorld3 : vec4; #ifdef THIN_INSTANCES uniform previousWorld : mat4x4; #endif #endif #else #if !defined(WORLD_UBO) uniform world : mat4x4; #endif #if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) uniform previousWorld : mat4x4; #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name83]) { ShaderStore.IncludesShadersStoreWGSL[name83] = shader83; } instancesDeclarationWGSL = { name: name83, shader: shader83 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/depth.vertex.js var depth_vertex_exports = {}; __export(depth_vertex_exports, { depthVertexShaderWGSL: () => depthVertexShaderWGSL }); var name84, shader84, depthVertexShaderWGSL; var init_depth_vertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/depth.vertex.js"() { init_shaderStore(); init_bonesDeclaration(); init_bakedVertexAnimationDeclaration(); init_morphTargetsVertexGlobalDeclaration(); init_morphTargetsVertexDeclaration(); init_clipPlaneVertexDeclaration(); init_instancesDeclaration(); init_morphTargetsVertexGlobal(); init_morphTargetsVertex(); init_instancesVertex(); init_bonesVertex(); init_bakedVertexAnimation(); init_clipPlaneVertex(); name84 = "depthVertexShader"; shader84 = `attribute position: vec3f; #include #include #include #include[0..maxSimultaneousMorphTargets] #include #include uniform viewProjection: mat4x4f;uniform depthValues: vec2f; #if defined(ALPHATEST) || defined(NEED_UV) varying vUV: vec2f;uniform diffuseMatrix: mat4x4f; #ifdef UV1 attribute uv: vec2f; #endif #ifdef UV2 attribute uv2: vec2f; #endif #endif #ifdef STORE_CAMERASPACE_Z uniform view: mat4x4f;varying vViewPos: vec4f; #endif varying vDepthMetric: f32; #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position; #ifdef UV1 var uvUpdated: vec2f=input.uv; #endif #ifdef UV2 var uv2Updated: vec2f=input.uv2; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0); #include vertexOutputs.position=uniforms.viewProjection*worldPos; #ifdef STORE_CAMERASPACE_Z vertexOutputs.vViewPos=uniforms.view*worldPos; #else #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.vDepthMetric=((-vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y)); #else vertexOutputs.vDepthMetric=((vertexOutputs.position.z+uniforms.depthValues.x)/(uniforms.depthValues.y)); #endif #endif #if defined(ALPHATEST) || defined(BASIC_RENDER) #ifdef UV1 vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef UV2 vertexOutputs.vUV= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy; #endif #endif } `; if (!ShaderStore.ShadersStoreWGSL[name84]) { ShaderStore.ShadersStoreWGSL[name84] = shader84; } depthVertexShaderWGSL = { name: name84, shader: shader84 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/depth.fragment.js var depth_fragment_exports = {}; __export(depth_fragment_exports, { depthPixelShaderWGSL: () => depthPixelShaderWGSL }); var name85, shader85, depthPixelShaderWGSL; var init_depth_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/depth.fragment.js"() { init_shaderStore(); init_clipPlaneFragmentDeclaration(); init_packingFunctions(); init_clipPlaneFragment(); name85 = "depthPixelShader"; shader85 = `#ifdef ALPHATEST varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #endif #include varying vDepthMetric: f32; #ifdef PACKED #include #endif #ifdef STORE_CAMERASPACE_Z varying vViewPos: vec4f; #endif #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #include #ifdef ALPHATEST if (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;} #endif #ifdef STORE_CAMERASPACE_Z #ifdef PACKED fragmentOutputs.color=pack(input.vViewPos.z); #else fragmentOutputs.color= vec4f(input.vViewPos.z,0.0,0.0,1.0); #endif #else #ifdef NONLINEARDEPTH #ifdef PACKED fragmentOutputs.color=pack(input.position.z); #else fragmentOutputs.color= vec4f(input.position.z,0.0,0.0,0.0); #endif #else #ifdef PACKED fragmentOutputs.color=pack(input.vDepthMetric); #else fragmentOutputs.color= vec4f(input.vDepthMetric,0.0,0.0,1.0); #endif #endif #endif }`; if (!ShaderStore.ShadersStoreWGSL[name85]) { ShaderStore.ShadersStoreWGSL[name85] = shader85; } depthPixelShaderWGSL = { name: name85, shader: shader85 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/instancesDeclaration.js var name86, shader86, instancesDeclaration; var init_instancesDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/instancesDeclaration.js"() { init_shaderStore(); name86 = "instancesDeclaration"; shader86 = `#ifdef INSTANCES attribute vec4 world0;attribute vec4 world1;attribute vec4 world2;attribute vec4 world3; #ifdef INSTANCESCOLOR attribute vec4 instanceColor; #endif #if defined(THIN_INSTANCES) && !defined(WORLD_UBO) uniform mat4 world; #endif #if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) attribute vec4 previousWorld0;attribute vec4 previousWorld1;attribute vec4 previousWorld2;attribute vec4 previousWorld3; #ifdef THIN_INSTANCES uniform mat4 previousWorld; #endif #endif #else #if !defined(WORLD_UBO) uniform mat4 world; #endif #if defined(VELOCITY) || defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) || defined(VELOCITY_LINEAR) uniform mat4 previousWorld; #endif #endif `; if (!ShaderStore.IncludesShadersStore[name86]) { ShaderStore.IncludesShadersStore[name86] = shader86; } instancesDeclaration = { name: name86, shader: shader86 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/pointCloudVertexDeclaration.js var name87, shader87, pointCloudVertexDeclaration; var init_pointCloudVertexDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/pointCloudVertexDeclaration.js"() { init_shaderStore(); name87 = "pointCloudVertexDeclaration"; shader87 = `#ifdef POINTSIZE uniform float pointSize; #endif `; if (!ShaderStore.IncludesShadersStore[name87]) { ShaderStore.IncludesShadersStore[name87] = shader87; } pointCloudVertexDeclaration = { name: name87, shader: shader87 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/pointCloudVertex.js var name88, shader88, pointCloudVertex; var init_pointCloudVertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/pointCloudVertex.js"() { init_shaderStore(); name88 = "pointCloudVertex"; shader88 = `#if defined(POINTSIZE) && !defined(WEBGPU) gl_PointSize=pointSize; #endif `; if (!ShaderStore.IncludesShadersStore[name88]) { ShaderStore.IncludesShadersStore[name88] = shader88; } pointCloudVertex = { name: name88, shader: shader88 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/depth.vertex.js var depth_vertex_exports2 = {}; __export(depth_vertex_exports2, { depthVertexShader: () => depthVertexShader }); var name89, shader89, depthVertexShader; var init_depth_vertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/depth.vertex.js"() { init_shaderStore(); init_bonesDeclaration2(); init_bakedVertexAnimationDeclaration2(); init_morphTargetsVertexGlobalDeclaration2(); init_morphTargetsVertexDeclaration2(); init_clipPlaneVertexDeclaration2(); init_instancesDeclaration2(); init_pointCloudVertexDeclaration(); init_morphTargetsVertexGlobal2(); init_morphTargetsVertex2(); init_instancesVertex2(); init_bonesVertex2(); init_bakedVertexAnimation2(); init_clipPlaneVertex2(); init_pointCloudVertex(); name89 = "depthVertexShader"; shader89 = `attribute vec3 position; #include #include #include #include[0..maxSimultaneousMorphTargets] #include #include uniform mat4 viewProjection;uniform vec2 depthValues; #if defined(ALPHATEST) || defined(NEED_UV) varying vec2 vUV;uniform mat4 diffuseMatrix; #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #endif #ifdef STORE_CAMERASPACE_Z uniform mat4 view;varying vec4 vViewPos; #endif #include varying float vDepthMetric; #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position; #ifdef UV1 vec2 uvUpdated=uv; #endif #ifdef UV2 vec2 uv2Updated=uv2; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); #include gl_Position=viewProjection*worldPos; #ifdef STORE_CAMERASPACE_Z vViewPos=view*worldPos; #else #ifdef USE_REVERSE_DEPTHBUFFER vDepthMetric=((-gl_Position.z+depthValues.x)/(depthValues.y)); #else vDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y)); #endif #endif #if defined(ALPHATEST) || defined(BASIC_RENDER) #ifdef UV1 vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef UV2 vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0)); #endif #endif #include } `; if (!ShaderStore.ShadersStore[name89]) { ShaderStore.ShadersStore[name89] = shader89; } depthVertexShader = { name: name89, shader: shader89 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/depth.fragment.js var depth_fragment_exports2 = {}; __export(depth_fragment_exports2, { depthPixelShader: () => depthPixelShader }); var name90, shader90, depthPixelShader; var init_depth_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/depth.fragment.js"() { init_shaderStore(); init_clipPlaneFragmentDeclaration2(); init_packingFunctions2(); init_clipPlaneFragment2(); name90 = "depthPixelShader"; shader90 = `#ifdef ALPHATEST varying vec2 vUV;uniform sampler2D diffuseSampler; #endif #include varying float vDepthMetric; #ifdef PACKED #include #endif #ifdef STORE_CAMERASPACE_Z varying vec4 vViewPos; #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #include #ifdef ALPHATEST if (texture2D(diffuseSampler,vUV).a<0.4) discard; #endif #ifdef STORE_CAMERASPACE_Z #ifdef PACKED gl_FragColor=pack(vViewPos.z); #else gl_FragColor=vec4(vViewPos.z,0.0,0.0,1.0); #endif #else #ifdef NONLINEARDEPTH #ifdef PACKED gl_FragColor=pack(gl_FragCoord.z); #else gl_FragColor=vec4(gl_FragCoord.z,0.0,0.0,0.0); #endif #else #ifdef PACKED gl_FragColor=pack(vDepthMetric); #else gl_FragColor=vec4(vDepthMetric,0.0,0.0,1.0); #endif #endif #endif }`; if (!ShaderStore.ShadersStore[name90]) { ShaderStore.ShadersStore[name90] = shader90; } depthPixelShader = { name: name90, shader: shader90 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Cameras/camera.js var Camera; var init_camera = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Cameras/camera.js"() { init_tslib_es6(); init_decorators(); init_smartArray(); init_tools(); init_observable(); init_math_vector(); init_node(); init_logger(); init_typeStore(); init_devTools(); init_math_viewport(); init_math_frustum(); init_decorators_serialization(); Camera = class _Camera extends Node { static { __name(this, "Camera"); } /** * Define the current local position of the camera in the scene */ get position() { return this._position; } set position(newPosition) { this._position = newPosition; } /** * The vector the camera should consider as up. * (default is Vector3(0, 1, 0) aka Vector3.Up()) */ set upVector(vec) { this._upVector = vec; } get upVector() { return this._upVector; } /** * The screen area in scene units squared */ get screenArea() { let x = 0; let y = 0; if (this.mode === _Camera.PERSPECTIVE_CAMERA) { if (this.fovMode === _Camera.FOVMODE_VERTICAL_FIXED) { y = this.minZ * 2 * Math.tan(this.fov / 2); x = this.getEngine().getAspectRatio(this) * y; } else { x = this.minZ * 2 * Math.tan(this.fov / 2); y = x / this.getEngine().getAspectRatio(this); } } else { const halfWidth = this.getEngine().getRenderWidth() / 2; const halfHeight = this.getEngine().getRenderHeight() / 2; x = (this.orthoRight ?? halfWidth) - (this.orthoLeft ?? -halfWidth); y = (this.orthoTop ?? halfHeight) - (this.orthoBottom ?? -halfHeight); } return x * y; } /** * Define the current limit on the left side for an orthographic camera * In scene unit */ set orthoLeft(value) { this._orthoLeft = value; for (const rigCamera of this._rigCameras) { rigCamera.orthoLeft = value; } } get orthoLeft() { return this._orthoLeft; } /** * Define the current limit on the right side for an orthographic camera * In scene unit */ set orthoRight(value) { this._orthoRight = value; for (const rigCamera of this._rigCameras) { rigCamera.orthoRight = value; } } get orthoRight() { return this._orthoRight; } /** * Define the current limit on the bottom side for an orthographic camera * In scene unit */ set orthoBottom(value) { this._orthoBottom = value; for (const rigCamera of this._rigCameras) { rigCamera.orthoBottom = value; } } get orthoBottom() { return this._orthoBottom; } /** * Define the current limit on the top side for an orthographic camera * In scene unit */ set orthoTop(value) { this._orthoTop = value; for (const rigCamera of this._rigCameras) { rigCamera.orthoTop = value; } } get orthoTop() { return this._orthoTop; } /** * Sets the camera's field of view in radians based on the focal length and sensor size. * @param value the focal length of the camera in mm. * @param sensorSize the sensor width size of the camera in mm. (default is 36mm, which is a full frame sensor) */ setFocalLength(value, sensorSize = 36) { this.fov = 2 * Math.atan(sensorSize / (2 * value)); } /** * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.ORTHOGRAPHIC_CAMERA) */ set mode(mode) { this._mode = mode; for (const rigCamera of this._rigCameras) { rigCamera.mode = mode; } } get mode() { return this._mode; } /** * Gets a flag indicating that the camera has moved in some way since the last call to Camera.update() */ get hasMoved() { return this._hasMoved; } /** * Instantiates a new camera object. * This should not be used directly but through the inherited cameras: ArcRotate, Free... * @see https://doc.babylonjs.com/features/featuresDeepDive/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 */ constructor(name260, position, scene, setActiveOnSceneIfNoneActive = true) { super(name260, scene, false); this._position = Vector3.Zero(); this._upVector = Vector3.Up(); this.oblique = null; this._orthoLeft = null; this._orthoRight = null; this._orthoBottom = null; this._orthoTop = null; this.fov = 0.8; this.projectionPlaneTilt = 0; this.minZ = 1; this.maxZ = 1e4; this.inertia = 0.9; this._mode = _Camera.PERSPECTIVE_CAMERA; this.isIntermediate = false; this.viewport = new Viewport(0, 0, 1, 1); this.layerMask = 268435455; this.fovMode = _Camera.FOVMODE_VERTICAL_FIXED; this.cameraRigMode = _Camera.RIG_MODE_NONE; this.customRenderTargets = []; this.outputRenderTarget = null; this.onViewMatrixChangedObservable = new Observable(); this.onProjectionMatrixChangedObservable = new Observable(); this.onAfterCheckInputsObservable = new Observable(); this.onRestoreStateObservable = new Observable(); this.isRigCamera = false; this._hasMoved = false; this._rigCameras = new Array(); this._skipRendering = false; this._projectionMatrix = new Matrix(); this._postProcesses = new Array(); this._activeMeshes = new SmartArray(256); this._globalPosition = Vector3.Zero(); this._computedViewMatrix = Matrix.Identity(); this._doNotComputeProjectionMatrix = false; this._transformMatrix = Matrix.Zero(); this._refreshFrustumPlanes = true; this._absoluteRotation = Quaternion.Identity(); this._isCamera = true; this._isLeftCamera = false; this._isRightCamera = false; this.getScene().addCamera(this); if (setActiveOnSceneIfNoneActive && !this.getScene().activeCamera) { this.getScene().activeCamera = this; } this.position = position; this.renderPassId = this.getScene().getEngine().createRenderPassId(`Camera ${name260}`); } /** * Store current camera state (fov, position, etc..) * @returns the camera */ storeState() { this._stateStored = true; this._storedFov = this.fov; return this; } /** * Returns true if a state has been stored by calling storeState method. * @returns true if state has been stored. */ hasStateStored() { return !!this._stateStored; } /** * Restores the camera state values if it has been stored. You must call storeState() first * @returns true if restored and false otherwise */ _restoreStateValues() { 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 */ restoreState() { if (this._restoreStateValues()) { this.onRestoreStateObservable.notifyObservers(this); return true; } return false; } /** * Gets the class name of the camera. * @returns the class name */ getClassName() { return "Camera"; } /** * Gets a string representation of the camera useful for debug purpose. * @param fullDetails Defines that a more verbose level of logging is required * @returns the string representation */ toString(fullDetails) { let ret = "Name: " + this.name; ret += ", type: " + this.getClassName(); if (this.animations) { for (let i = 0; i < this.animations.length; i++) { ret += ", animation[0]: " + this.animations[i].toString(fullDetails); } } return ret; } /** * Automatically tilts the projection plane, using `projectionPlaneTilt`, to correct the perspective effect on vertical lines. */ applyVerticalCorrection() { const rot = this.absoluteRotation.toEulerAngles(); this.projectionPlaneTilt = this._scene.useRightHandedSystem ? -rot.x : rot.x; } /** * Gets the current world space position of the camera. */ get globalPosition() { return this._globalPosition; } /** * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame) * @returns the active meshe list */ getActiveMeshes() { 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 */ isActiveMesh(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) * @returns true if the camera is ready */ isReady(completeCheck = false) { if (completeCheck) { for (const pp of this._postProcesses) { if (pp && !pp.isReady()) { return false; } } } return super.isReady(completeCheck); } /** @internal */ _initCache() { super._initCache(); this._cache.position = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._cache.upVector = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._cache.mode = void 0; this._cache.minZ = void 0; this._cache.maxZ = void 0; this._cache.fov = void 0; this._cache.fovMode = void 0; this._cache.aspectRatio = void 0; this._cache.orthoLeft = void 0; this._cache.orthoRight = void 0; this._cache.orthoBottom = void 0; this._cache.orthoTop = void 0; this._cache.obliqueAngle = void 0; this._cache.obliqueLength = void 0; this._cache.obliqueOffset = void 0; this._cache.renderWidth = void 0; this._cache.renderHeight = void 0; } /** * @internal */ _updateCache(ignoreParentClass) { if (!ignoreParentClass) { super._updateCache(); } this._cache.position.copyFrom(this.position); this._cache.upVector.copyFrom(this.upVector); } /** @internal */ _isSynchronized() { return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix(); } /** @internal */ _isSynchronizedViewMatrix() { if (!super._isSynchronized()) { return false; } return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent(); } /** @internal */ _isSynchronizedProjectionMatrix() { let isSynchronized = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ; if (!isSynchronized) { return false; } const engine = this.getEngine(); if (this.mode === _Camera.PERSPECTIVE_CAMERA) { isSynchronized = this._cache.fov === this.fov && this._cache.fovMode === this.fovMode && this._cache.aspectRatio === engine.getAspectRatio(this) && this._cache.projectionPlaneTilt === this.projectionPlaneTilt; } else { isSynchronized = 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(); if (this.oblique) { isSynchronized = isSynchronized && this._cache.obliqueAngle === this.oblique.angle && this._cache.obliqueLength === this.oblique.length && this._cache.obliqueOffset === this.oblique.offset; } } return isSynchronized; } /** * Attach the input controls to a specific dom element to get the input from. * This function is here because typescript removes the typing of the last function. * @param _ignored defines an ignored parameter kept for backward compatibility. * @param _noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ attachControl(_ignored, _noPreventDefault) { } /** * Detach the current controls from the specified dom element. * This function is here because typescript removes the typing of the last function. * @param _ignored defines an ignored parameter kept for backward compatibility. */ detachControl(_ignored) { } /** * Update the camera state according to the different inputs gathered during the frame. */ update() { this._hasMoved = false; this._checkInputs(); if (this.cameraRigMode !== _Camera.RIG_MODE_NONE) { this._updateRigCameras(); } this.getViewMatrix(); this.getProjectionMatrix(); } /** @internal */ _checkInputs() { this.onAfterCheckInputsObservable.notifyObservers(this); } /** @internal */ get rigCameras() { return this._rigCameras; } /** * Gets the post process used by the rig cameras */ get rigPostProcess() { return this._rigPostProcess; } /** * Internal, gets the first post process. * @returns the first post process to be run on this camera. */ _getFirstPostProcess() { for (let ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) { if (this._postProcesses[ppIndex] !== null) { return this._postProcesses[ppIndex]; } } return null; } _cascadePostProcessesToRigCams() { const firstPostProcess = this._getFirstPostProcess(); if (firstPostProcess) { firstPostProcess.markTextureDirty(); } for (let i = 0, len = this._rigCameras.length; i < len; i++) { const cam = this._rigCameras[i]; const rigPostProcess = cam._rigPostProcess; if (rigPostProcess) { const isPass = rigPostProcess.getEffectName() === "pass"; if (isPass) { 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/features/featuresDeepDive/postProcesses/usePostProcesses#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 */ attachPostProcess(postProcess, insertAt = null) { if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) { 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(); if (this._scene.prePassRenderer) { this._scene.prePassRenderer.markAsDirty(); } return this._postProcesses.indexOf(postProcess); } /** * Detach a post process to the camera. * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/usePostProcesses#attach-postprocess * @param postProcess The post process to detach from the camera */ detachPostProcess(postProcess) { const idx = this._postProcesses.indexOf(postProcess); if (idx !== -1) { this._postProcesses[idx] = null; } if (this._scene.prePassRenderer) { this._scene.prePassRenderer.markAsDirty(); } this._cascadePostProcessesToRigCams(); } /** * Gets the current world matrix of the camera * @returns the world matrix */ getWorldMatrix() { if (this._isSynchronizedViewMatrix()) { return this._worldMatrix; } this.getViewMatrix(); return this._worldMatrix; } /** @internal */ _getViewMatrix() { return 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 */ getViewMatrix(force) { if (!force && this._isSynchronizedViewMatrix()) { return this._computedViewMatrix; } this._hasMoved = true; 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); } 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 */ freezeProjectionMatrix(projection) { this._doNotComputeProjectionMatrix = true; if (projection !== void 0) { this._projectionMatrix = projection; } } /** * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix. */ unfreezeProjectionMatrix() { 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 */ getProjectionMatrix(force) { if (this._doNotComputeProjectionMatrix || !force && this._isSynchronizedProjectionMatrix()) { return this._projectionMatrix; } this._cache.mode = this.mode; this._cache.minZ = this.minZ; this._cache.maxZ = this.maxZ; this._refreshFrustumPlanes = true; const engine = this.getEngine(); const scene = this.getScene(); const reverseDepth = engine.useReverseDepthBuffer; if (this.mode === _Camera.PERSPECTIVE_CAMERA) { this._cache.fov = this.fov; this._cache.fovMode = this.fovMode; this._cache.aspectRatio = engine.getAspectRatio(this); this._cache.projectionPlaneTilt = this.projectionPlaneTilt; if (this.minZ <= 0) { this.minZ = 0.1; } let getProjectionMatrix; if (scene.useRightHandedSystem) { getProjectionMatrix = Matrix.PerspectiveFovRHToRef; } else { getProjectionMatrix = Matrix.PerspectiveFovLHToRef; } getProjectionMatrix(this.fov, engine.getAspectRatio(this), reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, this.fovMode === _Camera.FOVMODE_VERTICAL_FIXED, engine.isNDCHalfZRange, this.projectionPlaneTilt, reverseDepth); } else { const halfWidth = engine.getRenderWidth() / 2; const halfHeight = engine.getRenderHeight() / 2; if (scene.useRightHandedSystem) { if (this.oblique) { Matrix.ObliqueOffCenterRHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this.oblique.length, this.oblique.angle, this._computeObliqueDistance(this.oblique.offset), this._projectionMatrix, engine.isNDCHalfZRange); } else { Matrix.OrthoOffCenterRHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, engine.isNDCHalfZRange); } } else { if (this.oblique) { Matrix.ObliqueOffCenterLHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this.oblique.length, this.oblique.angle, this._computeObliqueDistance(this.oblique.offset), this._projectionMatrix, engine.isNDCHalfZRange); } else { Matrix.OrthoOffCenterLHToRef(this.orthoLeft ?? -halfWidth, this.orthoRight ?? halfWidth, this.orthoBottom ?? -halfHeight, this.orthoTop ?? halfHeight, reverseDepth ? this.maxZ : this.minZ, reverseDepth ? this.minZ : this.maxZ, this._projectionMatrix, engine.isNDCHalfZRange); } } this._cache.orthoLeft = this.orthoLeft; this._cache.orthoRight = this.orthoRight; this._cache.orthoBottom = this.orthoBottom; this._cache.orthoTop = this.orthoTop; this._cache.obliqueAngle = this.oblique?.angle; this._cache.obliqueLength = this.oblique?.length; this._cache.obliqueOffset = this.oblique?.offset; 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 */ getTransformationMatrix() { this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix); return this._transformMatrix; } _computeObliqueDistance(offset) { const arcRotateCamera = this; const targetCamera = this; return (arcRotateCamera.radius || (targetCamera.target ? Vector3.Distance(this.position, targetCamera.target) : this.position.length())) + offset; } /** @internal */ _updateFrustumPlanes() { if (!this._refreshFrustumPlanes) { return; } this.getTransformationMatrix(); if (!this._frustumPlanes) { this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix); } else { 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 VR camera both eyes should be checked) (Default: false) * @returns true if the object is in frustum otherwise false */ isInFrustum(target, checkRigCameras = false) { this._updateFrustumPlanes(); if (checkRigCameras && this.rigCameras.length > 0) { let result = false; for (const cam of this.rigCameras) { 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 checks the full bounding box * @param target The object to check * @returns true if the object is in frustum otherwise false */ isCompletelyInFrustum(target) { this._updateFrustumPlanes(); return target.isCompletelyInFrustum(this._frustumPlanes); } // eslint-disable-next-line jsdoc/require-returns-check /** * 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 matrix is used to create a world space ray * @param origin Defines the start point of the ray which defaults to the camera position * @returns the forward ray */ // eslint-disable-next-line @typescript-eslint/no-unused-vars getForwardRay(length = 100, transform, origin) { throw _WarnImport("Ray"); } // eslint-disable-next-line jsdoc/require-returns-check /** * 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 matrix is used to create a world space ray * @param origin Defines the start point of the ray which defaults to the camera position * @returns the forward ray */ // eslint-disable-next-line @typescript-eslint/no-unused-vars getForwardRayToRef(refRay, length = 100, transform, origin) { throw _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) */ dispose(doNotRecurse, disposeMaterialAndTextures = false) { this.onViewMatrixChangedObservable.clear(); this.onProjectionMatrixChangedObservable.clear(); this.onAfterCheckInputsObservable.clear(); this.onRestoreStateObservable.clear(); if (this.inputs) { this.inputs.clear(); } this.getScene().stopAnimation(this); this.getScene().removeCamera(this); while (this._rigCameras.length > 0) { const camera = this._rigCameras.pop(); if (camera) { camera.dispose(); } } if (this._parentContainer) { const index = this._parentContainer.cameras.indexOf(this); if (index > -1) { this._parentContainer.cameras.splice(index, 1); } this._parentContainer = null; } if (this._rigPostProcess) { this._rigPostProcess.dispose(this); this._rigPostProcess = null; this._postProcesses.length = 0; } else if (this.cameraRigMode !== _Camera.RIG_MODE_NONE) { this._rigPostProcess = null; this._postProcesses.length = 0; } else { let i2 = this._postProcesses.length; while (--i2 >= 0) { const postProcess = this._postProcesses[i2]; if (postProcess) { postProcess.dispose(this); } } } let i = this.customRenderTargets.length; while (--i >= 0) { this.customRenderTargets[i].dispose(); } this.customRenderTargets.length = 0; this._activeMeshes.dispose(); this.getScene().getEngine().releaseRenderPassId(this.renderPassId); super.dispose(doNotRecurse, disposeMaterialAndTextures); } /** * Gets the left camera of a rig setup in case of Rigged Camera */ get isLeftCamera() { return this._isLeftCamera; } /** * Gets the right camera of a rig setup in case of Rigged Camera */ get isRightCamera() { return this._isRightCamera; } /** * Gets the left camera of a rig setup in case of Rigged Camera */ get leftCamera() { if (this._rigCameras.length < 1) { return null; } return this._rigCameras[0]; } /** * Gets the right camera of a rig setup in case of Rigged Camera */ get rightCamera() { if (this._rigCameras.length < 2) { return null; } return this._rigCameras[1]; } /** * Gets the left camera target of a rig setup in case of Rigged Camera * @returns the target position */ getLeftTarget() { 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 */ getRightTarget() { if (this._rigCameras.length < 2) { return null; } return this._rigCameras[1].getTarget(); } /** * @internal */ setCameraRigMode(mode, rigParams) { if (this.cameraRigMode === mode) { return; } while (this._rigCameras.length > 0) { const camera = this._rigCameras.pop(); if (camera) { camera.dispose(); } } this.cameraRigMode = mode; this._cameraRigParams = {}; this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637; this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637); if (this.cameraRigMode !== _Camera.RIG_MODE_NONE) { const leftCamera = this.createRigCamera(this.name + "_L", 0); if (leftCamera) { leftCamera._isLeftCamera = true; } const rightCamera = this.createRigCamera(this.name + "_R", 1); if (rightCamera) { rightCamera._isRightCamera = true; } if (leftCamera && rightCamera) { this._rigCameras.push(leftCamera); this._rigCameras.push(rightCamera); } } this._setRigMode(rigParams); this._cascadePostProcessesToRigCams(); this.update(); } // eslint-disable-next-line @typescript-eslint/no-unused-vars _setRigMode(rigParams) { } /** @internal */ _getVRProjectionMatrix() { Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix, true, this.getEngine().isNDCHalfZRange); this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix); return this._projectionMatrix; } /** * @internal */ setCameraRigParameter(name260, value) { if (!this._cameraRigParams) { this._cameraRigParams = {}; } this._cameraRigParams[name260] = value; if (name260 === "interaxialDistance") { this._cameraRigParams.stereoHalfAngle = Tools.ToRadians(value / 0.0637); } } /** * needs to be overridden by children so sub has required properties to be copied * @internal */ // eslint-disable-next-line @typescript-eslint/no-unused-vars createRigCamera(name260, cameraIndex) { return null; } /** * May need to be overridden by children * @internal */ _updateRigCameras() { for (let 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); } if (this.cameraRigMode === _Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) { this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport; } } /** @internal */ _setupInputs() { } /** * Serialiaze the camera setup to a json representation * @returns the JSON representation */ serialize() { const serializationObject = SerializationHelper.Serialize(this); serializationObject.uniqueId = this.uniqueId; serializationObject.type = this.getClassName(); if (this.parent) { this.parent._serializeAsParent(serializationObject); } if (this.inputs) { this.inputs.serialize(serializationObject); } SerializationHelper.AppendSerializedAnimations(this, serializationObject); serializationObject.ranges = this.serializeAnimationRanges(); serializationObject.isEnabled = this.isEnabled(); return serializationObject; } /** * Clones the current camera. * @param name The cloned camera name * @param newParent The cloned camera's new parent (none by default) * @returns the cloned camera */ clone(name260, newParent = null) { const camera = SerializationHelper.Clone(_Camera.GetConstructorFromName(this.getClassName(), name260, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this); camera.name = name260; camera.parent = newParent; this.onClonedObservable.notifyObservers(camera); return camera; } /** * Gets the direction of the camera relative to a given local axis. * @param localAxis Defines the reference axis to provide a relative direction. * @returns the direction */ getDirection(localAxis) { const result = Vector3.Zero(); this.getDirectionToRef(localAxis, result); return result; } /** * Returns the current camera absolute rotation */ get absoluteRotation() { this.getWorldMatrix().decompose(void 0, this._absoluteRotation); return this._absoluteRotation; } /** * 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 */ getDirectionToRef(localAxis, result) { 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 construct the camera */ // eslint-disable-next-line @typescript-eslint/naming-convention static GetConstructorFromName(type, name260, scene, interaxial_distance = 0, isStereoscopicSideBySide = true) { const constructorFunc = Node.Construct(type, name260, scene, { // eslint-disable-next-line @typescript-eslint/naming-convention interaxial_distance, isStereoscopicSideBySide }); if (constructorFunc) { return constructorFunc; } return () => _Camera._CreateDefaultParsedCamera(name260, scene); } /** * Compute the world matrix of the camera. * @returns the camera world matrix */ computeWorldMatrix() { 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 */ static Parse(parsedCamera, scene) { const type = parsedCamera.type; const construct = _Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide); const camera = SerializationHelper.Parse(construct, parsedCamera, scene); if (parsedCamera.parentId !== void 0) { camera._waitingParentId = parsedCamera.parentId; } if (parsedCamera.parentInstanceIndex !== void 0) { camera._waitingParentInstanceIndex = parsedCamera.parentInstanceIndex; } if (camera.inputs) { camera.inputs.parse(parsedCamera); camera._setupInputs(); } if (parsedCamera.upVector) { camera.upVector = Vector3.FromArray(parsedCamera.upVector); } if (camera.setPosition) { camera.position.copyFromFloats(0, 0, 0); camera.setPosition(Vector3.FromArray(parsedCamera.position)); } if (parsedCamera.target) { if (camera.setTarget) { camera.setTarget(Vector3.FromArray(parsedCamera.target)); } } if (parsedCamera.cameraRigMode) { const rigParams = parsedCamera.interaxial_distance ? { interaxialDistance: parsedCamera.interaxial_distance } : {}; camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams); } if (parsedCamera.animations) { for (let animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) { const parsedAnimation = parsedCamera.animations[animationIndex]; const internalClass = GetClass("BABYLON.Animation"); if (internalClass) { camera.animations.push(internalClass.Parse(parsedAnimation)); } } Node.ParseAnimationRanges(camera, parsedCamera, scene); } if (parsedCamera.autoAnimate) { scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1); } if (parsedCamera.isEnabled !== void 0) { camera.setEnabled(parsedCamera.isEnabled); } return camera; } /** @internal */ _calculateHandednessMultiplier() { let handednessMultiplier = this.getScene().useRightHandedSystem ? -1 : 1; if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) { handednessMultiplier *= -1; } return handednessMultiplier; } }; Camera._CreateDefaultParsedCamera = (name260, scene) => { throw _WarnImport("UniversalCamera"); }; Camera.PERSPECTIVE_CAMERA = 0; Camera.ORTHOGRAPHIC_CAMERA = 1; Camera.FOVMODE_VERTICAL_FIXED = 0; Camera.FOVMODE_HORIZONTAL_FIXED = 1; Camera.RIG_MODE_NONE = 0; Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10; Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11; Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12; Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13; Camera.RIG_MODE_STEREOSCOPIC_INTERLACED = 14; Camera.RIG_MODE_VR = 20; Camera.RIG_MODE_CUSTOM = 22; Camera.ForceAttachControlToAlwaysPreventDefault = false; __decorate([ serializeAsVector3("position") ], Camera.prototype, "_position", void 0); __decorate([ serializeAsVector3("upVector") ], Camera.prototype, "_upVector", void 0); __decorate([ serialize() ], Camera.prototype, "orthoLeft", null); __decorate([ serialize() ], Camera.prototype, "orthoRight", null); __decorate([ serialize() ], Camera.prototype, "orthoBottom", null); __decorate([ serialize() ], Camera.prototype, "orthoTop", null); __decorate([ serialize() ], Camera.prototype, "fov", void 0); __decorate([ serialize() ], Camera.prototype, "projectionPlaneTilt", void 0); __decorate([ serialize() ], Camera.prototype, "minZ", void 0); __decorate([ serialize() ], Camera.prototype, "maxZ", void 0); __decorate([ serialize() ], Camera.prototype, "inertia", void 0); __decorate([ serialize() ], Camera.prototype, "mode", null); __decorate([ serialize() ], Camera.prototype, "layerMask", void 0); __decorate([ serialize() ], Camera.prototype, "fovMode", void 0); __decorate([ serialize() ], Camera.prototype, "cameraRigMode", void 0); __decorate([ serialize() ], Camera.prototype, "interaxialDistance", void 0); __decorate([ serialize() ], Camera.prototype, "isStereoscopicSideBySide", void 0); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/depthRenderer.js var DepthRenderer; var init_depthRenderer = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/depthRenderer.js"() { init_math_color(); init_buffer(); init_texture(); init_renderTargetTexture(); init_camera(); init_depth_fragment2(); init_depth_vertex2(); init_devTools(); init_clipPlaneMaterialHelper(); init_materialHelper_functions(); init_effectFallbacks(); DepthRenderer = class _DepthRenderer { static { __name(this, "DepthRenderer"); } /** * Gets the shader language used in this material. */ get shaderLanguage() { return this._shaderLanguage; } /** * Sets a specific material to be used to render a mesh/a list of meshes by the depth renderer * @param mesh mesh or array of meshes * @param material material to use by the depth render when rendering the mesh(es). If undefined is passed, the specific material created by the depth renderer will be used. */ setMaterialForRendering(mesh, material) { this._depthMap.setMaterialForRendering(mesh, material); } /** * Instantiates a depth renderer * @param scene The scene the renderer belongs to * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT) * @param camera The camera to be used to render the depth map (default: scene's active camera) * @param storeNonLinearDepth Defines whether the depth is stored linearly like in Babylon Shadows or directly like glFragCoord.z * @param samplingMode The sampling mode to be used with the render target (Linear, Nearest...) (default: TRILINEAR_SAMPLINGMODE) * @param storeCameraSpaceZ Defines whether the depth stored is the Z coordinate in camera space. If true, storeNonLinearDepth has no effect. (Default: false) * @param name Name of the render target (default: DepthRenderer) * @param existingRenderTargetTexture An existing render target texture to use (default: undefined). If not provided, a new render target texture will be created. */ constructor(scene, type = 1, camera = null, storeNonLinearDepth = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, storeCameraSpaceZ = false, name260, existingRenderTargetTexture) { this._shaderLanguage = 0; this.enabled = true; this.forceDepthWriteTransparentMeshes = false; this.useOnlyInActiveCamera = false; this.reverseCulling = false; this._shadersLoaded = false; this._scene = scene; this._storeNonLinearDepth = storeNonLinearDepth; this._storeCameraSpaceZ = storeCameraSpaceZ; this.isPacked = type === 0; if (this.isPacked) { this.clearColor = new Color4(1, 1, 1, 1); } else { this.clearColor = new Color4(storeCameraSpaceZ ? 0 : 1, 0, 0, 1); } this._initShaderSourceAsync(); _DepthRenderer._SceneComponentInitialization(this._scene); const engine = scene.getEngine(); this._camera = camera; if (samplingMode !== Texture.NEAREST_SAMPLINGMODE) { if (type === 1 && !engine._caps.textureFloatLinearFiltering) { samplingMode = Texture.NEAREST_SAMPLINGMODE; } if (type === 2 && !engine._caps.textureHalfFloatLinearFiltering) { samplingMode = Texture.NEAREST_SAMPLINGMODE; } } const format = this.isPacked || !engine._features.supportExtendedTextureFormats ? 5 : 6; this._depthMap = existingRenderTargetTexture ?? new RenderTargetTexture(name260 ?? "DepthRenderer", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type, false, samplingMode, void 0, void 0, void 0, format); this._depthMap.wrapU = Texture.CLAMP_ADDRESSMODE; this._depthMap.wrapV = Texture.CLAMP_ADDRESSMODE; this._depthMap.refreshRate = 1; this._depthMap.renderParticles = false; this._depthMap.renderList = null; this._depthMap.noPrePassRenderer = true; this._depthMap.activeCamera = this._camera; this._depthMap.ignoreCameraViewport = true; this._depthMap.useCameraPostProcesses = false; this._depthMap.onClearObservable.add((engine2) => { engine2.clear(this.clearColor, true, true, true); }); this._depthMap.onBeforeBindObservable.add(() => { engine._debugPushGroup?.("depth renderer", 1); }); this._depthMap.onAfterUnbindObservable.add(() => { engine._debugPopGroup?.(1); }); this._depthMap.customIsReadyFunction = (mesh, refreshRate, preWarm) => { if ((preWarm || refreshRate === 0) && mesh.subMeshes) { for (let i = 0; i < mesh.subMeshes.length; ++i) { const subMesh = mesh.subMeshes[i]; const renderingMesh = subMesh.getRenderingMesh(); const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== void 0 || renderingMesh.hasThinInstances); if (!this.isReady(subMesh, hardwareInstancedRendering)) { return false; } } } return true; }; const renderSubMesh = /* @__PURE__ */ __name((subMesh) => { const renderingMesh = subMesh.getRenderingMesh(); const effectiveMesh = subMesh.getEffectiveMesh(); const scene2 = this._scene; const engine2 = scene2.getEngine(); const material = subMesh.getMaterial(); effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; if (!material || effectiveMesh.infiniteDistance || material.disableDepthWrite || subMesh.verticesCount === 0 || subMesh._renderId === scene2.getRenderId()) { return; } const detNeg = effectiveMesh._getWorldMatrixDeterminant() < 0; let sideOrientation = material._getEffectiveOrientation(renderingMesh); if (detNeg) { sideOrientation = sideOrientation === 0 ? 1 : 0; } const reverseSideOrientation = sideOrientation === 0; engine2.setState(material.backFaceCulling, 0, false, reverseSideOrientation, this.reverseCulling ? !material.cullBackFaces : material.cullBackFaces); const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); if (batch.mustReturn) { return; } const hardwareInstancedRendering = engine2.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== void 0 || renderingMesh.hasThinInstances); const camera2 = this._camera || scene2.activeCamera; if (this.isReady(subMesh, hardwareInstancedRendering) && camera2) { subMesh._renderId = scene2.getRenderId(); const renderingMaterial = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine2.currentRenderPassId]; let drawWrapper = subMesh._getDrawWrapper(); if (!drawWrapper && renderingMaterial) { drawWrapper = renderingMaterial._getDrawWrapper(); } const cameraIsOrtho = camera2.mode === Camera.ORTHOGRAPHIC_CAMERA; if (!drawWrapper) { return; } const effect = drawWrapper.effect; engine2.enableEffect(drawWrapper); if (!hardwareInstancedRendering) { renderingMesh._bind(subMesh, effect, material.fillMode); } if (!renderingMaterial) { effect.setMatrix("viewProjection", scene2.getTransformMatrix()); effect.setMatrix("world", effectiveMesh.getWorldMatrix()); if (this._storeCameraSpaceZ) { effect.setMatrix("view", scene2.getViewMatrix()); } } else { renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh); } let minZ, maxZ; if (cameraIsOrtho) { minZ = !engine2.useReverseDepthBuffer && engine2.isNDCHalfZRange ? 0 : 1; maxZ = engine2.useReverseDepthBuffer && engine2.isNDCHalfZRange ? 0 : 1; } else { minZ = engine2.useReverseDepthBuffer && engine2.isNDCHalfZRange ? camera2.minZ : engine2.isNDCHalfZRange ? 0 : camera2.minZ; maxZ = engine2.useReverseDepthBuffer && engine2.isNDCHalfZRange ? 0 : camera2.maxZ; } effect.setFloat2("depthValues", minZ, minZ + maxZ); if (!renderingMaterial) { if (material.needAlphaTestingForMesh(effectiveMesh)) { const alphaTexture = material.getAlphaTestTexture(); if (alphaTexture) { effect.setTexture("diffuseSampler", alphaTexture); effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); } } BindBonesParameters(renderingMesh, effect); BindClipPlane(effect, material, scene2); BindMorphTargetParameters(renderingMesh, effect); if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { renderingMesh.morphTargetManager._bind(effect); } const bvaManager = subMesh.getMesh().bakedVertexAnimationManager; if (bvaManager && bvaManager.isEnabled) { bvaManager.bind(effect, hardwareInstancedRendering); } if (material.pointsCloud) { effect.setFloat("pointSize", material.pointSize); } } renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => effect.setMatrix("world", world)); } }, "renderSubMesh"); this._depthMap.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => { let index; if (depthOnlySubMeshes.length) { for (index = 0; index < depthOnlySubMeshes.length; index++) { renderSubMesh(depthOnlySubMeshes.data[index]); } } for (index = 0; index < opaqueSubMeshes.length; index++) { renderSubMesh(opaqueSubMeshes.data[index]); } for (index = 0; index < alphaTestSubMeshes.length; index++) { renderSubMesh(alphaTestSubMeshes.data[index]); } if (this.forceDepthWriteTransparentMeshes) { for (index = 0; index < transparentSubMeshes.length; index++) { renderSubMesh(transparentSubMeshes.data[index]); } } else { for (index = 0; index < transparentSubMeshes.length; index++) { transparentSubMeshes.data[index].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = false; } } }; } async _initShaderSourceAsync(forceGLSL = false) { const engine = this._scene.getEngine(); if (engine.isWebGPU && !forceGLSL && !_DepthRenderer.ForceGLSL) { this._shaderLanguage = 1; await Promise.all([Promise.resolve().then(() => (init_depth_vertex(), depth_vertex_exports)), Promise.resolve().then(() => (init_depth_fragment(), depth_fragment_exports))]); } else { await Promise.all([Promise.resolve().then(() => (init_depth_vertex2(), depth_vertex_exports2)), Promise.resolve().then(() => (init_depth_fragment2(), depth_fragment_exports2))]); } this._shadersLoaded = true; } /** * Creates the depth rendering effect and checks if the effect is ready. * @param subMesh The submesh to be used to render the depth map of * @param useInstances If multiple world instances should be used * @returns if the depth renderer is ready to render the depth map */ isReady(subMesh, useInstances) { if (!this._shadersLoaded) { return false; } const engine = this._scene.getEngine(); const mesh = subMesh.getMesh(); const scene = mesh.getScene(); const renderingMaterial = mesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine.currentRenderPassId]; if (renderingMaterial) { return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances); } const material = subMesh.getMaterial(); if (!material || material.disableDepthWrite) { return false; } const defines = []; const attribs = [VertexBuffer.PositionKind]; let uv1 = false; let uv2 = false; const color = false; if (material.needAlphaTestingForMesh(mesh) && material.getAlphaTestTexture()) { defines.push("#define ALPHATEST"); if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { attribs.push(VertexBuffer.UVKind); defines.push("#define UV1"); uv1 = true; } if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) { attribs.push(VertexBuffer.UV2Kind); defines.push("#define UV2"); uv2 = true; } } const fallbacks = new EffectFallbacks(); if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { attribs.push(VertexBuffer.MatricesIndicesKind); attribs.push(VertexBuffer.MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(VertexBuffer.MatricesIndicesExtraKind); attribs.push(VertexBuffer.MatricesWeightsExtraKind); } defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); if (mesh.numBoneInfluencers > 0) { fallbacks.addCPUSkinningFallback(0, mesh); } const skeleton = mesh.skeleton; if (skeleton.isUsingTextureForMatrices) { defines.push("#define BONETEXTURE"); } else { defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1)); } } else { defines.push("#define NUM_BONE_INFLUENCERS 0"); } const numMorphInfluencers = mesh.morphTargetManager ? PrepareDefinesAndAttributesForMorphTargets( mesh.morphTargetManager, defines, attribs, mesh, true, // usePositionMorph false, // useNormalMorph false, // useTangentMorph uv1, // useUVMorph uv2, // useUV2Morph color // useColorMorph ) : 0; if (material.pointsCloud) { defines.push("#define POINTSIZE"); } if (useInstances) { defines.push("#define INSTANCES"); PushAttributesForInstances(attribs); if (subMesh.getRenderingMesh().hasThinInstances) { defines.push("#define THIN_INSTANCES"); } } const bvaManager = mesh.bakedVertexAnimationManager; if (bvaManager && bvaManager.isEnabled) { defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"); if (useInstances) { attribs.push("bakedVertexAnimationSettingsInstanced"); } } if (this._storeNonLinearDepth) { defines.push("#define NONLINEARDEPTH"); } if (this._storeCameraSpaceZ) { defines.push("#define STORE_CAMERASPACE_Z"); } if (this.isPacked) { defines.push("#define PACKED"); } PrepareStringDefinesForClipPlanes(material, scene, defines); const drawWrapper = subMesh._getDrawWrapper(void 0, true); const cachedDefines = drawWrapper.defines; const join = defines.join("\n"); if (cachedDefines !== join) { const uniforms = [ "world", "mBones", "boneTextureWidth", "pointSize", "viewProjection", "view", "diffuseMatrix", "depthValues", "morphTargetInfluences", "morphTargetCount", "morphTargetTextureInfo", "morphTargetTextureIndices", "bakedVertexAnimationSettings", "bakedVertexAnimationTextureSizeInverted", "bakedVertexAnimationTime", "bakedVertexAnimationTexture" ]; const samplers = ["diffuseSampler", "morphTargets", "boneSampler", "bakedVertexAnimationTexture"]; AddClipPlaneUniforms(uniforms); drawWrapper.setEffect(engine.createEffect("depth", { attributes: attribs, uniformsNames: uniforms, uniformBuffersNames: [], samplers, defines: join, fallbacks, onCompiled: null, onError: null, indexParameters: { maxSimultaneousMorphTargets: numMorphInfluencers }, shaderLanguage: this._shaderLanguage }, engine), join); } return drawWrapper.effect.isReady(); } /** * Gets the texture which the depth map will be written to. * @returns The depth map texture */ getDepthMap() { return this._depthMap; } /** * Disposes of the depth renderer. */ dispose() { const keysToDelete = []; for (const key in this._scene._depthRenderer) { const depthRenderer = this._scene._depthRenderer[key]; if (depthRenderer === this) { keysToDelete.push(key); } } if (keysToDelete.length > 0) { this._depthMap.dispose(); for (const key of keysToDelete) { delete this._scene._depthRenderer[key]; } } } }; DepthRenderer.ForceGLSL = false; DepthRenderer._SceneComponentInitialization = (_) => { throw _WarnImport("DepthRendererSceneComponent"); }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/minmaxRedux.fragment.js var minmaxRedux_fragment_exports = {}; __export(minmaxRedux_fragment_exports, { minmaxReduxPixelShaderWGSL: () => minmaxReduxPixelShaderWGSL }); var name91, shader91, minmaxReduxPixelShaderWGSL; var init_minmaxRedux_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/minmaxRedux.fragment.js"() { init_shaderStore(); name91 = "minmaxReduxPixelShader"; shader91 = `varying vUV: vec2f;var textureSampler: texture_2d; #if defined(INITIAL) uniform texSize: vec2f;@fragment fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*(uniforms.texSize-1.0));let f1=textureLoad(textureSampler,coord,0).r;let f2=textureLoad(textureSampler,coord+vec2i(1,0),0).r;let f3=textureLoad(textureSampler,coord+vec2i(1,1),0).r;let f4=textureLoad(textureSampler,coord+vec2i(0,1),0).r; #ifdef DEPTH_REDUX #ifdef VIEW_DEPTH var minz=3.4e38;if (f1 != 0.0) { minz=f1; } if (f2 != 0.0) { minz=min(minz,f2); } if (f3 != 0.0) { minz=min(minz,f3); } if (f4 != 0.0) { minz=min(minz,f4); } let maxz=max(max(max(f1,f2),f3),f4); #else let minz=min(min(min(f1,f2),f3),f4);let maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4); #endif #else let minz=min(min(min(f1,f2),f3),f4);let maxz=max(max(max(f1,f2),f3),f4); #endif fragmentOutputs.color=vec4f(minz,maxz,0.,0.);} #elif defined(MAIN) uniform texSize: vec2f;@fragment fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*(uniforms.texSize-1.0));let f1=textureLoad(textureSampler,coord,0).rg;let f2=textureLoad(textureSampler,coord+vec2i(1,0),0).rg;let f3=textureLoad(textureSampler,coord+vec2i(1,1),0).rg;let f4=textureLoad(textureSampler,coord+vec2i(0,1),0).rg;let minz=min(min(min(f1.x,f2.x),f3.x),f4.x);let maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);fragmentOutputs.color=vec4(minz,maxz,0.,0.);} #elif defined(ONEBEFORELAST) uniform texSize: vec2i;@fragment fn main(input: FragmentInputs)->FragmentOutputs {let coord=vec2i(fragmentInputs.vUV*vec2f(uniforms.texSize-1));let f1=textureLoad(textureSampler,coord % uniforms.texSize,0).rg;let f2=textureLoad(textureSampler,(coord+vec2i(1,0)) % uniforms.texSize,0).rg;let f3=textureLoad(textureSampler,(coord+vec2i(1,1)) % uniforms.texSize,0).rg;let f4=textureLoad(textureSampler,(coord+vec2i(0,1)) % uniforms.texSize,0).rg;let minz=min(min(min(f1.x,f2.x),f3.x),f4.x);let maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);fragmentOutputs.color=vec4(minz,maxz,0.,0.);} #elif defined(LAST) @fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=vec4f(0.);if (true) { discard;}} #endif `; if (!ShaderStore.ShadersStoreWGSL[name91]) { ShaderStore.ShadersStoreWGSL[name91] = shader91; } minmaxReduxPixelShaderWGSL = { name: name91, shader: shader91 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/minmaxRedux.fragment.js var minmaxRedux_fragment_exports2 = {}; __export(minmaxRedux_fragment_exports2, { minmaxReduxPixelShader: () => minmaxReduxPixelShader }); var name92, shader92, minmaxReduxPixelShader; var init_minmaxRedux_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/minmaxRedux.fragment.js"() { init_shaderStore(); name92 = "minmaxReduxPixelShader"; shader92 = `varying vec2 vUV;uniform sampler2D textureSampler; #if defined(INITIAL) uniform vec2 texSize;void main(void) {ivec2 coord=ivec2(vUV*(texSize-1.0));float f1=texelFetch(textureSampler,coord,0).r;float f2=texelFetch(textureSampler,coord+ivec2(1,0),0).r;float f3=texelFetch(textureSampler,coord+ivec2(1,1),0).r;float f4=texelFetch(textureSampler,coord+ivec2(0,1),0).r; #ifdef DEPTH_REDUX #ifdef VIEW_DEPTH float minz=3.4e38;if (f1 != 0.0) { minz=f1; } if (f2 != 0.0) { minz=min(minz,f2); } if (f3 != 0.0) { minz=min(minz,f3); } if (f4 != 0.0) { minz=min(minz,f4); } float maxz=max(max(max(f1,f2),f3),f4); #else float minz=min(min(min(f1,f2),f3),f4);float maxz=max(max(max(sign(1.0-f1)*f1,sign(1.0-f2)*f2),sign(1.0-f3)*f3),sign(1.0-f4)*f4); #endif #else float minz=min(min(min(f1,f2),f3),f4);float maxz=max(max(max(f1,f2),f3),f4); #endif glFragColor=vec4(minz,maxz,0.,0.);} #elif defined(MAIN) uniform vec2 texSize;void main(void) {ivec2 coord=ivec2(vUV*(texSize-1.0));vec2 f1=texelFetch(textureSampler,coord,0).rg;vec2 f2=texelFetch(textureSampler,coord+ivec2(1,0),0).rg;vec2 f3=texelFetch(textureSampler,coord+ivec2(1,1),0).rg;vec2 f4=texelFetch(textureSampler,coord+ivec2(0,1),0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);} #elif defined(ONEBEFORELAST) uniform ivec2 texSize;void main(void) {ivec2 coord=ivec2(vUV*vec2(texSize-1));vec2 f1=texelFetch(textureSampler,coord % texSize,0).rg;vec2 f2=texelFetch(textureSampler,(coord+ivec2(1,0)) % texSize,0).rg;vec2 f3=texelFetch(textureSampler,(coord+ivec2(1,1)) % texSize,0).rg;vec2 f4=texelFetch(textureSampler,(coord+ivec2(0,1)) % texSize,0).rg;float minz=min(min(min(f1.x,f2.x),f3.x),f4.x);float maxz=max(max(max(f1.y,f2.y),f3.y),f4.y);glFragColor=vec4(minz,maxz,0.,0.);} #elif defined(LAST) void main(void) {glFragColor=vec4(0.);if (true) { discard;}} #endif `; if (!ShaderStore.ShadersStore[name92]) { ShaderStore.ShadersStore[name92] = shader92; } minmaxReduxPixelShader = { name: name92, shader: shader92 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/thinMinMaxReducer.js var DepthTextureType, ThinMinMaxReducerPostProcess, BufferFloat, BufferUint8, MinMax, ThinMinMaxReducer; var init_thinMinMaxReducer = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/thinMinMaxReducer.js"() { init_observable(); init_effectRenderer(); init_engine(); (function(DepthTextureType2) { DepthTextureType2[DepthTextureType2["NormalizedViewDepth"] = 0] = "NormalizedViewDepth"; DepthTextureType2[DepthTextureType2["ViewDepth"] = 1] = "ViewDepth"; DepthTextureType2[DepthTextureType2["ScreenDepth"] = 2] = "ScreenDepth"; })(DepthTextureType || (DepthTextureType = {})); ThinMinMaxReducerPostProcess = class _ThinMinMaxReducerPostProcess extends EffectWrapper { static { __name(this, "ThinMinMaxReducerPostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_minmaxRedux_fragment(), minmaxRedux_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_minmaxRedux_fragment2(), minmaxRedux_fragment_exports2))); } } constructor(name260, engine = null, defines = "", options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinMinMaxReducerPostProcess.FragmentUrl, uniforms: _ThinMinMaxReducerPostProcess.Uniforms, defines }); this.textureWidth = 0; this.textureHeight = 0; } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); const effect = this.drawWrapper.effect; if (this.textureWidth === 1 || this.textureHeight === 1) { effect.setInt2("texSize", this.textureWidth, this.textureHeight); } else { effect.setFloat2("texSize", this.textureWidth, this.textureHeight); } } }; ThinMinMaxReducerPostProcess.FragmentUrl = "minmaxRedux"; ThinMinMaxReducerPostProcess.Uniforms = ["texSize"]; BufferFloat = new Float32Array(4 * 1 * 1); BufferUint8 = new Uint8Array(4 * 1 * 1); MinMax = { min: 0, max: 0 }; ThinMinMaxReducer = class { static { __name(this, "ThinMinMaxReducer"); } get depthRedux() { return this._depthRedux; } set depthRedux(value) { if (this._depthRedux === value) { return; } this._depthRedux = value; this._recreatePostProcesses(); } get textureWidth() { return this._textureWidth; } get textureHeight() { return this._textureHeight; } constructor(scene, depthRedux = true) { this.onAfterReductionPerformed = new Observable(); this._textureWidth = 0; this._textureHeight = 0; this._scene = scene; this._depthRedux = depthRedux; this.reductionSteps = []; } setTextureDimensions(width, height, depthTextureType = 0) { if (width === this._textureWidth && height === this._textureHeight && depthTextureType === this._depthTextureType) { return false; } this._textureWidth = width; this._textureHeight = height; this._depthTextureType = depthTextureType; this._recreatePostProcesses(); return true; } readMinMax(texture) { const isFloat = texture.type === Engine.TEXTURETYPE_FLOAT || texture.type === Engine.TEXTURETYPE_HALF_FLOAT; const buffer = isFloat ? BufferFloat : BufferUint8; this._scene.getEngine()._readTexturePixels(texture, 1, 1, -1, 0, buffer, false); MinMax.min = buffer[0]; MinMax.max = buffer[1]; if (!isFloat) { MinMax.min = MinMax.min / 255; MinMax.max = MinMax.max / 255; } if (MinMax.min >= MinMax.max) { MinMax.min = 0; MinMax.max = 1; } this.onAfterReductionPerformed.notifyObservers(MinMax); } dispose(disposeAll = true) { if (disposeAll) { this.onAfterReductionPerformed.clear(); this._textureWidth = 0; this._textureHeight = 0; } for (let i = 0; i < this.reductionSteps.length; ++i) { this.reductionSteps[i].dispose(); } this.reductionSteps.length = 0; } _recreatePostProcesses() { this.dispose(false); const scene = this._scene; let w = this.textureWidth, h = this.textureHeight; const reductionInitial = new ThinMinMaxReducerPostProcess("Initial reduction phase", scene.getEngine(), "#define INITIAL" + (this._depthRedux ? "\n#define DEPTH_REDUX" : "") + (this._depthTextureType === 1 ? "\n#define VIEW_DEPTH" : "")); reductionInitial.textureWidth = w; reductionInitial.textureHeight = h; this.reductionSteps.push(reductionInitial); let index = 1; while (w > 1 || h > 1) { w = Math.max(Math.round(w / 2), 1); h = Math.max(Math.round(h / 2), 1); const reduction = new ThinMinMaxReducerPostProcess("Reduction phase " + index, scene.getEngine(), "#define " + (w == 1 && h == 1 ? "LAST" : w == 1 || h == 1 ? "ONEBEFORELAST" : "MAIN")); reduction.textureWidth = w; reduction.textureHeight = h; this.reductionSteps.push(reduction); index++; } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/minMaxReducer.js var MinMaxReducer; var init_minMaxReducer = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/minMaxReducer.js"() { init_postProcess(); init_postProcessManager(); init_thinMinMaxReducer(); init_minmaxRedux_fragment2(); init_minmaxRedux_fragment(); MinMaxReducer = class { static { __name(this, "MinMaxReducer"); } /** * Observable triggered when the computation has been performed */ get onAfterReductionPerformed() { return this._thinMinMaxReducer.onAfterReductionPerformed; } /** * Creates a min/max reducer * @param camera The camera to use for the post processes */ constructor(camera) { this._onAfterUnbindObserver = null; this._forceFullscreenViewport = true; this._activated = false; this._camera = camera; this._postProcessManager = new PostProcessManager(camera.getScene()); this._thinMinMaxReducer = new ThinMinMaxReducer(camera.getScene()); this._reductionSteps = []; this._onContextRestoredObserver = camera.getEngine().onContextRestoredObservable.add(() => { this._postProcessManager._rebuild(); }); } /** * Gets the texture used to read the values from. */ get sourceTexture() { return this._sourceTexture; } /** * Sets the source texture to read the values from. * One must indicate if the texture is a depth texture or not through the depthRedux parameter * because in such textures '1' value must not be taken into account to compute the maximum * as this value is used to clear the texture. * Note that the computation is not activated by calling this function, you must call activate() for that! * @param sourceTexture The texture to read the values from. The values should be in the red channel. * @param depthRedux Indicates if the texture is a depth texture or not * @param type The type of the textures created for the reduction (defaults to TEXTURETYPE_HALF_FLOAT) * @param forceFullscreenViewport Forces the post processes used for the reduction to be applied without taking into account viewport (defaults to true) */ setSourceTexture(sourceTexture, depthRedux, type = 2, forceFullscreenViewport = true) { if (sourceTexture === this._sourceTexture) { return; } this._thinMinMaxReducer.depthRedux = depthRedux; this.deactivate(); this._sourceTexture = sourceTexture; this._forceFullscreenViewport = forceFullscreenViewport; if (this._thinMinMaxReducer.setTextureDimensions(sourceTexture.getRenderWidth(), sourceTexture.getRenderHeight())) { this._disposePostProcesses(); const reductionSteps = this._thinMinMaxReducer.reductionSteps; for (let i = 0; i < reductionSteps.length; ++i) { const reductionStep = reductionSteps[i]; const postProcess = new PostProcess(reductionStep.name, ThinMinMaxReducerPostProcess.FragmentUrl, { effectWrapper: reductionStep, samplingMode: 1, engine: this._camera.getScene().getEngine(), textureType: type, textureFormat: 7, size: { width: reductionStep.textureWidth, height: reductionStep.textureHeight } }); this._reductionSteps.push(postProcess); postProcess.autoClear = false; postProcess.forceFullscreenViewport = forceFullscreenViewport; if (i === 0) { postProcess.externalTextureSamplerBinding = true; postProcess.onApplyObservable.add((effect) => { effect.setTexture("textureSampler", this._sourceTexture); }); } if (i === reductionSteps.length - 1) { this._reductionSteps[i - 1].onAfterRenderObservable.add(() => { this._thinMinMaxReducer.readMinMax(postProcess.inputTexture.texture); }); } } } } /** * Defines the refresh rate of the computation. * Use 0 to compute just once, 1 to compute on every frame, 2 to compute every two frames and so on... */ get refreshRate() { return this._sourceTexture ? this._sourceTexture.refreshRate : -1; } set refreshRate(value) { if (this._sourceTexture) { this._sourceTexture.refreshRate = value; } } /** * Gets the activation status of the reducer */ get activated() { return this._activated; } /** * Activates the reduction computation. * When activated, the observers registered in onAfterReductionPerformed are * called after the computation is performed */ activate() { if (this._onAfterUnbindObserver || !this._sourceTexture) { return; } this._onAfterUnbindObserver = this._sourceTexture.onAfterUnbindObservable.add(() => { const engine = this._camera.getScene().getEngine(); engine._debugPushGroup?.(`min max reduction`, 1); this._reductionSteps[0].activate(this._camera); this._postProcessManager.directRender(this._reductionSteps, this._reductionSteps[0].inputTexture, this._forceFullscreenViewport, 0, 0, true, this._reductionSteps.length - 1); engine.unBindFramebuffer(this._reductionSteps[this._reductionSteps.length - 1].inputTexture, false); engine._debugPopGroup?.(1); }); this._activated = true; } /** * Deactivates the reduction computation. */ deactivate() { if (!this._onAfterUnbindObserver || !this._sourceTexture) { return; } this._sourceTexture.onAfterUnbindObservable.remove(this._onAfterUnbindObserver); this._onAfterUnbindObserver = null; this._activated = false; } /** * Disposes the min/max reducer * @param disposeAll true to dispose all the resources. You should always call this function with true as the parameter (or without any parameter as it is the default one). This flag is meant to be used internally. */ dispose(disposeAll = true) { if (!disposeAll) { return; } this.onAfterReductionPerformed.clear(); this._camera.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver); this._onContextRestoredObserver = void 0; this._disposePostProcesses(); this._postProcessManager.dispose(); this._postProcessManager = void 0; this._thinMinMaxReducer.dispose(); this._thinMinMaxReducer = void 0; this._sourceTexture = null; } _disposePostProcesses() { for (let i = 0; i < this._reductionSteps.length; ++i) { this._reductionSteps[i].dispose(); } this._reductionSteps.length = 0; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/depthReducer.js var DepthReducer; var init_depthReducer = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/depthReducer.js"() { init_depthRenderer(); init_minMaxReducer(); DepthReducer = class extends MinMaxReducer { static { __name(this, "DepthReducer"); } /** * Gets the depth renderer used for the computation. * Note that the result is null if you provide your own renderer when calling setDepthRenderer. */ get depthRenderer() { return this._depthRenderer; } /** * Creates a depth reducer * @param camera The camera used to render the depth texture */ constructor(camera) { super(camera); } /** * Sets the depth renderer to use to generate the depth map * @param depthRenderer The depth renderer to use. If not provided, a new one will be created automatically * @param type The texture type of the depth map (default: TEXTURETYPE_HALF_FLOAT) * @param forceFullscreenViewport Forces the post processes used for the reduction to be applied without taking into account viewport (defaults to true) */ setDepthRenderer(depthRenderer = null, type = 2, forceFullscreenViewport = true) { const scene = this._camera.getScene(); if (this._depthRenderer) { delete scene._depthRenderer[this._depthRendererId]; this._depthRenderer.dispose(); this._depthRenderer = null; } if (depthRenderer === null) { if (!scene._depthRenderer) { scene._depthRenderer = {}; } this._depthRendererId = "minmax_" + this._camera.id; depthRenderer = this._depthRenderer = new DepthRenderer(scene, type, this._camera, false, 1, false, `DepthRenderer ${this._depthRendererId}`); depthRenderer.enabled = false; scene._depthRenderer[this._depthRendererId] = depthRenderer; } super.setSourceTexture(depthRenderer.getDepthMap(), true, type, forceFullscreenViewport); } /** * @internal */ setSourceTexture(sourceTexture, depthRedux, type = 2, forceFullscreenViewport = true) { super.setSourceTexture(sourceTexture, depthRedux, type, forceFullscreenViewport); } /** * Activates the reduction computation. * When activated, the observers registered in onAfterReductionPerformed are * called after the computation is performed */ activate() { if (this._depthRenderer) { this._depthRenderer.enabled = true; } super.activate(); } /** * Deactivates the reduction computation. */ deactivate() { super.deactivate(); if (this._depthRenderer) { this._depthRenderer.enabled = false; } } /** * Disposes the depth reducer * @param disposeAll true to dispose all the resources. You should always call this function with true as the parameter (or without any parameter as it is the default one). This flag is meant to be used internally. */ dispose(disposeAll = true) { super.dispose(disposeAll); if (this._depthRenderer && disposeAll) { this._depthRenderer.dispose(); this._depthRenderer = null; } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/Shadows/cascadedShadowGenerator.js var UpDir, ZeroVec, Tmpv1, Tmpv2, TmpMatrix, CascadedShadowGenerator; var init_cascadedShadowGenerator = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/Shadows/cascadedShadowGenerator.js"() { init_math_vector(); init_renderTargetTexture(); init_devTools(); init_shadowGenerator(); init_boundingInfo(); init_depthReducer(); init_logger(); init_engineStore(); UpDir = Vector3.Up(); ZeroVec = Vector3.Zero(); Tmpv1 = new Vector3(); Tmpv2 = new Vector3(); TmpMatrix = new Matrix(); CascadedShadowGenerator = class _CascadedShadowGenerator extends ShadowGenerator { static { __name(this, "CascadedShadowGenerator"); } _validateFilter(filter) { if (filter === ShadowGenerator.FILTER_NONE || filter === ShadowGenerator.FILTER_PCF || filter === ShadowGenerator.FILTER_PCSS) { return filter; } Logger.Error('Unsupported filter "' + filter + '"!'); return ShadowGenerator.FILTER_NONE; } /** * Gets or set the number of cascades used by the CSM. */ get numCascades() { return this._numCascades; } set numCascades(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(); this._recreateSceneUBOs(); } /** * 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 freezeShadowCastersBoundingInfo() { return this._freezeShadowCastersBoundingInfo; } set freezeShadowCastersBoundingInfo(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()); } this._freezeShadowCastersBoundingInfo = freeze; if (freeze) { this._computeShadowCastersBoundingInfo(); } } _computeShadowCastersBoundingInfo() { this._scbiMin.copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._scbiMax.copyFromFloats(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); if (this._shadowMap && this._shadowMap.renderList) { const renderList = this._shadowMap.renderList; for (let meshIndex = 0; meshIndex < renderList.length; meshIndex++) { const mesh = renderList[meshIndex]; if (!mesh) { continue; } const boundingInfo = mesh.getBoundingInfo(), boundingBox = boundingInfo.boundingBox; this._scbiMin.minimizeInPlace(boundingBox.minimumWorld); this._scbiMax.maximizeInPlace(boundingBox.maximumWorld); } } this._shadowCastersBoundingInfo.reConstruct(this._scbiMin, this._scbiMax); } /** * 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 shadowCastersBoundingInfo() { return this._shadowCastersBoundingInfo; } set shadowCastersBoundingInfo(boundingInfo) { this._shadowCastersBoundingInfo = boundingInfo; } /** * 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.) */ setMinMaxDistance(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; } /** Gets the minimal distance used in the cascade break computation */ get minDistance() { return this._minDistance; } /** Gets the maximal distance used in the cascade break computation */ get maxDistance() { return this._maxDistance; } /** * Gets the class name of that object * @returns "CascadedShadowGenerator" */ getClassName() { return _CascadedShadowGenerator.CLASSNAME; } /** * Gets a cascade minimum extents * @param cascadeIndex index of the cascade * @returns the minimum cascade extents */ getCascadeMinExtents(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 */ getCascadeMaxExtents(cascadeIndex) { return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMaxExtents[cascadeIndex] : null; } /** * Gets the shadow max z distance. It's the limit beyond which shadows are not displayed. * It defaults to camera.maxZ */ get shadowMaxZ() { if (!this._getCamera()) { return 0; } return this._shadowMaxZ; } /** * Sets the shadow max z distance. */ set shadowMaxZ(value) { const camera = this._getCamera(); if (!camera) { this._shadowMaxZ = value; return; } if (this._shadowMaxZ === value || value < camera.minZ || value > camera.maxZ && camera.maxZ !== 0) { return; } this._shadowMaxZ = value; this._light._markMeshesAsLightDirty(); this._breaksAreDirty = true; } /** * Gets or sets the debug flag. * When enabled, the cascades are materialized by different colors on the screen. */ get debug() { return this._debug; } set debug(dbg) { this._debug = dbg; this._light._markMeshesAsLightDirty(); } /** * 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 depthClamp() { return this._depthClamp; } set depthClamp(value) { this._depthClamp = value; } /** * Gets or sets the percentage of blending between two cascades (value between 0. and 1.). * It defaults to 0.1 (10% blending). */ get cascadeBlendPercentage() { return this._cascadeBlendPercentage; } set cascadeBlendPercentage(value) { this._cascadeBlendPercentage = value; this._light._markMeshesAsLightDirty(); } /** * 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 lambda() { return this._lambda; } set lambda(value) { const lambda = Math.min(Math.max(value, 0), 1); if (this._lambda == lambda) { return; } this._lambda = lambda; this._breaksAreDirty = true; } /** * Gets the view matrix corresponding to a given cascade * @param cascadeNum cascade to retrieve the view matrix from * @returns the cascade view matrix */ getCascadeViewMatrix(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 */ getCascadeProjectionMatrix(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 */ getCascadeTransformMatrix(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 */ setDepthRenderer(depthRenderer) { this._depthRenderer = depthRenderer; if (this._depthReducer) { this._depthReducer.setDepthRenderer(this._depthRenderer); } } /** * 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 autoCalcDepthBounds() { return this._autoCalcDepthBounds; } set autoCalcDepthBounds(value) { const camera = this._getCamera(); 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 DepthReducer(camera); this._depthReducer.onAfterReductionPerformed.add((minmax) => { let 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(); } /** * 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 autoCalcDepthBoundsRefreshRate() { return this._depthReducer?.depthRenderer?.getDepthMap().refreshRate ?? -1; } set autoCalcDepthBoundsRefreshRate(value) { if (this._depthReducer?.depthRenderer) { this._depthReducer.depthRenderer.getDepthMap().refreshRate = value; } } /** * 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! */ splitFrustum() { this._breaksAreDirty = true; } _splitFrustum() { const camera = this._getCamera(); if (!camera) { return; } const near = camera.minZ, far = camera.maxZ || this._shadowMaxZ, cameraRange = far - near, minDistance = this._minDistance, maxDistance = this._shadowMaxZ < far && this._shadowMaxZ >= near ? Math.min((this._shadowMaxZ - near) / (far - near), this._maxDistance) : this._maxDistance; const minZ = near + minDistance * cameraRange, maxZ = near + maxDistance * cameraRange; const range = maxZ - minZ, ratio = maxZ / minZ; for (let cascadeIndex = 0; cascadeIndex < this._cascades.length; ++cascadeIndex) { const p = (cascadeIndex + 1) / this._numCascades, log = minZ * ratio ** p, uniform = minZ + range * p; const 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] = d; this._frustumLengths[cascadeIndex] = (this._cascades[cascadeIndex].breakDistance - this._cascades[cascadeIndex].prevBreakDistance) * cameraRange; } this._breaksAreDirty = false; } _computeMatrices() { const scene = this._scene; const camera = this._getCamera(); if (!camera) { return; } Vector3.NormalizeToRef(this._light.getShadowDirection(0), this._lightDirection); if (Math.abs(Vector3.Dot(this._lightDirection, Vector3.Up())) === 1) { this._lightDirection.z = 1e-13; } this._cachedDirection.copyFrom(this._lightDirection); const useReverseDepthBuffer = scene.getEngine().useReverseDepthBuffer; for (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) { this._computeFrustumInWorldSpace(cascadeIndex); this._computeCascadeFrustum(cascadeIndex); this._cascadeMaxExtents[cascadeIndex].subtractToRef(this._cascadeMinExtents[cascadeIndex], Tmpv1); this._frustumCenter[cascadeIndex].addToRef(this._lightDirection.scale(this._cascadeMinExtents[cascadeIndex].z), this._shadowCameraPos[cascadeIndex]); Matrix.LookAtLHToRef(this._shadowCameraPos[cascadeIndex], this._frustumCenter[cascadeIndex], UpDir, this._viewMatrices[cascadeIndex]); let viewMinZ = 0, viewMaxZ = Tmpv1.z; const boundingInfo = this._shadowCastersBoundingInfo; boundingInfo.update(this._viewMatrices[cascadeIndex]); const castersViewMinZ = boundingInfo.boundingBox.minimumWorld.z; const castersViewMaxZ = boundingInfo.boundingBox.maximumWorld.z; if (castersViewMinZ > viewMaxZ) { } else { if (!this._depthClamp || this.filter === ShadowGenerator.FILTER_PCSS) { viewMinZ = Math.min(viewMinZ, castersViewMinZ); if (this.filter !== ShadowGenerator.FILTER_PCSS) { viewMaxZ = Math.min(viewMaxZ, castersViewMaxZ); } } else { viewMaxZ = Math.min(viewMaxZ, castersViewMaxZ); viewMinZ = Math.max(viewMinZ, castersViewMinZ); viewMaxZ = Math.max(viewMinZ + 1, viewMaxZ); } } Matrix.OrthoOffCenterLHToRef(this._cascadeMinExtents[cascadeIndex].x, this._cascadeMaxExtents[cascadeIndex].x, this._cascadeMinExtents[cascadeIndex].y, this._cascadeMaxExtents[cascadeIndex].y, useReverseDepthBuffer ? viewMaxZ : viewMinZ, useReverseDepthBuffer ? viewMinZ : viewMaxZ, this._projectionMatrices[cascadeIndex], scene.getEngine().isNDCHalfZRange); this._cascadeMinExtents[cascadeIndex].z = viewMinZ; this._cascadeMaxExtents[cascadeIndex].z = viewMaxZ; this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]); Vector3.TransformCoordinatesToRef(ZeroVec, this._transformMatrices[cascadeIndex], Tmpv1); Tmpv1.scaleInPlace(this._mapSize / 2); Tmpv2.copyFromFloats(Math.round(Tmpv1.x), Math.round(Tmpv1.y), Math.round(Tmpv1.z)); Tmpv2.subtractInPlace(Tmpv1).scaleInPlace(2 / this._mapSize); Matrix.TranslationToRef(Tmpv2.x, Tmpv2.y, 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 _computeFrustumInWorldSpace(cascadeIndex) { const camera = this._getCamera(); if (!camera) { return; } const prevSplitDist = this._cascades[cascadeIndex].prevBreakDistance, splitDist = this._cascades[cascadeIndex].breakDistance; const isNDCHalfZRange = this._scene.getEngine().isNDCHalfZRange; camera.getViewMatrix(); const cameraInfiniteFarPlane = camera.maxZ === 0; const saveCameraMaxZ = camera.maxZ; if (cameraInfiniteFarPlane) { camera.maxZ = this._shadowMaxZ; camera.getProjectionMatrix(true); } const invViewProj = Matrix.Invert(camera.getTransformationMatrix()); if (cameraInfiniteFarPlane) { camera.maxZ = saveCameraMaxZ; camera.getProjectionMatrix(true); } const cornerIndexOffset = this._scene.getEngine().useReverseDepthBuffer ? 4 : 0; for (let cornerIndex = 0; cornerIndex < _CascadedShadowGenerator._FrustumCornersNdcSpace.length; ++cornerIndex) { Tmpv1.copyFrom(_CascadedShadowGenerator._FrustumCornersNdcSpace[(cornerIndex + cornerIndexOffset) % _CascadedShadowGenerator._FrustumCornersNdcSpace.length]); if (isNDCHalfZRange && Tmpv1.z === -1) { Tmpv1.z = 0; } Vector3.TransformCoordinatesToRef(Tmpv1, invViewProj, this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]); } for (let 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); Tmpv1.scaleInPlace(splitDist); Tmpv1.addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]); this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4].copyFrom(Tmpv1); this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].addInPlace(Tmpv2); } } _computeCascadeFrustum(cascadeIndex) { this._cascadeMinExtents[cascadeIndex].copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); this._cascadeMaxExtents[cascadeIndex].copyFromFloats(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); this._frustumCenter[cascadeIndex].copyFromFloats(0, 0, 0); const camera = this._getCamera(); if (!camera) { return; } for (let 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) { let sphereRadius = 0; for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) { const 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 { const lightCameraPos = this._frustumCenter[cascadeIndex]; this._frustumCenter[cascadeIndex].addToRef(this._lightDirection, Tmpv1); Matrix.LookAtLHToRef(lightCameraPos, Tmpv1, UpDir, TmpMatrix); for (let cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) { Vector3.TransformCoordinatesToRef(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex], TmpMatrix, Tmpv1); this._cascadeMinExtents[cascadeIndex].minimizeInPlace(Tmpv1); this._cascadeMaxExtents[cascadeIndex].maximizeInPlace(Tmpv1); } } } _recreateSceneUBOs() { this._disposeSceneUBOs(); if (this._sceneUBOs) { for (let i = 0; i < this._numCascades; ++i) { this._sceneUBOs.push(this._scene.createSceneUniformBuffer(`Scene for CSM Shadow Generator (light "${this._light.name}" cascade #${i})`)); } } } /** * Support test. */ static get IsSupported() { const engine = EngineStore.LastCreatedEngine; if (!engine) { return false; } return engine._features.supportCSM; } /** * 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. * @param camera Camera associated with this shadow generator (default: null). If null, takes the scene active camera at the time we need to access it * @param useRedTextureType Forces the generator to use a Red instead of a RGBA type for the shadow map texture format (default: true) */ constructor(mapSize, light, usefulFloatFirst, camera, useRedTextureType = true) { if (!_CascadedShadowGenerator.IsSupported) { Logger.Error("CascadedShadowMap is not supported by the current engine."); return; } super(mapSize, light, usefulFloatFirst, camera, useRedTextureType); this.usePercentageCloserFiltering = true; } _initializeGenerator() { this.penumbraDarkness = this.penumbraDarkness ?? 1; this._numCascades = this._numCascades ?? _CascadedShadowGenerator.DEFAULT_CASCADES_COUNT; this.stabilizeCascades = this.stabilizeCascades ?? false; this._freezeShadowCastersBoundingInfoObservable = this._freezeShadowCastersBoundingInfoObservable ?? null; this.freezeShadowCastersBoundingInfo = this.freezeShadowCastersBoundingInfo ?? false; this._scbiMin = this._scbiMin ?? new Vector3(0, 0, 0); this._scbiMax = this._scbiMax ?? new Vector3(0, 0, 0); this._shadowCastersBoundingInfo = this._shadowCastersBoundingInfo ?? new BoundingInfo(new Vector3(0, 0, 0), new Vector3(0, 0, 0)); this._breaksAreDirty = this._breaksAreDirty ?? true; this._minDistance = this._minDistance ?? 0; this._maxDistance = this._maxDistance ?? 1; this._currentLayer = this._currentLayer ?? 0; this._shadowMaxZ = this._shadowMaxZ ?? this._getCamera()?.maxZ ?? 1e4; this._debug = this._debug ?? false; this._depthClamp = this._depthClamp ?? true; this._cascadeBlendPercentage = this._cascadeBlendPercentage ?? 0.1; this._lambda = this._lambda ?? 0.5; this._autoCalcDepthBounds = this._autoCalcDepthBounds ?? false; this._recreateSceneUBOs(); super._initializeGenerator(); } _createTargetRenderTexture() { const engine = this._scene.getEngine(); this._shadowMap?.dispose(); const size = { width: this._mapSize, height: this._mapSize, layers: this.numCascades }; this._shadowMap = new RenderTargetTexture(this._light.name + "_CSMShadowMap", size, this._scene, false, true, this._textureType, false, void 0, false, false, void 0, this._useRedTextureType ? 6 : 5); this._shadowMap.createDepthStencilTexture(engine.useReverseDepthBuffer ? 516 : 513, true, void 0, void 0, void 0, `DepthStencilForCSMShadowGenerator-${this._light.name}`); this._shadowMap.noPrePassRenderer = true; } _initializeShadowMap() { super._initializeShadowMap(); 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 (let cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) { this._cascades[cascadeIndex] = { prevBreakDistance: 0, breakDistance: 0 }; this._viewMatrices[cascadeIndex] = Matrix.Zero(); this._projectionMatrices[cascadeIndex] = Matrix.Zero(); this._transformMatrices[cascadeIndex] = Matrix.Zero(); this._cascadeMinExtents[cascadeIndex] = new Vector3(); this._cascadeMaxExtents[cascadeIndex] = new Vector3(); this._frustumCenter[cascadeIndex] = new Vector3(); this._shadowCameraPos[cascadeIndex] = new Vector3(); this._frustumCornersWorldSpace[cascadeIndex] = new Array(_CascadedShadowGenerator._FrustumCornersNdcSpace.length); for (let i = 0; i < _CascadedShadowGenerator._FrustumCornersNdcSpace.length; ++i) { this._frustumCornersWorldSpace[cascadeIndex][i] = new Vector3(); } } const engine = this._scene.getEngine(); this._shadowMap.onBeforeBindObservable.clear(); this._shadowMap.onBeforeRenderObservable.clear(); this._shadowMap.onBeforeRenderObservable.add((layer) => { if (this._sceneUBOs) { this._scene.setSceneUniformBuffer(this._sceneUBOs[layer]); } this._currentLayer = layer; if (this._filter === ShadowGenerator.FILTER_PCF) { engine.setColorWrite(false); } this._scene.setTransformMatrix(this.getCascadeViewMatrix(layer), this.getCascadeProjectionMatrix(layer)); if (this._useUBO) { this._scene.getSceneUniformBuffer().unbindEffect(); this._scene.finalizeSceneUbo(); } }); this._shadowMap.onBeforeBindObservable.add(() => { this._currentSceneUBO = this._scene.getSceneUniformBuffer(); engine._debugPushGroup?.(`cascaded shadow map generation for pass id ${engine.currentRenderPassId}`, 1); if (this._breaksAreDirty) { this._splitFrustum(); } this._computeMatrices(); }); this._splitFrustum(); } _bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect) { effect.setMatrix("viewProjection", this.getCascadeTransformMatrix(this._currentLayer)); } _isReadyCustomDefines(defines) { defines.push("#define SM_DEPTHCLAMP " + (this._depthClamp && this._filter !== 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 */ prepareDefines(defines, lightIndex) { super.prepareDefines(defines, lightIndex); const scene = this._scene; const 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; const camera = this._getCamera(); if (camera && this._shadowMaxZ <= (camera.maxZ || this._shadowMaxZ)) { 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 */ bindShadowLight(lightIndex, effect) { const light = this._light; const scene = this._scene; if (!scene.shadowsEnabled || !light.shadowEnabled) { return; } const camera = this._getCamera(); if (!camera) { return; } const shadowMap = this.getShadowMap(); if (!shadowMap) { return; } const width = shadowMap.getSize().width; effect.setMatrices("lightMatrix" + lightIndex, this._transformMatricesAsArray); effect.setArray("viewFrustumZ" + lightIndex, this._viewSpaceFrustumsZ); effect.setFloat("cascadeBlendFactor" + lightIndex, this.cascadeBlendPercentage === 0 ? 1e4 : 1 / this.cascadeBlendPercentage); effect.setArray("frustumLengths" + lightIndex, this._frustumLengths); if (this._filter === ShadowGenerator.FILTER_PCF) { effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMap); light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex); } else if (this._filter === ShadowGenerator.FILTER_PCSS) { for (let 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); this._lightSizeUVCorrection[cascadeIndex * 2 + 1] = cascadeIndex === 0 ? 1 : (this._cascadeMaxExtents[0].y - this._cascadeMinExtents[0].y) / (this._cascadeMaxExtents[cascadeIndex].y - this._cascadeMinExtents[cascadeIndex].y); this._depthCorrection[cascadeIndex] = cascadeIndex === 0 ? 1 : (this._cascadeMaxExtents[cascadeIndex].z - this._cascadeMinExtents[cascadeIndex].z) / (this._cascadeMaxExtents[0].z - this._cascadeMinExtents[0].z); } effect.setDepthStencilTexture("shadowTexture" + lightIndex, shadowMap); effect.setTexture("depthTexture" + 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("shadowTexture" + 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 */ getTransformMatrix() { return this.getCascadeTransformMatrix(0); } /** * Disposes the ShadowGenerator. * Returns nothing. */ dispose() { super.dispose(); 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 */ serialize() { const serializationObject = super.serialize(); const 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 (let meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) { const 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 */ static Parse(parsedShadowGenerator, scene) { const shadowGenerator = ShadowGenerator.Parse(parsedShadowGenerator, scene, (mapSize, light, camera) => new _CascadedShadowGenerator(mapSize, light, void 0, camera)); if (parsedShadowGenerator.numCascades !== void 0) { shadowGenerator.numCascades = parsedShadowGenerator.numCascades; } if (parsedShadowGenerator.debug !== void 0) { shadowGenerator.debug = parsedShadowGenerator.debug; } if (parsedShadowGenerator.stabilizeCascades !== void 0) { shadowGenerator.stabilizeCascades = parsedShadowGenerator.stabilizeCascades; } if (parsedShadowGenerator.lambda !== void 0) { shadowGenerator.lambda = parsedShadowGenerator.lambda; } if (parsedShadowGenerator.cascadeBlendPercentage !== void 0) { shadowGenerator.cascadeBlendPercentage = parsedShadowGenerator.cascadeBlendPercentage; } if (parsedShadowGenerator.depthClamp !== void 0) { shadowGenerator.depthClamp = parsedShadowGenerator.depthClamp; } if (parsedShadowGenerator.autoCalcDepthBounds !== void 0) { shadowGenerator.autoCalcDepthBounds = parsedShadowGenerator.autoCalcDepthBounds; } if (parsedShadowGenerator.shadowMaxZ !== void 0) { shadowGenerator.shadowMaxZ = parsedShadowGenerator.shadowMaxZ; } if (parsedShadowGenerator.penumbraDarkness !== void 0) { shadowGenerator.penumbraDarkness = parsedShadowGenerator.penumbraDarkness; } if (parsedShadowGenerator.freezeShadowCastersBoundingInfo !== void 0) { shadowGenerator.freezeShadowCastersBoundingInfo = parsedShadowGenerator.freezeShadowCastersBoundingInfo; } if (parsedShadowGenerator.minDistance !== void 0 && parsedShadowGenerator.maxDistance !== void 0) { shadowGenerator.setMinMaxDistance(parsedShadowGenerator.minDistance, parsedShadowGenerator.maxDistance); } return shadowGenerator; } }; CascadedShadowGenerator._FrustumCornersNdcSpace = [ new Vector3(-1, 1, -1), new Vector3(1, 1, -1), new Vector3(1, -1, -1), new Vector3(-1, -1, -1), new Vector3(-1, 1, 1), new Vector3(1, 1, 1), new Vector3(1, -1, 1), new Vector3(-1, -1, 1) ]; CascadedShadowGenerator.CLASSNAME = "CascadedShadowGenerator"; CascadedShadowGenerator.DEFAULT_CASCADES_COUNT = 4; CascadedShadowGenerator.MIN_CASCADES_COUNT = 2; CascadedShadowGenerator.MAX_CASCADES_COUNT = 4; CascadedShadowGenerator._SceneComponentInitialization = (_) => { throw _WarnImport("ShadowGeneratorSceneComponent"); }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/shadowGeneratorTask.js var FrameGraphShadowGeneratorTask; var init_shadowGeneratorTask = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/shadowGeneratorTask.js"() { init_frameGraphTask(); init_shadowGenerator(); FrameGraphShadowGeneratorTask = class extends FrameGraphTask { static { __name(this, "FrameGraphShadowGeneratorTask"); } /** * The light to generate shadows from. */ get light() { return this._light; } set light(value) { if (value === this._light) { return; } this._light = value; this._setupShadowGenerator(); } /** * Gets or sets the camera used to generate the shadow generator. */ get camera() { return this._camera; } set camera(camera) { this._camera = camera; this._setupShadowGenerator(); } /** * The size of the shadow map. */ get mapSize() { return this._mapSize; } set mapSize(value) { if (value === this._mapSize) { return; } this._mapSize = value; this._setupShadowGenerator(); } /** * If true, the shadow map will use a 32 bits float texture type (else, 16 bits float is used if supported). */ get useFloat32TextureType() { return this._useFloat32TextureType; } set useFloat32TextureType(value) { if (value === this._useFloat32TextureType) { return; } this._useFloat32TextureType = value; this._setupShadowGenerator(); } /** * If true, the shadow map will use a red texture format (else, a RGBA format is used). */ get useRedTextureFormat() { return this._useRedTextureFormat; } set useRedTextureFormat(value) { if (value === this._useRedTextureFormat) { return; } this._useRedTextureFormat = value; this._setupShadowGenerator(); } /** * The bias to apply to the shadow map. */ get bias() { return this._bias; } set bias(value) { if (value === this._bias) { return; } this._bias = value; if (this._shadowGenerator) { this._shadowGenerator.bias = value; } } /** * The normal bias to apply to the shadow map. */ get normalBias() { return this._normalBias; } set normalBias(value) { if (value === this._normalBias) { return; } this._normalBias = value; if (this._shadowGenerator) { this._shadowGenerator.normalBias = value; } } /** * The darkness of the shadows. */ get darkness() { return this._darkness; } set darkness(value) { if (value === this._darkness) { return; } this._darkness = value; if (this._shadowGenerator) { this._shadowGenerator.darkness = value; } } /** * Gets or sets the ability to have transparent shadow */ get transparencyShadow() { return this._transparencyShadow; } set transparencyShadow(value) { if (value === this._transparencyShadow) { return; } this._transparencyShadow = value; if (this._shadowGenerator) { this._shadowGenerator.transparencyShadow = value; } } /** * Enables or disables shadows with varying strength based on the transparency */ get enableSoftTransparentShadow() { return this._enableSoftTransparentShadow; } set enableSoftTransparentShadow(value) { if (value === this._enableSoftTransparentShadow) { return; } this._enableSoftTransparentShadow = value; if (this._shadowGenerator) { this._shadowGenerator.enableSoftTransparentShadow = value; } } /** * If this is true, use the opacity texture's alpha channel for transparent shadows instead of the diffuse one */ get useOpacityTextureForTransparentShadow() { return this._useOpacityTextureForTransparentShadow; } set useOpacityTextureForTransparentShadow(value) { if (value === this._useOpacityTextureForTransparentShadow) { return; } this._useOpacityTextureForTransparentShadow = value; if (this._shadowGenerator) { this._shadowGenerator.useOpacityTextureForTransparentShadow = value; } } /** * The filter to apply to the shadow map. */ get filter() { return this._filter; } set filter(value) { if (value === this._filter) { return; } this._filter = value; if (this._shadowGenerator) { this._shadowGenerator.filter = value; } } /** * The filtering quality to apply to the filter. */ get filteringQuality() { return this._filteringQuality; } set filteringQuality(value) { if (value === this._filteringQuality) { return; } this._filteringQuality = value; if (this._shadowGenerator) { this._shadowGenerator.filteringQuality = value; } } _createShadowGenerator() { this._shadowGenerator = new ShadowGenerator(this._mapSize, this._light, this._useFloat32TextureType, void 0, this._useRedTextureFormat); } _setupShadowGenerator() { this._shadowGenerator?.dispose(); this._shadowGenerator = void 0; if (this._light !== void 0) { this._createShadowGenerator(); const shadowGenerator = this._shadowGenerator; if (shadowGenerator === void 0) { return; } shadowGenerator.bias = this._bias; shadowGenerator.normalBias = this._normalBias; shadowGenerator.darkness = this._darkness; shadowGenerator.transparencyShadow = this._transparencyShadow; shadowGenerator.enableSoftTransparentShadow = this._enableSoftTransparentShadow; shadowGenerator.useOpacityTextureForTransparentShadow = this._useOpacityTextureForTransparentShadow; shadowGenerator.filter = this._filter; shadowGenerator.filteringQuality = this._filteringQuality; const shadowMap = shadowGenerator.getShadowMap(); shadowMap._disableEngineStages = true; shadowMap.cameraForLOD = this._camera; this.shadowGenerator = shadowGenerator; } } isReady() { return !!this._shadowGenerator && !!this._shadowGenerator.getShadowMap()?.isReadyForRendering(); } /** * Creates a new shadow generator task. * @param name The name of the task. * @param frameGraph The frame graph the task belongs to. * @param _scene The scene to create the shadow generator for. */ constructor(name260, frameGraph, _scene) { super(name260, frameGraph); this._mapSize = 1024; this._useFloat32TextureType = false; this._useRedTextureFormat = true; this._bias = 0.01; this._normalBias = 0; this._darkness = 0; this._transparencyShadow = false; this._enableSoftTransparentShadow = false; this._useOpacityTextureForTransparentShadow = false; this._filter = ShadowGenerator.FILTER_PCF; this._filteringQuality = ShadowGenerator.QUALITY_HIGH; this.outputTexture = this._frameGraph.textureManager.createDanglingHandle(); } record() { if (this.light === void 0 || this.objectList === void 0 || this.camera === void 0) { throw new Error(`FrameGraphShadowGeneratorTask ${this.name}: light, objectList and camera are required`); } const shadowMap = this._shadowGenerator.getShadowMap(); shadowMap.renderList = this.objectList.meshes; shadowMap.particleSystemList = this.objectList.particleSystems; const shadowTextureHandle = this._frameGraph.textureManager.importTexture(`${this.name} shadowmap`, this._shadowGenerator.getShadowMap().getInternalTexture()); this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, shadowTextureHandle); const pass = this._frameGraph.addPass(this.name); pass.setExecuteFunc((context) => { if (!this.light.isEnabled() || !this.light.shadowEnabled) { return; } const shadowMap2 = this._shadowGenerator.getShadowMap(); shadowMap2.renderList = this.objectList.meshes; shadowMap2.particleSystemList = this.objectList.particleSystems; context.saveDepthStates(); context.setDepthStates(true, true); context.renderUnmanaged(shadowMap2); context.restoreDepthStates(); }); const passDisabled = this._frameGraph.addPass(this.name + "_disabled", true); passDisabled.setExecuteFunc((_context) => { }); } dispose() { this._shadowGenerator?.dispose(); this._shadowGenerator = void 0; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/shadowLight.js var ShadowLight; var init_shadowLight = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/shadowLight.js"() { init_tslib_es6(); init_decorators(); init_math_vector(); init_light(); init_math_axis(); ShadowLight = class extends Light { static { __name(this, "ShadowLight"); } constructor() { super(...arguments); this._needProjectionMatrixCompute = true; this._viewMatrix = Matrix.Identity(); this._projectionMatrix = Matrix.Identity(); } _setPosition(value) { this._position = value; } /** * Sets the position the shadow will be casted from. Also use as the light position for both * point and spot lights. */ get position() { 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 position(value) { this._setPosition(value); } _setDirection(value) { this._direction = value; } /** * 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 direction() { 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 direction(value) { this._setDirection(value); } /** * Gets the shadow projection clipping minimum z value. */ get shadowMinZ() { return this._shadowMinZ; } /** * Sets the shadow projection clipping minimum z value. */ set shadowMinZ(value) { this._shadowMinZ = value; this.forceProjectionMatrixCompute(); } /** * Sets the shadow projection clipping maximum z value. */ get shadowMaxZ() { return this._shadowMaxZ; } /** * Gets the shadow projection clipping maximum z value. */ set shadowMaxZ(value) { this._shadowMaxZ = value; this.forceProjectionMatrixCompute(); } /** * 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) */ computeTransformedInformation() { if (this.parent && this.parent.getWorldMatrix) { if (!this.transformedPosition) { this.transformedPosition = Vector3.Zero(); } Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition); if (this.direction) { if (!this.transformedDirection) { this.transformedDirection = Vector3.Zero(); } 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. */ getDepthScale() { return 50; } /** * 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 */ // eslint-disable-next-line @typescript-eslint/no-unused-vars getShadowDirection(faceIndex) { return this.transformedDirection ? this.transformedDirection : this.direction; } /** * If computeTransformedInformation has been called, returns the ShadowLight absolute position in the world. Otherwise, returns the local position. * @returns the position vector in world space */ getAbsolutePosition() { 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 */ setDirectionToTarget(target) { this.direction = 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. */ getRotation() { this.direction.normalize(); const xaxis = Vector3.Cross(this.direction, Axis.Y); const yaxis = Vector3.Cross(xaxis, this.direction); return 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 */ needCube() { return false; } /** * Detects if the projection matrix requires to be recomputed this frame. * @returns true if it requires to be recomputed otherwise, false. */ needProjectionMatrixCompute() { return this._needProjectionMatrixCompute; } /** * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed. */ forceProjectionMatrixCompute() { this._needProjectionMatrixCompute = true; } /** @internal */ _initCache() { super._initCache(); this._cache.position = Vector3.Zero(); } /** @internal */ _isSynchronized() { 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 */ computeWorldMatrix(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 = Matrix.Identity(); } 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(); } 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 */ getDepthMinZ(activeCamera) { return this.shadowMinZ !== void 0 ? this.shadowMinZ : activeCamera?.minZ || 0; } /** * 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 */ getDepthMaxZ(activeCamera) { return this.shadowMaxZ !== void 0 ? this.shadowMaxZ : activeCamera?.maxZ || 1e4; } /** * Sets the shadow projection matrix in parameter to the generated projection matrix. * @param matrix The matrix 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 */ setShadowProjectionMatrix(matrix, viewMatrix, renderList) { if (this.customProjectionMatrixBuilder) { this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix); } else { this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList); } return this; } /** @internal */ _syncParentEnabledState() { super._syncParentEnabledState(); if (!this.parent || !this.parent.getWorldMatrix) { this.transformedPosition = null; this.transformedDirection = null; } } /** * Returns the view matrix. * @param faceIndex The index of the face for which we want to extract the view matrix. Only used for point light types. * @returns The view matrix. Can be null, if a view matrix cannot be defined for the type of light considered (as for a hemispherical light, for example). */ getViewMatrix(faceIndex) { const lightDirection = TmpVectors.Vector3[0]; let lightPosition = this.position; if (this.computeTransformedInformation()) { lightPosition = this.transformedPosition; } Vector3.NormalizeToRef(this.getShadowDirection(faceIndex), lightDirection); if (Math.abs(Vector3.Dot(lightDirection, Vector3.Up())) === 1) { lightDirection.z = 1e-13; } const lightTarget = TmpVectors.Vector3[1]; lightPosition.addToRef(lightDirection, lightTarget); Matrix.LookAtLHToRef(lightPosition, lightTarget, Vector3.Up(), this._viewMatrix); return this._viewMatrix; } /** * Returns the projection matrix. * Note that viewMatrix and renderList are optional and are only used by lights that calculate the projection matrix from a list of meshes (e.g. directional lights with automatic extents calculation). * @param viewMatrix The view transform matrix of the light (optional). * @param renderList The list of meshes to take into account when calculating the projection matrix (optional). * @returns The projection matrix. Can be null, if a projection matrix cannot be defined for the type of light considered (as for a hemispherical light, for example). */ getProjectionMatrix(viewMatrix, renderList) { this.setShadowProjectionMatrix(this._projectionMatrix, viewMatrix ?? this._viewMatrix, renderList ?? []); return this._projectionMatrix; } }; __decorate([ serializeAsVector3() ], ShadowLight.prototype, "position", null); __decorate([ serializeAsVector3() ], ShadowLight.prototype, "direction", null); __decorate([ serialize() ], ShadowLight.prototype, "shadowMinZ", null); __decorate([ serialize() ], ShadowLight.prototype, "shadowMaxZ", null); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/directionalLight.js var DirectionalLight; var init_directionalLight = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Lights/directionalLight.js"() { init_tslib_es6(); init_decorators(); init_math_vector(); init_node(); init_light(); init_shadowLight(); init_typeStore(); Node.AddNodeConstructor("Light_Type_1", (name260, scene) => { return () => new DirectionalLight(name260, Vector3.Zero(), scene); }); DirectionalLight = class extends ShadowLight { static { __name(this, "DirectionalLight"); } /** * Fix frustum size for the shadow generation. This is disabled if the value is 0. */ get shadowFrustumSize() { return this._shadowFrustumSize; } /** * Specifies a fix frustum size for the shadow generation. */ set shadowFrustumSize(value) { this._shadowFrustumSize = value; this.forceProjectionMatrixCompute(); } /** * 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 shadowOrthoScale() { 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 shadowOrthoScale(value) { this._shadowOrthoScale = value; this.forceProjectionMatrixCompute(); } /** * Gets or sets the orthoLeft property used to build the light frustum */ get orthoLeft() { return this._orthoLeft; } set orthoLeft(left) { this._orthoLeft = left; } /** * Gets or sets the orthoRight property used to build the light frustum */ get orthoRight() { return this._orthoRight; } set orthoRight(right) { this._orthoRight = right; } /** * Gets or sets the orthoTop property used to build the light frustum */ get orthoTop() { return this._orthoTop; } set orthoTop(top) { this._orthoTop = top; } /** * Gets or sets the orthoBottom property used to build the light frustum */ get orthoBottom() { return this._orthoBottom; } set orthoBottom(bottom) { this._orthoBottom = bottom; } /** * 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/features/featuresDeepDive/lights/lights_introduction * @param name The friendly name of the light * @param direction The direction of the light * @param scene The scene the light belongs to */ constructor(name260, direction, scene) { super(name260, scene); this._shadowFrustumSize = 0; this._shadowOrthoScale = 0.1; this.autoUpdateExtends = true; this.autoCalcShadowZBounds = false; 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); this.direction = direction; } /** * Returns the string "DirectionalLight". * @returns The class name */ getClassName() { return "DirectionalLight"; } /** * Returns the integer 1. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x */ // eslint-disable-next-line @typescript-eslint/naming-convention getTypeID() { return 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. * @param matrix * @param viewMatrix * @param renderList */ _setDefaultShadowProjectionMatrix(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. * @param matrix */ _setDefaultFixedFrustumShadowProjectionMatrix(matrix) { const activeCamera = this.getScene().activeCamera; if (!activeCamera) { return; } Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== void 0 ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== void 0 ? this.shadowMaxZ : activeCamera.maxZ, matrix, this.getScene().getEngine().isNDCHalfZRange); } /** * 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. * @param matrix * @param viewMatrix * @param renderList */ _setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList) { const activeCamera = this.getScene().activeCamera; if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) { const tempVector3 = Vector3.Zero(); this._orthoLeft = Number.MAX_VALUE; this._orthoRight = -Number.MAX_VALUE; this._orthoTop = -Number.MAX_VALUE; this._orthoBottom = Number.MAX_VALUE; let shadowMinZ = Number.MAX_VALUE; let shadowMaxZ = -Number.MAX_VALUE; for (let meshIndex = 0; meshIndex < renderList.length; meshIndex++) { const mesh = renderList[meshIndex]; if (!mesh) { continue; } const boundingInfo = mesh.getBoundingInfo(); const boundingBox = boundingInfo.boundingBox; for (let index = 0; index < boundingBox.vectorsWorld.length; index++) { 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; } } const xOffset = this._orthoRight - this._orthoLeft; const yOffset = this._orthoTop - this._orthoBottom; const minZ = this.shadowMinZ !== void 0 ? this.shadowMinZ : activeCamera?.minZ || 0; const maxZ = this.shadowMaxZ !== void 0 ? this.shadowMaxZ : activeCamera?.maxZ || 1e4; const useReverseDepthBuffer = this.getScene().getEngine().useReverseDepthBuffer; Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, useReverseDepthBuffer ? maxZ : minZ, useReverseDepthBuffer ? minZ : maxZ, matrix, this.getScene().getEngine().isNDCHalfZRange); } _buildUniformLayout() { 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 */ transferToEffect(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; } transferToNodeMaterialEffect(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. * (when not using reverse depth buffer / NDC half Z range) * @param _activeCamera The camera we are returning the min for (not used) * @returns the depth min z */ // eslint-disable-next-line @typescript-eslint/no-unused-vars getDepthMinZ(_activeCamera) { const engine = this._scene.getEngine(); return !engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 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. * (when not using reverse depth buffer / NDC half Z range) * @param _activeCamera The camera we are returning the max for * @returns the depth max z */ // eslint-disable-next-line @typescript-eslint/no-unused-vars getDepthMaxZ(_activeCamera) { const engine = this._scene.getEngine(); return engine.useReverseDepthBuffer && engine.isNDCHalfZRange ? 0 : 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 */ prepareLightSpecificDefines(defines, lightIndex) { defines["DIRLIGHT" + lightIndex] = true; } }; __decorate([ serialize() ], DirectionalLight.prototype, "shadowFrustumSize", null); __decorate([ serialize() ], DirectionalLight.prototype, "shadowOrthoScale", null); __decorate([ serialize() ], DirectionalLight.prototype, "autoUpdateExtends", void 0); __decorate([ serialize() ], DirectionalLight.prototype, "autoCalcShadowZBounds", void 0); __decorate([ serialize("orthoLeft") ], DirectionalLight.prototype, "_orthoLeft", void 0); __decorate([ serialize("orthoRight") ], DirectionalLight.prototype, "_orthoRight", void 0); __decorate([ serialize("orthoTop") ], DirectionalLight.prototype, "_orthoTop", void 0); __decorate([ serialize("orthoBottom") ], DirectionalLight.prototype, "_orthoBottom", void 0); RegisterClass("BABYLON.DirectionalLight", DirectionalLight); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/postProcessTask.js var FrameGraphPostProcessTask; var init_postProcessTask = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/PostProcesses/postProcessTask.js"() { init_frameGraphTask(); FrameGraphPostProcessTask = class extends FrameGraphTask { static { __name(this, "FrameGraphPostProcessTask"); } /** * The draw wrapper used by the post process */ get drawWrapper() { return this._postProcessDrawWrapper; } /** * Constructs a new post process task. * @param name Name of the task. * @param frameGraph The frame graph this task is associated with. * @param postProcess The post process to apply. */ constructor(name260, frameGraph, postProcess) { super(name260, frameGraph); this.sourceSamplingMode = 2; this.depthReadOnly = false; this.stencilReadOnly = false; this.disableColorWrite = false; this.drawBackFace = false; this.depthTest = true; this.postProcess = postProcess; this._postProcessDrawWrapper = this.postProcess.drawWrapper; this.outputTexture = this._frameGraph.textureManager.createDanglingHandle(); this.outputDepthAttachmentTexture = this._frameGraph.textureManager.createDanglingHandle(); } isReady() { return this.postProcess.isReady(); } record(skipCreationOfDisabledPasses = false, additionalExecute, additionalBindings) { if (this.sourceTexture === void 0 && this.targetTexture === void 0) { throw new Error(`FrameGraphPostProcessTask "${this.name}": sourceTexture or targetTexture is required`); } const sourceTextureCreationOptions = this.sourceTexture !== void 0 ? this._frameGraph.textureManager.getTextureCreationOptions(this.sourceTexture) : void 0; if (sourceTextureCreationOptions) { sourceTextureCreationOptions.options.samples = 1; } this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, this.targetTexture, this.name, sourceTextureCreationOptions); if (this.depthAttachmentTexture !== void 0) { this._frameGraph.textureManager.resolveDanglingHandle(this.outputDepthAttachmentTexture, this.depthAttachmentTexture); } if (sourceTextureCreationOptions) { const sourceSize = this._frameGraph.textureManager.getTextureAbsoluteDimensions(sourceTextureCreationOptions); this._sourceWidth = sourceSize.width; this._sourceHeight = sourceSize.height; } const outputTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.outputTexture); this._outputWidth = outputTextureDescription.size.width; this._outputHeight = outputTextureDescription.size.height; const pass = this._frameGraph.addRenderPass(this.name); pass.depthReadOnly = this.depthReadOnly; pass.stencilReadOnly = this.stencilReadOnly; pass.addDependencies(this.sourceTexture); pass.setRenderTarget(this.outputTexture); pass.setRenderTargetDepth(this.depthAttachmentTexture); pass.setExecuteFunc((context) => { if (this.sourceTexture !== void 0) { context.setTextureSamplingMode(this.sourceTexture, this.sourceSamplingMode); } additionalExecute?.(context); context.applyFullScreenEffect(this._postProcessDrawWrapper, () => { if (this.sourceTexture !== void 0) { context.bindTextureHandle(this._postProcessDrawWrapper.effect, "textureSampler", this.sourceTexture); } additionalBindings?.(context); this.postProcess.bind(); }, this.stencilState, this.disableColorWrite, this.drawBackFace, this.depthTest); }); if (!skipCreationOfDisabledPasses) { const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); passDisabled.depthReadOnly = this.depthReadOnly; passDisabled.stencilReadOnly = this.stencilReadOnly; passDisabled.addDependencies(this.sourceTexture); passDisabled.setRenderTarget(this.outputTexture); passDisabled.setRenderTargetDepth(this.depthAttachmentTexture); passDisabled.setExecuteFunc((context) => { if (this.sourceTexture !== void 0) { context.copyTexture(this.sourceTexture); } }); } return pass; } dispose() { this.postProcess.dispose(); super.dispose(); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/textureCreationOptions.js function textureSizeIsObject(size) { return size.width !== void 0; } function getDimensionsFromTextureSize(size) { if (textureSizeIsObject(size)) { return { width: size.width, height: size.height }; } return { width: size, height: size }; } var init_textureCreationOptions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/textureCreationOptions.js"() { __name(textureSizeIsObject, "textureSizeIsObject"); __name(getDimensionsFromTextureSize, "getDimensionsFromTextureSize"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/csmShadowGeneratorTask.js var FrameGraphCascadedShadowGeneratorTask; var init_csmShadowGeneratorTask = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/csmShadowGeneratorTask.js"() { init_cascadedShadowGenerator(); init_shadowGeneratorTask(); init_directionalLight(); init_thinMinMaxReducer(); init_postProcessTask(); init_textureCreationOptions(); FrameGraphCascadedShadowGeneratorTask = class extends FrameGraphShadowGeneratorTask { static { __name(this, "FrameGraphCascadedShadowGeneratorTask"); } /** * Checks if a shadow generator task is a cascaded shadow generator task. * @param task The task to check. * @returns True if the task is a cascaded shadow generator task, else false. */ static IsCascadedShadowGenerator(task) { return task.numCascades !== void 0; } /** * The number of cascades. */ get numCascades() { return this._numCascades; } set numCascades(value) { if (value === this._numCascades) { return; } this._numCascades = value; this._setupShadowGenerator(); } /** * Gets or sets a value indicating whether the shadow generator should display the cascades. */ get debug() { return this._debug; } set debug(value) { if (value === this._debug) { return; } this._debug = value; if (this._shadowGenerator) { this._shadowGenerator.debug = value; } } /** * Gets or sets a value indicating whether the shadow generator should stabilize the cascades. */ get stabilizeCascades() { return this._stabilizeCascades; } set stabilizeCascades(value) { if (value === this._stabilizeCascades) { return; } this._stabilizeCascades = value; if (this._shadowGenerator) { this._shadowGenerator.stabilizeCascades = value; } } /** * Gets or sets the lambda parameter of the shadow generator. */ get lambda() { return this._lambda; } set lambda(value) { if (value === this._lambda) { return; } this._lambda = value; if (this._shadowGenerator) { this._shadowGenerator.lambda = value; } } /** * Gets or sets the cascade blend percentage. */ get cascadeBlendPercentage() { return this._cascadeBlendPercentage; } set cascadeBlendPercentage(value) { if (value === this._cascadeBlendPercentage) { return; } this._cascadeBlendPercentage = value; if (this._shadowGenerator) { this._shadowGenerator.cascadeBlendPercentage = value; } } /** * Gets or sets a value indicating whether the shadow generator should use depth clamping. */ get depthClamp() { return this._depthClamp; } set depthClamp(value) { if (value === this._depthClamp) { return; } this._depthClamp = value; if (this._shadowGenerator) { this._shadowGenerator.depthClamp = value; } } /** * Gets or sets a value indicating whether the shadow generator should automatically calculate the depth bounds. */ get autoCalcDepthBounds() { return this._autoCalcDepthBounds; } set autoCalcDepthBounds(value) { if (value === this._autoCalcDepthBounds) { return; } this._autoCalcDepthBounds = value; this._currentAutoCalcDepthBoundsCounter = this._autoCalcDepthBoundsRefreshRate; if (!value) { this._shadowGenerator?.setMinMaxDistance(0, 1); } const passes = this.passes; for (let i = 0; i < passes.length - 1; ++i) { passes[i].disabled = !value; } } /** * 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... */ get autoCalcDepthBoundsRefreshRate() { return this._autoCalcDepthBoundsRefreshRate; } set autoCalcDepthBoundsRefreshRate(value) { this._autoCalcDepthBoundsRefreshRate = value; this._currentAutoCalcDepthBoundsCounter = this._autoCalcDepthBoundsRefreshRate; } /** * Gets or sets the maximum shadow Z value. */ get shadowMaxZ() { return this._shadowMaxZ; } set shadowMaxZ(value) { if (value === this._shadowMaxZ) { return; } this._shadowMaxZ = value; if (this._shadowGenerator) { this._shadowGenerator.shadowMaxZ = value; } } /** * Creates a new shadow generator task. * @param name The name of the task. * @param frameGraph The frame graph the task belongs to. * @param scene The scene to create the shadow generator for. */ constructor(name260, frameGraph, scene) { super(name260, frameGraph, scene); this.depthTextureType = 0; this._numCascades = CascadedShadowGenerator.DEFAULT_CASCADES_COUNT; this._debug = false; this._stabilizeCascades = false; this._lambda = 0.5; this._cascadeBlendPercentage = 0.1; this._depthClamp = true; this._autoCalcDepthBounds = false; this._currentAutoCalcDepthBoundsCounter = 0; this._autoCalcDepthBoundsRefreshRate = 1; this._shadowMaxZ = 1e4; this._thinMinMaxReducer = new ThinMinMaxReducer(scene); this._thinMinMaxReducer.onAfterReductionPerformed.add((minmax) => { if (!this._shadowGenerator) { return; } const camera = this.camera; let min = minmax.min, max = minmax.max; if (min >= max) { min = 0; max = 1; } else if (camera && this.depthTextureType !== 0) { if (this.depthTextureType === 2) { const engine = this._frameGraph.engine; const projectionMatrix = camera.getProjectionMatrix(); const p2z = projectionMatrix.m[10]; const p3z = projectionMatrix.m[14]; if (!engine.isNDCHalfZRange) { min = min * 2 - 1; max = max * 2 - 1; } min = p3z / (min - p2z); max = p3z / (max - p2z); } const zNear = camera.minZ; const zFar = camera.maxZ; min = (min - zNear) / (zFar - zNear); max = (max - zNear) / (zFar - zNear); } if (min !== this._shadowGenerator.minDistance || max !== this._shadowGenerator.maxDistance) { this._shadowGenerator.setMinMaxDistance(min, max); } }); } _createShadowGenerator() { if (!(this.light instanceof DirectionalLight)) { throw new Error(`FrameGraphCascadedShadowGeneratorTask ${this.name}: the CSM shadow generator only supports directional lights.`); } this._shadowGenerator = new CascadedShadowGenerator(this.mapSize, this.light, this.useFloat32TextureType, this.camera, this.useRedTextureFormat); this._shadowGenerator.numCascades = this._numCascades; } _setupShadowGenerator() { super._setupShadowGenerator(); const shadowGenerator = this._shadowGenerator; if (shadowGenerator === void 0) { return; } shadowGenerator.debug = this._debug; shadowGenerator.stabilizeCascades = this._stabilizeCascades; shadowGenerator.lambda = this._lambda; shadowGenerator.cascadeBlendPercentage = this._cascadeBlendPercentage; shadowGenerator.depthClamp = this._depthClamp; shadowGenerator.shadowMaxZ = this._shadowMaxZ; } record() { if (this.light === void 0 || this.objectList === void 0 || this.camera === void 0) { throw new Error(`FrameGraphCascadedShadowGeneratorTask ${this.name}: light, objectList and camera are required`); } if (this.depthTexture !== void 0) { const depthTextureCreationOptions = this._frameGraph.textureManager.getTextureCreationOptions(this.depthTexture); const size = !depthTextureCreationOptions.sizeIsPercentage ? textureSizeIsObject(depthTextureCreationOptions.size) ? depthTextureCreationOptions.size : { width: depthTextureCreationOptions.size, height: depthTextureCreationOptions.size } : this._frameGraph.textureManager.getAbsoluteDimensions(depthTextureCreationOptions.size); const width = size.width; const height = size.height; depthTextureCreationOptions.sizeIsPercentage = false; depthTextureCreationOptions.options.formats = [7]; depthTextureCreationOptions.options.samples = 1; this._thinMinMaxReducer.setTextureDimensions(width, height, this.depthTextureType); const reductionSteps = this._thinMinMaxReducer.reductionSteps; let targetTexture; this._frameGraph.addPass(`${this.name} Before Min Max Reduction`).setExecuteFunc((context) => { context.pushDebugGroup(`Min Max Reduction`); }); for (let i = 0; i < reductionSteps.length - 1; ++i) { const reductionStep = reductionSteps[i]; depthTextureCreationOptions.size = { width: reductionSteps[i + 1].textureWidth, height: reductionSteps[i + 1].textureHeight }; const postProcess = new FrameGraphPostProcessTask(reductionStep.name, this._frameGraph, reductionStep); postProcess.sourceTexture = i == 0 ? this.depthTexture : targetTexture; postProcess.sourceSamplingMode = 1; postProcess.targetTexture = this._frameGraph.textureManager.createRenderTargetTexture(`${this.name} ${reductionStep.name}`, depthTextureCreationOptions); postProcess.record(true); targetTexture = postProcess.outputTexture; } this._frameGraph.addPass(`${this.name} After Min Max Reduction`).setExecuteFunc((context) => { context.popDebugGroup(); if (this._autoCalcDepthBounds && this._currentAutoCalcDepthBoundsCounter >= 0) { if (++this._currentAutoCalcDepthBoundsCounter >= this._autoCalcDepthBoundsRefreshRate) { const minMaxTexture = context.getTextureFromHandle(targetTexture); if (minMaxTexture) { this._thinMinMaxReducer.readMinMax(minMaxTexture); } } this._currentAutoCalcDepthBoundsCounter %= this._autoCalcDepthBoundsRefreshRate; if (this._autoCalcDepthBoundsRefreshRate === 0) { this._currentAutoCalcDepthBoundsCounter = -1; } } }); } super.record(); } dispose() { super.dispose(); this._thinMinMaxReducer.dispose(); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/objectRendererTask.js var FrameGraphObjectRendererTask; var init_objectRendererTask = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/FrameGraph/Tasks/Rendering/objectRendererTask.js"() { init_frameGraphTypes(); init_frameGraphTask(); init_objectRenderer(); init_csmShadowGeneratorTask(); FrameGraphObjectRendererTask = class extends FrameGraphTask { static { __name(this, "FrameGraphObjectRendererTask"); } /** * Gets or sets the camera used to render the objects. */ get camera() { return this._camera; } set camera(camera) { this._camera = camera; this._renderer.activeCamera = this.camera; } /** * If image processing should be disabled (default is false). * false means that the default image processing configuration will be applied (the one from the scene) */ get disableImageProcessing() { return this._disableImageProcessing; } set disableImageProcessing(value) { if (value === this._disableImageProcessing) { return; } this._disableImageProcessing = value; this._renderer.disableImageProcessing = value; } /** * Define if particles should be rendered (default is true). */ get renderParticles() { return this._renderParticles; } set renderParticles(value) { if (value === this._renderParticles) { return; } this._renderParticles = value; this._renderer.renderParticles = value; } /** * Define if sprites should be rendered (default is true). */ get renderSprites() { return this._renderSprites; } set renderSprites(value) { if (value === this._renderSprites) { return; } this._renderSprites = value; this._renderer.renderSprites = value; } /** * Force checking the layerMask property even if a custom list of meshes is provided (ie. if renderList is not undefined). Default is true. */ get forceLayerMaskCheck() { return this._forceLayerMaskCheck; } set forceLayerMaskCheck(value) { if (value === this._forceLayerMaskCheck) { return; } this._forceLayerMaskCheck = value; this._renderer.forceLayerMaskCheck = value; } /** * Enables the rendering of bounding boxes for meshes (still subject to Mesh.showBoundingBox or scene.forceShowBoundingBoxes). Default is true. */ get enableBoundingBoxRendering() { return this._enableBoundingBoxRendering; } set enableBoundingBoxRendering(value) { if (value === this._enableBoundingBoxRendering) { return; } this._enableBoundingBoxRendering = value; this._renderer.enableBoundingBoxRendering = value; } /** * Enables the rendering of outlines/overlays for meshes (still subject to Mesh.renderOutline/Mesh.renderOverlay). Default is true. */ get enableOutlineRendering() { return this._enableOutlineRendering; } set enableOutlineRendering(value) { if (value === this._enableOutlineRendering) { return; } this._enableOutlineRendering = value; this._renderer.enableOutlineRendering = value; } /** * The object renderer used to render the objects. */ get objectRenderer() { return this._renderer; } get name() { return this._name; } set name(value) { this._name = value; if (this._renderer) { this._renderer.name = value; } } /** * Constructs a new object renderer task. * @param name The name of the task. * @param frameGraph The frame graph the task belongs to. * @param scene The scene the frame graph is associated with. * @param options The options of the object renderer. * @param existingObjectRenderer An existing object renderer to use (optional). If provided, the options parameter will be ignored. */ constructor(name260, frameGraph, scene, options, existingObjectRenderer) { super(name260, frameGraph); this.shadowGenerators = []; this.depthTest = true; this.depthWrite = true; this.disableShadows = false; this._disableImageProcessing = false; this.isMainObjectRenderer = false; this._renderParticles = true; this._renderSprites = true; this._forceLayerMaskCheck = true; this._enableBoundingBoxRendering = true; this._enableOutlineRendering = true; this._onBeforeRenderObservable = null; this._onAfterRenderObservable = null; this._externalObjectRenderer = false; this._scene = scene; this._engine = scene.getEngine(); this._externalObjectRenderer = !!existingObjectRenderer; this._renderer = existingObjectRenderer ?? new ObjectRenderer(name260, scene, options); this.name = name260; this._renderer.disableImageProcessing = this._disableImageProcessing; this._renderer.renderParticles = this._renderParticles; this._renderer.renderSprites = this._renderSprites; this._renderer.enableBoundingBoxRendering = this._enableBoundingBoxRendering; this._renderer.forceLayerMaskCheck = this._forceLayerMaskCheck; if (!this._externalObjectRenderer) { this._renderer.onBeforeRenderingManagerRenderObservable.add(() => { if (!this._renderer.options.doNotChangeAspectRatio) { scene.updateTransformMatrix(true); } }); } this.outputTexture = this._frameGraph.textureManager.createDanglingHandle(); this.outputDepthTexture = this._frameGraph.textureManager.createDanglingHandle(); } isReady() { return this._renderer.isReadyForRendering(this._textureWidth, this._textureHeight); } record(skipCreationOfDisabledPasses = false, additionalExecute) { if (this.targetTexture === void 0 || this.objectList === void 0) { throw new Error(`FrameGraphObjectRendererTask ${this.name}: targetTexture and objectList are required`); } this._renderer.renderList = this.objectList.meshes; this._renderer.particleSystemList = this.objectList.particleSystems; const targetTextures = Array.isArray(this.targetTexture) ? this.targetTexture : [this.targetTexture]; const outputTextureDescription = this._frameGraph.textureManager.getTextureDescription(targetTextures[0]); let depthEnabled = false; if (this.depthTexture !== void 0) { if (this.depthTexture === backbufferDepthStencilTextureHandle && (targetTextures[0] !== backbufferColorTextureHandle || targetTextures.length > 1)) { throw new Error(`FrameGraphObjectRendererTask ${this.name}: the back buffer color texture is the only color texture allowed when the depth is the back buffer depth/stencil`); } if (this.depthTexture !== backbufferDepthStencilTextureHandle && targetTextures[0] === backbufferColorTextureHandle) { throw new Error(`FrameGraphObjectRendererTask ${this.name}: the back buffer depth/stencil texture is the only depth texture allowed when the target is the back buffer color`); } const depthTextureDescription = this._frameGraph.textureManager.getTextureDescription(this.depthTexture); if (depthTextureDescription.options.samples !== outputTextureDescription.options.samples) { throw new Error(`FrameGraphObjectRendererTask ${this.name}: the depth texture and the output texture must have the same number of samples`); } depthEnabled = true; } this._frameGraph.textureManager.resolveDanglingHandle(this.outputTexture, targetTextures[0]); if (this.depthTexture !== void 0) { this._frameGraph.textureManager.resolveDanglingHandle(this.outputDepthTexture, this.depthTexture); } this._textureWidth = outputTextureDescription.size.width; this._textureHeight = outputTextureDescription.size.height; this._setLightsForShadow(); const pass = this._frameGraph.addRenderPass(this.name); pass.setRenderTarget(targetTextures); pass.setRenderTargetDepth(this.depthTexture); pass.setExecuteFunc((context) => { this._renderer.renderList = this.objectList.meshes; this._renderer.particleSystemList = this.objectList.particleSystems; const boundingBoxRenderer = this.getBoundingBoxRenderer?.(); const currentBoundingBoxMeshList = boundingBoxRenderer && boundingBoxRenderer.renderList.length > 0 ? boundingBoxRenderer.renderList.data.slice() : []; if (boundingBoxRenderer) { currentBoundingBoxMeshList.length = boundingBoxRenderer.renderList.length; } context.setDepthStates(this.depthTest && depthEnabled, this.depthWrite && depthEnabled); const camera = this._renderer.activeCamera; if (camera && camera.cameraRigMode !== 0 && !camera._renderingMultiview) { for (let index = 0; index < camera._rigCameras.length; index++) { const rigCamera = camera._rigCameras[index]; rigCamera.rigParent = void 0; this._renderer.activeCamera = rigCamera; context.render(this._renderer, this._textureWidth, this._textureHeight); rigCamera.rigParent = camera; } this._renderer.activeCamera = camera; } else { context.render(this._renderer, this._textureWidth, this._textureHeight); } additionalExecute?.(context); if (boundingBoxRenderer) { boundingBoxRenderer.renderList.data = currentBoundingBoxMeshList; boundingBoxRenderer.renderList.length = currentBoundingBoxMeshList.length; } }); if (!skipCreationOfDisabledPasses) { const passDisabled = this._frameGraph.addRenderPass(this.name + "_disabled", true); passDisabled.setRenderTarget(targetTextures); passDisabled.setRenderTargetDepth(this.depthTexture); passDisabled.setExecuteFunc((_context) => { }); } return pass; } dispose() { this._renderer.onBeforeRenderObservable.remove(this._onBeforeRenderObservable); this._renderer.onAfterRenderObservable.remove(this._onAfterRenderObservable); if (!this._externalObjectRenderer) { this._renderer.dispose(); } super.dispose(); } _setLightsForShadow() { const lightsForShadow = /* @__PURE__ */ new Set(); const shadowEnabled = /* @__PURE__ */ new Map(); if (this.shadowGenerators) { for (const shadowGeneratorTask of this.shadowGenerators) { const shadowGenerator = shadowGeneratorTask.shadowGenerator; const light = shadowGenerator.getLight(); if (light.isEnabled() && light.shadowEnabled) { lightsForShadow.add(light); if (FrameGraphCascadedShadowGeneratorTask.IsCascadedShadowGenerator(shadowGeneratorTask)) { light._shadowGenerators.set(shadowGeneratorTask.camera, shadowGenerator); } else { light._shadowGenerators.set(null, shadowGenerator); } } } } this._renderer.onBeforeRenderObservable.remove(this._onBeforeRenderObservable); this._onBeforeRenderObservable = this._renderer.onBeforeRenderObservable.add(() => { for (let i = 0; i < this._scene.lights.length; i++) { const light = this._scene.lights[i]; if (!light.setShadowProjectionMatrix) { continue; } shadowEnabled.set(light, light.shadowEnabled); light.shadowEnabled = !this.disableShadows && lightsForShadow.has(light); } }); this._renderer.onAfterRenderObservable.remove(this._onAfterRenderObservable); this._onAfterRenderObservable = this._renderer.onAfterRenderObservable.add(() => { for (let i = 0; i < this._scene.lights.length; i++) { const light = this._scene.lights[i]; if (!light.setShadowProjectionMatrix) { continue; } light.shadowEnabled = shadowEnabled.get(light); } }); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/scene.js var ScenePerformancePriority, Scene; var init_scene = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/scene.js"() { init_tools(); init_precisionDate(); init_observable(); init_smartArray(); init_stringDictionary(); init_tags(); init_math_vector(); init_imageProcessingConfiguration(); init_uniformBuffer(); init_pickingInfo(); init_actionEvent(); init_postProcessManager(); init_floatingOriginMatrixOverrides(); init_renderingManager(); init_sceneComponent(); init_domManagement(); init_engineStore(); init_devTools(); init_scene_inputManager(); init_perfCounter(); init_math_color(); init_math_frustum(); init_uniqueIdGenerator(); init_fileTools(); init_lightConstants(); init_arrayTools(); init_pointerPickingConfiguration(); init_logger(); init_typeStore(); init_objectRendererTask(); init_timingTools(); (function(ScenePerformancePriority2) { ScenePerformancePriority2[ScenePerformancePriority2["BackwardCompatible"] = 0] = "BackwardCompatible"; ScenePerformancePriority2[ScenePerformancePriority2["Intermediate"] = 1] = "Intermediate"; ScenePerformancePriority2[ScenePerformancePriority2["Aggressive"] = 2] = "Aggressive"; })(ScenePerformancePriority || (ScenePerformancePriority = {})); Scene = class _Scene { static { __name(this, "Scene"); } // eslint-disable-next-line jsdoc/require-returns-check /** * Factory used to create the default material. * @param scene The scene to create the material for * @returns The default material */ static DefaultMaterialFactory(scene) { throw _WarnImport("StandardMaterial"); } // eslint-disable-next-line jsdoc/require-returns-check /** * Factory used to create the a collision coordinator. * @returns The collision coordinator */ static CollisionCoordinatorFactory() { throw _WarnImport("DefaultCollisionCoordinator"); } /** * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0)) */ get clearColor() { return this._clearColor; } set clearColor(value) { if (value !== this._clearColor) { this._clearColor = value; this.onClearColorChangedObservable.notifyObservers(this._clearColor); } } /** * Default image processing configuration used either in the rendering * Forward main pass or through the imageProcessingPostProcess if present. * As in the majority of the scene they are the same (exception for multi camera), * this is easier to reference from here than from all the materials and post process. * * No setter as we it is a shared configuration, you can set the values instead. */ get imageProcessingConfiguration() { return this._imageProcessingConfiguration; } /** * Gets or sets a value indicating how to treat performance relatively to ease of use and backward compatibility */ get performancePriority() { return this._performancePriority; } set performancePriority(value) { if (value === this._performancePriority) { return; } this._performancePriority = value; switch (value) { case 0: this.skipFrustumClipping = false; this._renderingManager.maintainStateBetweenFrames = false; this.skipPointerMovePicking = false; this.autoClear = true; break; case 1: this.skipFrustumClipping = false; this._renderingManager.maintainStateBetweenFrames = false; this.skipPointerMovePicking = true; this.autoClear = false; break; case 2: this.skipFrustumClipping = true; this._renderingManager.maintainStateBetweenFrames = true; this.skipPointerMovePicking = true; this.autoClear = false; break; } this.onScenePerformancePriorityChangedObservable.notifyObservers(value); } /** * Gets or sets a boolean indicating if all rendering must be done in wireframe */ set forceWireframe(value) { if (this._forceWireframe === value) { return; } this._forceWireframe = value; this.markAllMaterialsAsDirty(16); } get forceWireframe() { return this._forceWireframe; } /** * Gets or sets a boolean indicating if we should skip the frustum clipping part of the active meshes selection */ set skipFrustumClipping(value) { if (this._skipFrustumClipping === value) { return; } this._skipFrustumClipping = value; } get skipFrustumClipping() { return this._skipFrustumClipping; } /** * Gets or sets a boolean indicating if all rendering must be done in point cloud */ set forcePointsCloud(value) { if (this._forcePointsCloud === value) { return; } this._forcePointsCloud = value; this.markAllMaterialsAsDirty(16); } get forcePointsCloud() { return this._forcePointsCloud; } /** * Texture used in all pbr material as the reflection texture. * As in the majority of the scene they are the same (exception for multi room and so on), * this is easier to reference from here than from all the materials. */ get environmentTexture() { return this._environmentTexture; } /** * Texture used in all pbr material as the reflection texture. * As in the majority of the scene they are the same (exception for multi room and so on), * this is easier to set here than in all the materials. */ set environmentTexture(value) { if (this._environmentTexture === value) { return; } this._environmentTexture = value; this.onEnvironmentTextureChangedObservable.notifyObservers(value); this.markAllMaterialsAsDirty(1); } /** * @returns all meshes, lights, cameras, transformNodes and bones */ getNodes() { let nodes = []; nodes = nodes.concat(this.meshes); nodes = nodes.concat(this.lights); nodes = nodes.concat(this.cameras); nodes = nodes.concat(this.transformNodes); for (const skeleton of this.skeletons) { nodes = nodes.concat(skeleton.bones); } return nodes; } /** * Gets or sets the animation properties override */ get animationPropertiesOverride() { return this._animationPropertiesOverride; } set animationPropertiesOverride(value) { this._animationPropertiesOverride = value; } /** Sets a function to be executed when this scene is disposed. */ set onDispose(callback) { if (this._onDisposeObserver) { this.onDisposeObservable.remove(this._onDisposeObserver); } this._onDisposeObserver = this.onDisposeObservable.add(callback); } /** Sets a function to be executed before rendering this scene */ set beforeRender(callback) { if (this._onBeforeRenderObserver) { this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); } if (callback) { this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); } } /** Sets a function to be executed after rendering this scene */ set afterRender(callback) { if (this._onAfterRenderObserver) { this.onAfterRenderObservable.remove(this._onAfterRenderObserver); } if (callback) { this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); } } /** Sets a function to be executed before rendering a camera*/ set beforeCameraRender(callback) { if (this._onBeforeCameraRenderObserver) { this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver); } this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback); } /** Sets a function to be executed after rendering a camera*/ set afterCameraRender(callback) { if (this._onAfterCameraRenderObserver) { this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver); } this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback); } /** * Gets or sets a predicate used to select candidate meshes for a pointer down event */ get pointerDownPredicate() { return this._pointerPickingConfiguration.pointerDownPredicate; } set pointerDownPredicate(value) { this._pointerPickingConfiguration.pointerDownPredicate = value; } /** * Gets or sets a predicate used to select candidate meshes for a pointer up event */ get pointerUpPredicate() { return this._pointerPickingConfiguration.pointerUpPredicate; } set pointerUpPredicate(value) { this._pointerPickingConfiguration.pointerUpPredicate = value; } /** * Gets or sets a predicate used to select candidate meshes for a pointer move event */ get pointerMovePredicate() { return this._pointerPickingConfiguration.pointerMovePredicate; } set pointerMovePredicate(value) { this._pointerPickingConfiguration.pointerMovePredicate = value; } /** * Gets or sets a predicate used to select candidate meshes for a pointer down event */ get pointerDownFastCheck() { return this._pointerPickingConfiguration.pointerDownFastCheck; } set pointerDownFastCheck(value) { this._pointerPickingConfiguration.pointerDownFastCheck = value; } /** * Gets or sets a predicate used to select candidate meshes for a pointer up event */ get pointerUpFastCheck() { return this._pointerPickingConfiguration.pointerUpFastCheck; } set pointerUpFastCheck(value) { this._pointerPickingConfiguration.pointerUpFastCheck = value; } /** * Gets or sets a predicate used to select candidate meshes for a pointer move event */ get pointerMoveFastCheck() { return this._pointerPickingConfiguration.pointerMoveFastCheck; } set pointerMoveFastCheck(value) { this._pointerPickingConfiguration.pointerMoveFastCheck = value; } /** * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer move event occurs. */ get skipPointerMovePicking() { return this._pointerPickingConfiguration.skipPointerMovePicking; } set skipPointerMovePicking(value) { this._pointerPickingConfiguration.skipPointerMovePicking = value; } /** * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer down event occurs. */ get skipPointerDownPicking() { return this._pointerPickingConfiguration.skipPointerDownPicking; } set skipPointerDownPicking(value) { this._pointerPickingConfiguration.skipPointerDownPicking = value; } /** * Gets or sets a boolean indicating if the user want to entirely skip the picking phase when a pointer up event occurs. Off by default. */ get skipPointerUpPicking() { return this._pointerPickingConfiguration.skipPointerUpPicking; } set skipPointerUpPicking(value) { this._pointerPickingConfiguration.skipPointerUpPicking = value; } /** * Gets the pointer coordinates without any translation (ie. straight out of the pointer event) */ get unTranslatedPointer() { return this._inputManager.unTranslatedPointer; } /** * Gets or sets the distance in pixel that you have to move to prevent some events. Default is 10 pixels */ static get DragMovementThreshold() { return InputManager.DragMovementThreshold; } static set DragMovementThreshold(value) { InputManager.DragMovementThreshold = value; } /** * Time in milliseconds to wait to raise long press events if button is still pressed. Default is 500 ms */ static get LongPressDelay() { return InputManager.LongPressDelay; } static set LongPressDelay(value) { InputManager.LongPressDelay = value; } /** * Time in milliseconds to wait to raise long press events if button is still pressed. Default is 300 ms */ static get DoubleClickDelay() { return InputManager.DoubleClickDelay; } static set DoubleClickDelay(value) { InputManager.DoubleClickDelay = value; } /** If you need to check double click without raising a single click at first click, enable this flag */ static get ExclusiveDoubleClickMode() { return InputManager.ExclusiveDoubleClickMode; } static set ExclusiveDoubleClickMode(value) { InputManager.ExclusiveDoubleClickMode = value; } /** * Bind the current view position to an effect. * @param effect The effect to be bound * @param variableName name of the shader variable that will hold the eye position * @param isVector3 true to indicates that variableName is a Vector3 and not a Vector4 * @returns the computed eye position */ bindEyePosition(effect, variableName = "vEyePosition", isVector3 = false) { const eyePosition = this._forcedViewPosition ? this._forcedViewPosition : this._mirroredCameraPosition ? this._mirroredCameraPosition : this.activeCamera?.globalPosition ?? Vector3.ZeroReadOnly; const invertNormal = this.useRightHandedSystem === (this._mirroredCameraPosition != null); const offset = this.floatingOriginOffset; const eyePos = this._tempVect4.set(eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1); const offsetEyePos = eyePos.subtractFromFloatsToRef(offset.x, offset.y, offset.z, 0, TmpVectors.Vector4[1]); if (effect) { if (isVector3) { effect.setFloat3(variableName, offsetEyePos.x, offsetEyePos.y, offsetEyePos.z); } else { effect.setVector4(variableName, offsetEyePos); } } return eyePos; } /** * Update the scene ubo before it can be used in rendering processing * @returns the scene UniformBuffer */ finalizeSceneUbo() { const ubo = this.getSceneUniformBuffer(); const eyePosition = this.bindEyePosition(null); const offset = this.floatingOriginOffset; ubo.updateFloat4("vEyePosition", eyePosition.x - offset.x, eyePosition.y - offset.y, eyePosition.z - offset.z, eyePosition.w); ubo.update(); return ubo; } /** * Gets or sets a boolean indicating if the scene must use right-handed coordinates system */ set useRightHandedSystem(value) { if (this._useRightHandedSystem === value) { return; } this._useRightHandedSystem = value; this.markAllMaterialsAsDirty(16); } get useRightHandedSystem() { return this._useRightHandedSystem; } /** * Sets the step Id used by deterministic lock step * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep * @param newStepId defines the step Id */ setStepId(newStepId) { this._currentStepId = newStepId; } /** * Gets the step Id used by deterministic lock step * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep * @returns the step Id */ getStepId() { return this._currentStepId; } /** * Gets the internal step used by deterministic lock step * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep * @returns the internal step */ getInternalStep() { return this._currentInternalStep; } /** * Gets or sets a boolean indicating if fog is enabled on this scene * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog * (Default is true) */ set fogEnabled(value) { if (this._fogEnabled === value) { return; } this._fogEnabled = value; this.markAllMaterialsAsDirty(16); } get fogEnabled() { return this._fogEnabled; } /** * Gets or sets the fog mode to use * @see https://doc.babylonjs.com/features/featuresDeepDive/environment/environment_introduction#fog * | mode | value | * | --- | --- | * | FOGMODE_NONE | 0 | * | FOGMODE_EXP | 1 | * | FOGMODE_EXP2 | 2 | * | FOGMODE_LINEAR | 3 | */ set fogMode(value) { if (this._fogMode === value) { return; } this._fogMode = value; this.markAllMaterialsAsDirty(16); } get fogMode() { return this._fogMode; } /** * Flag indicating that the frame buffer binding is handled by another component */ get prePass() { return !!this.prePassRenderer && this.prePassRenderer.defaultRT.enabled; } /** * Gets or sets a boolean indicating if shadows are enabled on this scene */ set shadowsEnabled(value) { if (this._shadowsEnabled === value) { return; } this._shadowsEnabled = value; this.markAllMaterialsAsDirty(2); } get shadowsEnabled() { return this._shadowsEnabled; } /** * Gets or sets a boolean indicating if lights are enabled on this scene */ set lightsEnabled(value) { if (this._lightsEnabled === value) { return; } this._lightsEnabled = value; this.markAllMaterialsAsDirty(2); } get lightsEnabled() { return this._lightsEnabled; } /** All of the active cameras added to this scene. */ get activeCameras() { return this._activeCameras; } set activeCameras(cameras) { if (this._unObserveActiveCameras) { this._unObserveActiveCameras(); this._unObserveActiveCameras = null; } if (cameras) { this._unObserveActiveCameras = _ObserveArray(cameras, () => { this.onActiveCamerasChanged.notifyObservers(this); }); } this._activeCameras = cameras; } /** Gets or sets the current active camera */ get activeCamera() { return this._activeCamera; } set activeCamera(value) { if (value === this._activeCamera) { return; } this._activeCamera = value; this.onActiveCameraChanged.notifyObservers(this); } /** @internal */ get _hasDefaultMaterial() { return _Scene.DefaultMaterialFactory !== _Scene._OriginalDefaultMaterialFactory; } /** The default material used on meshes when no material is affected */ get defaultMaterial() { if (!this._defaultMaterial) { this._defaultMaterial = _Scene.DefaultMaterialFactory(this); } return this._defaultMaterial; } /** The default material used on meshes when no material is affected */ set defaultMaterial(value) { this._defaultMaterial = value; } /** * Gets or sets a boolean indicating if textures are enabled on this scene */ set texturesEnabled(value) { if (this._texturesEnabled === value) { return; } this._texturesEnabled = value; this.markAllMaterialsAsDirty(1); } get texturesEnabled() { return this._texturesEnabled; } /** * Gets or sets the frame graph used to render the scene. If set, the scene will use the frame graph to render the scene instead of the default render loop. */ get frameGraph() { return this._frameGraph; } set frameGraph(value) { if (this._frameGraph) { this._frameGraph = value; if (!value) { this.customRenderFunction = this._currentCustomRenderFunction; } return; } this._frameGraph = value; if (value) { this._currentCustomRenderFunction = this.customRenderFunction; this.customRenderFunction = this._renderWithFrameGraph; this.activeCamera = null; } } /** * Gets or sets a boolean indicating if skeletons are enabled on this scene */ set skeletonsEnabled(value) { if (this._skeletonsEnabled === value) { return; } this._skeletonsEnabled = value; this.markAllMaterialsAsDirty(8); } get skeletonsEnabled() { return this._skeletonsEnabled; } /** @internal */ get collisionCoordinator() { if (!this._collisionCoordinator) { this._collisionCoordinator = _Scene.CollisionCoordinatorFactory(); this._collisionCoordinator.init(this); } return this._collisionCoordinator; } /** * Gets the scene's rendering manager */ get renderingManager() { return this._renderingManager; } /** * Gets the list of frustum planes (built from the active camera) */ get frustumPlanes() { return this._frustumPlanes; } /** * Registers the transient components if needed. */ _registerTransientComponents() { if (this._transientComponents.length > 0) { for (const component of this._transientComponents) { component.register(); } this._transientComponents.length = 0; } } /** * @internal * Add a component to the scene. * Note that the ccomponent could be registered on th next frame if this is called after * the register component stage. * @param component Defines the component to add to the scene */ _addComponent(component) { this._components.push(component); this._transientComponents.push(component); const serializableComponent = component; if (serializableComponent.addFromContainer && serializableComponent.serialize) { this._serializableComponents.push(serializableComponent); } } /** * @internal * Gets a component from the scene. * @param name defines the name of the component to retrieve * @returns the component or null if not present */ _getComponent(name260) { for (const component of this._components) { if (component.name === name260) { return component; } } return null; } /** * Gets the unique id of the scene */ get uniqueId() { return this._uniqueId; } /** * Creates a new Scene * @param engine defines the engine to use to render this scene * @param options defines the scene options */ constructor(engine, options) { this._inputManager = new InputManager(this); this.cameraToUseForPointers = null; this._isScene = true; this._blockEntityCollection = false; this.autoClear = true; this.autoClearDepthAndStencil = true; this._clearColor = new Color4(0.2, 0.2, 0.3, 1); this._tempVect4 = new Vector4(); this.onClearColorChangedObservable = new Observable(); this.ambientColor = new Color3(0, 0, 0); this.environmentIntensity = 1; this.iblIntensity = 1; this._performancePriority = 0; this.onScenePerformancePriorityChangedObservable = new Observable(); this._forceWireframe = false; this._skipFrustumClipping = false; this._forcePointsCloud = false; this.rootNodes = []; this.cameras = []; this.lights = []; this.meshes = []; this.skeletons = []; this.particleSystems = []; this.animations = []; this.animationGroups = []; this.multiMaterials = []; this.materials = []; this.morphTargetManagers = []; this.geometries = []; this.transformNodes = []; this.actionManagers = []; this.objectRenderers = []; this.textures = []; this._environmentTexture = null; this.postProcesses = []; this.effectLayers = []; this.sounds = null; this.layers = []; this.lensFlareSystems = []; this.proceduralTextures = []; this.animationsEnabled = true; this._animationPropertiesOverride = null; this.useConstantAnimationDeltaTime = false; this.constantlyUpdateMeshUnderPointer = false; this.hoverCursor = "pointer"; this.defaultCursor = ""; this.doNotHandleCursors = false; this.preventDefaultOnPointerDown = true; this.preventDefaultOnPointerUp = true; this.metadata = null; this.reservedDataStore = null; this.disableOfflineSupportExceptionRules = []; this.onDisposeObservable = new Observable(); this._onDisposeObserver = null; this.onBeforeRenderObservable = new Observable(); this._onBeforeRenderObserver = null; this.onAfterRenderObservable = new Observable(); this.onAfterRenderCameraObservable = new Observable(); this._onAfterRenderObserver = null; this.onBeforeAnimationsObservable = new Observable(); this.onAfterAnimationsObservable = new Observable(); this.onBeforeDrawPhaseObservable = new Observable(); this.onAfterDrawPhaseObservable = new Observable(); this.onReadyObservable = new Observable(); this.onBeforeCameraRenderObservable = new Observable(); this._onBeforeCameraRenderObserver = null; this.onAfterCameraRenderObservable = new Observable(); this._onAfterCameraRenderObserver = null; this.onBeforeActiveMeshesEvaluationObservable = new Observable(); this.onAfterActiveMeshesEvaluationObservable = new Observable(); this.onBeforeParticlesRenderingObservable = new Observable(); this.onAfterParticlesRenderingObservable = new Observable(); this.onDataLoadedObservable = new Observable(); this.onNewCameraAddedObservable = new Observable(); this.onCameraRemovedObservable = new Observable(); this.onNewLightAddedObservable = new Observable(); this.onLightRemovedObservable = new Observable(); this.onNewGeometryAddedObservable = new Observable(); this.onGeometryRemovedObservable = new Observable(); this.onNewTransformNodeAddedObservable = new Observable(); this.onTransformNodeRemovedObservable = new Observable(); this.onNewMeshAddedObservable = new Observable(); this.onMeshRemovedObservable = new Observable(); this.onNewSkeletonAddedObservable = new Observable(); this.onSkeletonRemovedObservable = new Observable(); this.onNewParticleSystemAddedObservable = new Observable(); this.onParticleSystemRemovedObservable = new Observable(); this.onNewAnimationGroupAddedObservable = new Observable(); this.onAnimationGroupRemovedObservable = new Observable(); this.onNewMaterialAddedObservable = new Observable(); this.onNewMultiMaterialAddedObservable = new Observable(); this.onMaterialRemovedObservable = new Observable(); this.onMultiMaterialRemovedObservable = new Observable(); this.onNewTextureAddedObservable = new Observable(); this.onTextureRemovedObservable = new Observable(); this.onNewFrameGraphAddedObservable = new Observable(); this.onFrameGraphRemovedObservable = new Observable(); this.onNewObjectRendererAddedObservable = new Observable(); this.onObjectRendererRemovedObservable = new Observable(); this.onNewPostProcessAddedObservable = new Observable(); this.onPostProcessRemovedObservable = new Observable(); this.onNewEffectLayerAddedObservable = new Observable(); this.onEffectLayerRemovedObservable = new Observable(); this.onBeforeRenderTargetsRenderObservable = new Observable(); this.onAfterRenderTargetsRenderObservable = new Observable(); this.onBeforeStepObservable = new Observable(); this.onAfterStepObservable = new Observable(); this.onActiveCameraChanged = new Observable(); this.onActiveCamerasChanged = new Observable(); this.onBeforeRenderingGroupObservable = new Observable(); this.onAfterRenderingGroupObservable = new Observable(); this.onMeshImportedObservable = new Observable(); this.onAnimationFileImportedObservable = new Observable(); this.onEnvironmentTextureChangedObservable = new Observable(); this.onMeshUnderPointerUpdatedObservable = new Observable(); this._registeredForLateAnimationBindings = new SmartArrayNoDuplicate(256); this._pointerPickingConfiguration = new PointerPickingConfiguration(); this.onPrePointerObservable = new Observable(); this.onPointerObservable = new Observable(); this.onPreKeyboardObservable = new Observable(); this.onKeyboardObservable = new Observable(); this._useRightHandedSystem = false; this._timeAccumulator = 0; this._currentStepId = 0; this._currentInternalStep = 0; this._fogEnabled = true; this._fogMode = _Scene.FOGMODE_NONE; this.fogColor = new Color3(0.2, 0.2, 0.3); this.fogDensity = 0.1; this.fogStart = 0; this.fogEnd = 1e3; this.needsPreviousWorldMatrices = false; this._shadowsEnabled = true; this._lightsEnabled = true; this._unObserveActiveCameras = null; this._texturesEnabled = true; this._frameGraph = null; this.frameGraphs = []; this.physicsEnabled = true; this.particlesEnabled = true; this.spritesEnabled = true; this._skeletonsEnabled = true; this.lensFlaresEnabled = true; this.collisionsEnabled = true; this.gravity = new Vector3(0, -9.807, 0); this.postProcessesEnabled = true; this.renderTargetsEnabled = true; this.dumpNextRenderTargets = false; this.customRenderTargets = []; this.importedMeshesFiles = []; this.probesEnabled = true; this._meshesForIntersections = new SmartArrayNoDuplicate(256); this.proceduralTexturesEnabled = true; this._totalVertices = new PerfCounter(); this._activeIndices = new PerfCounter(); this._activeParticles = new PerfCounter(); this._activeBones = new PerfCounter(); this._animationTime = 0; this.animationTimeScale = 1; this._renderId = 0; this._frameId = 0; this._executeWhenReadyTimeoutId = null; this._intermediateRendering = false; this._defaultFrameBufferCleared = false; this._viewUpdateFlag = -1; this._projectionUpdateFlag = -1; this._toBeDisposed = new Array(256); this._activeRequests = new Array(); this._pendingData = []; this._isDisposed = false; this.dispatchAllSubMeshesOfActiveMeshes = false; this._activeMeshes = new SmartArray(256); this._processedMaterials = new SmartArray(256); this._renderTargets = new SmartArrayNoDuplicate(256); this._materialsRenderTargets = new SmartArrayNoDuplicate(256); this._activeParticleSystems = new SmartArray(256); this._activeSkeletons = new SmartArrayNoDuplicate(32); this._softwareSkinnedMeshes = new SmartArrayNoDuplicate(32); this._activeAnimatables = new Array(); this._transformMatrix = Matrix.Zero(); this.requireLightSorting = false; this._components = []; this._serializableComponents = []; this._transientComponents = []; this._beforeCameraUpdateStage = Stage.Create(); this._beforeClearStage = Stage.Create(); this._beforeRenderTargetClearStage = Stage.Create(); this._gatherRenderTargetsStage = Stage.Create(); this._gatherActiveCameraRenderTargetsStage = Stage.Create(); this._isReadyForMeshStage = Stage.Create(); this._beforeEvaluateActiveMeshStage = Stage.Create(); this._evaluateSubMeshStage = Stage.Create(); this._preActiveMeshStage = Stage.Create(); this._cameraDrawRenderTargetStage = Stage.Create(); this._beforeCameraDrawStage = Stage.Create(); this._beforeRenderTargetDrawStage = Stage.Create(); this._beforeRenderingGroupDrawStage = Stage.Create(); this._beforeRenderingMeshStage = Stage.Create(); this._afterRenderingMeshStage = Stage.Create(); this._afterRenderingGroupDrawStage = Stage.Create(); this._afterCameraDrawStage = Stage.Create(); this._afterCameraPostProcessStage = Stage.Create(); this._afterRenderTargetDrawStage = Stage.Create(); this._afterRenderTargetPostProcessStage = Stage.Create(); this._afterRenderStage = Stage.Create(); this._pointerMoveStage = Stage.Create(); this._pointerDownStage = Stage.Create(); this._pointerUpStage = Stage.Create(); this._geometriesByUniqueId = null; this._uniqueId = 0; this._defaultMeshCandidates = { data: [], length: 0 }; this._defaultSubMeshCandidates = { data: [], length: 0 }; this._floatingOriginScene = void 0; this._floatingOriginOffsetDefault = Vector3.Zero(); this._preventFreeActiveMeshesAndRenderingGroups = false; this._activeMeshesFrozen = false; this._activeMeshesFrozenButKeepClipping = false; this._skipEvaluateActiveMeshesCompletely = false; this._freezeActiveMeshesCancel = null; this._useCurrentFrameBuffer = false; this._allowPostProcessClearColor = true; this.getDeterministicFrameTime = () => { return this._engine.getTimeStep(); }; this._getFloatingOriginScene = () => { return this._floatingOriginScene; }; this._registeredActions = 0; this._blockMaterialDirtyMechanism = false; this._perfCollector = null; this.activeCameras = []; this._uniqueId = this.getUniqueId(); const fullOptions = { useGeometryUniqueIdsMap: true, useMaterialMeshMap: true, useClonedMeshMap: true, virtual: false, ...options }; engine = this._engine = engine || EngineStore.LastCreatedEngine; if (fullOptions.virtual) { engine._virtualScenes.push(this); } else { EngineStore._LastCreatedScene = this; engine.scenes.push(this); } if (engine.getCreationOptions().useLargeWorldRendering || options?.useFloatingOrigin) { OverrideMatrixFunctions(); this._floatingOriginScene = this; } this._uid = null; this._renderingManager = new RenderingManager(this); if (PostProcessManager) { this.postProcessManager = new PostProcessManager(this); } if (IsWindowObjectExist()) { this.attachControl(); } this._createUbo(); if (ImageProcessingConfiguration) { this._imageProcessingConfiguration = new ImageProcessingConfiguration(); } this.setDefaultCandidateProviders(); if (fullOptions.useGeometryUniqueIdsMap) { this._geometriesByUniqueId = {}; } this.useMaterialMeshMap = fullOptions.useMaterialMeshMap; this.useClonedMeshMap = fullOptions.useClonedMeshMap; if (!options || !options.virtual) { engine.onNewSceneAddedObservable.notifyObservers(this); } } /** * Gets a string identifying the name of the class * @returns "Scene" string */ getClassName() { return "Scene"; } /** * @internal */ _getDefaultMeshCandidates() { this._defaultMeshCandidates.data = this.meshes; this._defaultMeshCandidates.length = this.meshes.length; return this._defaultMeshCandidates; } /** * @internal */ _getDefaultSubMeshCandidates(mesh) { this._defaultSubMeshCandidates.data = mesh.subMeshes; this._defaultSubMeshCandidates.length = mesh.subMeshes.length; return this._defaultSubMeshCandidates; } /** * Sets the default candidate providers for the scene. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates * and getCollidingSubMeshCandidates to their default function */ setDefaultCandidateProviders() { this.getActiveMeshCandidates = () => this._getDefaultMeshCandidates(); this.getActiveSubMeshCandidates = (mesh) => this._getDefaultSubMeshCandidates(mesh); this.getIntersectingSubMeshCandidates = (mesh, localRay) => this._getDefaultSubMeshCandidates(mesh); this.getCollidingSubMeshCandidates = (mesh, collider) => this._getDefaultSubMeshCandidates(mesh); } /** * Gets the mesh that is currently under the pointer */ get meshUnderPointer() { return this._inputManager.meshUnderPointer; } /** * Gets or sets the current on-screen X position of the pointer */ get pointerX() { return this._inputManager.pointerX; } set pointerX(value) { this._inputManager.pointerX = value; } /** * Gets or sets the current on-screen Y position of the pointer */ get pointerY() { return this._inputManager.pointerY; } set pointerY(value) { this._inputManager.pointerY = value; } /** * Gets the cached material (ie. the latest rendered one) * @returns the cached material */ getCachedMaterial() { return this._cachedMaterial; } /** * Gets the cached effect (ie. the latest rendered one) * @returns the cached effect */ getCachedEffect() { return this._cachedEffect; } /** * Gets the cached visibility state (ie. the latest rendered one) * @returns the cached visibility state */ getCachedVisibility() { return this._cachedVisibility; } /** * Gets a boolean indicating if the current material / effect / visibility must be bind again * @param material defines the current material * @param effect defines the current effect * @param visibility defines the current visibility state * @returns true if one parameter is not cached */ isCachedMaterialInvalid(material, effect, visibility = 1) { return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility; } /** * Gets the engine associated with the scene * @returns an Engine */ getEngine() { return this._engine; } /** * Gets the total number of vertices rendered per frame * @returns the total number of vertices rendered per frame */ getTotalVertices() { return this._totalVertices.current; } /** * Gets the performance counter for total vertices * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation */ get totalVerticesPerfCounter() { return this._totalVertices; } /** * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3) * @returns the total number of active indices rendered per frame */ getActiveIndices() { return this._activeIndices.current; } /** * Gets the performance counter for active indices * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation */ get totalActiveIndicesPerfCounter() { return this._activeIndices; } /** * Gets the total number of active particles rendered per frame * @returns the total number of active particles rendered per frame */ getActiveParticles() { return this._activeParticles.current; } /** * Gets the performance counter for active particles * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation */ get activeParticlesPerfCounter() { return this._activeParticles; } /** * Gets the total number of active bones rendered per frame * @returns the total number of active bones rendered per frame */ getActiveBones() { return this._activeBones.current; } /** * Gets the performance counter for active bones * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#instrumentation */ get activeBonesPerfCounter() { return this._activeBones; } /** * Gets the array of active meshes * @returns an array of AbstractMesh */ getActiveMeshes() { return this._activeMeshes; } /** * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.) * @returns a number */ getAnimationRatio() { return this._animationRatio !== void 0 ? this._animationRatio : 1; } /** * Gets an unique Id for the current render phase * @returns a number */ getRenderId() { return this._renderId; } /** * Gets an unique Id for the current frame * @returns a number */ getFrameId() { return this._frameId; } /** Call this function if you want to manually increment the render Id*/ incrementRenderId() { this._renderId++; } _createUbo() { this.setSceneUniformBuffer(this.createSceneUniformBuffer()); } /** * 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) * @returns the current scene */ simulatePointerMove(pickResult, pointerEventInit) { this._inputManager.simulatePointerMove(pickResult, pointerEventInit); return this; } /** * 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) * @returns the current scene */ simulatePointerDown(pickResult, pointerEventInit) { this._inputManager.simulatePointerDown(pickResult, pointerEventInit); return this; } /** * 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) * @returns the current scene */ simulatePointerUp(pickResult, pointerEventInit, doubleTap) { this._inputManager.simulatePointerUp(pickResult, pointerEventInit, doubleTap); return this; } /** * 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 */ isPointerCaptured(pointerId = 0) { return this._inputManager.isPointerCaptured(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 */ attachControl(attachUp = true, attachDown = true, attachMove = true) { this._inputManager.attachControl(attachUp, attachDown, attachMove); } /** Detaches all event handlers*/ detachControl() { this._inputManager.detachControl(); } /** * This function will check if the scene can be rendered (textures are loaded, shaders are compiled) * Delay loaded resources are not taking in account * @param checkRenderTargets true to also check that the meshes rendered as part of a render target are ready (default: true) * @returns true if all required resources are ready */ isReady(checkRenderTargets = true) { if (this._isDisposed) { return false; } let index; const engine = this.getEngine(); const currentRenderPassId = engine.currentRenderPassId; engine.currentRenderPassId = this.activeCamera?.renderPassId ?? currentRenderPassId; let isReady = true; if (this._pendingData.length > 0) { isReady = false; } this.prePassRenderer?.update(); if (this.useOrderIndependentTransparency && this.depthPeelingRenderer) { isReady && (isReady = this.depthPeelingRenderer.isReady()); } if (checkRenderTargets) { this._processedMaterials.reset(); this._materialsRenderTargets.reset(); } for (index = 0; index < this.meshes.length; index++) { const mesh = this.meshes[index]; if (!mesh.subMeshes || mesh.subMeshes.length === 0) { continue; } if (!mesh.isReady(true)) { isReady = false; continue; } const hardwareInstancedRendering = mesh.hasThinInstances || mesh.getClassName() === "InstancedMesh" || mesh.getClassName() === "InstancedLinesMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0; for (const step of this._isReadyForMeshStage) { if (!step.action(mesh, hardwareInstancedRendering)) { isReady = false; } } if (!checkRenderTargets) { continue; } const mat = mesh.material || this.defaultMaterial; if (mat) { if (mat._storeEffectOnSubMeshes) { for (const subMesh of mesh.subMeshes) { const material = subMesh.getMaterial(); if (material && material.hasRenderTargetTextures && material.getRenderTargetTextures != null) { if (this._processedMaterials.indexOf(material) === -1) { this._processedMaterials.push(material); this._materialsRenderTargets.concatWithNoDuplicate(material.getRenderTargetTextures()); } } } } else { if (mat.hasRenderTargetTextures && mat.getRenderTargetTextures != null) { if (this._processedMaterials.indexOf(mat) === -1) { this._processedMaterials.push(mat); this._materialsRenderTargets.concatWithNoDuplicate(mat.getRenderTargetTextures()); } } } } } if (checkRenderTargets) { for (index = 0; index < this._materialsRenderTargets.length; ++index) { const rtt = this._materialsRenderTargets.data[index]; if (!rtt.isReadyForRendering()) { isReady = false; } } } for (index = 0; index < this.geometries.length; index++) { const geometry = this.geometries[index]; if (geometry.delayLoadState === 2) { isReady = false; } } if (this.activeCameras && this.activeCameras.length > 0) { for (const camera of this.activeCameras) { if (!camera.isReady(true)) { isReady = false; } } } else if (this.activeCamera) { if (!this.activeCamera.isReady(true)) { isReady = false; } } for (const particleSystem of this.particleSystems) { if (!particleSystem.isReady()) { isReady = false; } } if (this.layers) { for (const layer of this.layers) { if (!layer.isReady()) { isReady = false; } } } if (this.effectLayers) { for (const effectLayer of this.effectLayers) { if (!effectLayer.isLayerReady()) { isReady = false; } } } if (!engine.areAllEffectsReady()) { isReady = false; } engine.currentRenderPassId = currentRenderPassId; return isReady; } /** Resets all cached information relative to material (including effect and visibility) */ resetCachedMaterial() { this._cachedMaterial = null; this._cachedEffect = null; this._cachedVisibility = null; } /** * Registers a function to be called before every frame render * @param func defines the function to register */ registerBeforeRender(func) { this.onBeforeRenderObservable.add(func); } /** * Unregisters a function called before every frame render * @param func defines the function to unregister */ unregisterBeforeRender(func) { this.onBeforeRenderObservable.removeCallback(func); } /** * Registers a function to be called after every frame render * @param func defines the function to register */ registerAfterRender(func) { this.onAfterRenderObservable.add(func); } /** * Unregisters a function called after every frame render * @param func defines the function to unregister */ unregisterAfterRender(func) { this.onAfterRenderObservable.removeCallback(func); } _executeOnceBeforeRender(func) { const execFunc = /* @__PURE__ */ __name(() => { func(); setTimeout(() => { this.unregisterBeforeRender(execFunc); }); }, "execFunc"); this.registerBeforeRender(execFunc); } /** * The provided function will run before render once and will be disposed afterwards. * A timeout delay can be provided so that the function will be executed in N ms. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed. * @param func The function to be executed. * @param timeout optional delay in ms */ executeOnceBeforeRender(func, timeout) { if (timeout !== void 0) { setTimeout(() => { this._executeOnceBeforeRender(func); }, timeout); } else { this._executeOnceBeforeRender(func); } } /** * This function can help adding any object to the list of data awaited to be ready in order to check for a complete scene loading. * @param data defines the object to wait for */ addPendingData(data) { this._pendingData.push(data); } /** * Remove a pending data from the loading list which has previously been added with addPendingData. * @param data defines the object to remove from the pending list */ removePendingData(data) { const wasLoading = this.isLoading; const index = this._pendingData.indexOf(data); if (index !== -1) { this._pendingData.splice(index, 1); } if (wasLoading && !this.isLoading) { this.onDataLoadedObservable.notifyObservers(this); } } /** * Returns the number of items waiting to be loaded * @returns the number of items waiting to be loaded */ getWaitingItemsCount() { return this._pendingData.length; } /** * Returns a boolean indicating if the scene is still loading data */ get isLoading() { return this._pendingData.length > 0; } /** * Registers a function to be executed when the scene is ready * @param func - the function to be executed * @param checkRenderTargets true to also check that the meshes rendered as part of a render target are ready (default: false) */ executeWhenReady(func, checkRenderTargets = false) { this.onReadyObservable.addOnce(func); if (this._executeWhenReadyTimeoutId !== null) { return; } this._checkIsReady(checkRenderTargets); } /** * Returns a promise that resolves when the scene is ready * @param checkRenderTargets true to also check that the meshes rendered as part of a render target are ready (default: false) * @returns A promise that resolves when the scene is ready */ async whenReadyAsync(checkRenderTargets = false) { return await new Promise((resolve) => { this.executeWhenReady(() => { resolve(); }, checkRenderTargets); }); } /** * @internal */ _checkIsReady(checkRenderTargets = false) { this._registerTransientComponents(); if (this.isReady(checkRenderTargets)) { this.onReadyObservable.notifyObservers(this); this.onReadyObservable.clear(); this._executeWhenReadyTimeoutId = null; return; } if (this._isDisposed) { this.onReadyObservable.clear(); this._executeWhenReadyTimeoutId = null; return; } this._executeWhenReadyTimeoutId = setTimeout(() => { this.incrementRenderId(); this._checkIsReady(checkRenderTargets); }, 100); } /** * Gets all animatable attached to the scene */ get animatables() { return this._activeAnimatables; } /** * Resets the last animation time frame. * Useful to override when animations start running when loading a scene for the first time. */ resetLastAnimationTimeFrame() { this._animationTimeLast = PrecisionDate.Now; } // Matrix /** * Gets the current view matrix * @returns a Matrix */ getViewMatrix() { return this._viewMatrix; } /** * Gets the current projection matrix * @returns a Matrix */ getProjectionMatrix() { return this._projectionMatrix; } /** * Gets the current transform matrix * @returns a Matrix made of View * Projection */ getTransformMatrix() { return this._transformMatrix; } /** * Sets the current transform matrix * @param viewL defines the View matrix to use * @param projectionL defines the Projection matrix to use * @param viewR defines the right View matrix to use (if provided) * @param projectionR defines the right Projection matrix to use (if provided) */ setTransformMatrix(viewL, projectionL, viewR, projectionR) { if (!viewR && !projectionR && this._multiviewSceneUbo) { this._multiviewSceneUbo.dispose(); this._multiviewSceneUbo = null; } if (this._viewUpdateFlag === viewL.updateFlag && this._projectionUpdateFlag === projectionL.updateFlag) { return; } this._viewUpdateFlag = viewL.updateFlag; this._projectionUpdateFlag = projectionL.updateFlag; this._viewMatrix = viewL; this._projectionMatrix = projectionL; this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix); if (!this._frustumPlanes) { this._frustumPlanes = Frustum.GetPlanes(this._transformMatrix); } else { Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes); } if (this._multiviewSceneUbo && this._multiviewSceneUbo.useUbo) { this._updateMultiviewUbo(viewR, projectionR); } else if (this._sceneUbo.useUbo) { this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix); this._sceneUbo.updateMatrix("view", this._viewMatrix); this._sceneUbo.updateMatrix("projection", this._projectionMatrix); } } /** * Gets the uniform buffer used to store scene data * @returns a UniformBuffer */ getSceneUniformBuffer() { return this._multiviewSceneUbo ? this._multiviewSceneUbo : this._sceneUbo; } /** * Creates a scene UBO * @param name name of the uniform buffer (optional, for debugging purpose only) * @param trackUBOsInFrame define if the UBOs should be tracked in the frame (default: undefined - will use the value from Engine._features.trackUbosInFrame) * @returns a new ubo */ createSceneUniformBuffer(name260, trackUBOsInFrame) { const sceneUbo = new UniformBuffer(this._engine, void 0, false, name260 ?? "scene", void 0, trackUBOsInFrame); sceneUbo.addUniform("viewProjection", 16); sceneUbo.addUniform("view", 16); sceneUbo.addUniform("projection", 16); sceneUbo.addUniform("vEyePosition", 4); return sceneUbo; } /** * Sets the scene ubo * @param ubo the ubo to set for the scene */ setSceneUniformBuffer(ubo) { this._sceneUbo = ubo; this._viewUpdateFlag = -1; this._projectionUpdateFlag = -1; } /** * @experimental * True if floatingOriginMode was passed to engine or this scene creation otions. * This mode avoids floating point imprecision in huge coordinate system by offsetting uniform values before passing to shader, centering camera at origin and displacing rest of scene by camera position */ get floatingOriginMode() { return this._floatingOriginScene !== void 0; } /** * @experimental * When floatingOriginMode is enabled, offset is equal to the active camera position in world space. If no active camera or floatingOriginMode is disabled, offset is 0. */ get floatingOriginOffset() { return this.floatingOriginMode && this.activeCamera ? this.activeCamera.getWorldMatrix().getTranslation() : this._floatingOriginOffsetDefault; } /** * Gets an unique (relatively to the current scene) Id * @returns an unique number for the scene */ getUniqueId() { return UniqueIdGenerator.UniqueId; } /** * Add a mesh to the list of scene's meshes * @param newMesh defines the mesh to add * @param recursive if all child meshes should also be added to the scene */ addMesh(newMesh, recursive = false) { if (this._blockEntityCollection) { return; } this.meshes.push(newMesh); newMesh._resyncLightSources(); if (!newMesh.parent) { newMesh._addToSceneRootNodes(); } Tools.SetImmediate(() => { this.onNewMeshAddedObservable.notifyObservers(newMesh); }); if (recursive) { const children = newMesh.getChildMeshes(); for (const m of children) { this.addMesh(m); } } } /** * Remove a mesh for the list of scene's meshes * @param toRemove defines the mesh to remove * @param recursive if all child meshes should also be removed from the scene * @returns the index where the mesh was in the mesh list */ removeMesh(toRemove, recursive = false) { const index = this.meshes.indexOf(toRemove); if (index !== -1) { this.meshes.splice(index, 1); if (!toRemove.parent) { toRemove._removeFromSceneRootNodes(); } } this._inputManager._invalidateMesh(toRemove); this.onMeshRemovedObservable.notifyObservers(toRemove); if (recursive) { const children = toRemove.getChildMeshes(); for (const m of children) { this.removeMesh(m); } } return index; } /** * Add a transform node to the list of scene's transform nodes * @param newTransformNode defines the transform node to add */ addTransformNode(newTransformNode) { if (this._blockEntityCollection) { return; } if (newTransformNode.getScene() === this && newTransformNode._indexInSceneTransformNodesArray !== -1) { return; } newTransformNode._indexInSceneTransformNodesArray = this.transformNodes.length; this.transformNodes.push(newTransformNode); if (!newTransformNode.parent) { newTransformNode._addToSceneRootNodes(); } this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode); } /** * Remove a transform node for the list of scene's transform nodes * @param toRemove defines the transform node to remove * @returns the index where the transform node was in the transform node list */ removeTransformNode(toRemove) { const index = toRemove._indexInSceneTransformNodesArray; if (index !== -1) { if (index !== this.transformNodes.length - 1) { const lastNode = this.transformNodes[this.transformNodes.length - 1]; this.transformNodes[index] = lastNode; lastNode._indexInSceneTransformNodesArray = index; } toRemove._indexInSceneTransformNodesArray = -1; this.transformNodes.pop(); if (!toRemove.parent) { toRemove._removeFromSceneRootNodes(); } } this.onTransformNodeRemovedObservable.notifyObservers(toRemove); return index; } /** * Remove a skeleton for the list of scene's skeletons * @param toRemove defines the skeleton to remove * @returns the index where the skeleton was in the skeleton list */ removeSkeleton(toRemove) { const index = this.skeletons.indexOf(toRemove); if (index !== -1) { this.skeletons.splice(index, 1); this.onSkeletonRemovedObservable.notifyObservers(toRemove); this._executeActiveContainerCleanup(this._activeSkeletons); } return index; } /** * Remove a morph target for the list of scene's morph targets * @param toRemove defines the morph target to remove * @returns the index where the morph target was in the morph target list */ removeMorphTargetManager(toRemove) { const index = this.morphTargetManagers.indexOf(toRemove); if (index !== -1) { this.morphTargetManagers.splice(index, 1); } return index; } /** * Remove a light for the list of scene's lights * @param toRemove defines the light to remove * @returns the index where the light was in the light list */ removeLight(toRemove) { const index = this.lights.indexOf(toRemove); if (index !== -1) { for (const mesh of this.meshes) { mesh._removeLightSource(toRemove, false); } this.lights.splice(index, 1); this.sortLightsByPriority(); if (!toRemove.parent) { toRemove._removeFromSceneRootNodes(); } } this.onLightRemovedObservable.notifyObservers(toRemove); return index; } /** * Remove a camera for the list of scene's cameras * @param toRemove defines the camera to remove * @returns the index where the camera was in the camera list */ removeCamera(toRemove) { const index = this.cameras.indexOf(toRemove); if (index !== -1) { this.cameras.splice(index, 1); if (!toRemove.parent) { toRemove._removeFromSceneRootNodes(); } } if (this.activeCameras) { const index2 = this.activeCameras.indexOf(toRemove); if (index2 !== -1) { this.activeCameras.splice(index2, 1); } } if (this.activeCamera === toRemove) { if (this.cameras.length > 0) { this.activeCamera = this.cameras[0]; } else { this.activeCamera = null; } } this.onCameraRemovedObservable.notifyObservers(toRemove); return index; } /** * Remove a particle system for the list of scene's particle systems * @param toRemove defines the particle system to remove * @returns the index where the particle system was in the particle system list */ removeParticleSystem(toRemove) { const index = this.particleSystems.indexOf(toRemove); if (index !== -1) { this.particleSystems.splice(index, 1); this._executeActiveContainerCleanup(this._activeParticleSystems); } this.onParticleSystemRemovedObservable.notifyObservers(toRemove); return index; } /** * Remove a animation for the list of scene's animations * @param toRemove defines the animation to remove * @returns the index where the animation was in the animation list */ removeAnimation(toRemove) { const index = this.animations.indexOf(toRemove); if (index !== -1) { this.animations.splice(index, 1); } return index; } /** * 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) */ stopAnimation(target, animationName, targetMask) { } /** * Removes the given animation group from this scene. * @param toRemove The animation group to remove * @returns The index of the removed animation group */ removeAnimationGroup(toRemove) { const index = this.animationGroups.indexOf(toRemove); if (index !== -1) { this.animationGroups.splice(index, 1); } this.onAnimationGroupRemovedObservable.notifyObservers(toRemove); return index; } /** * Removes the given multi-material from this scene. * @param toRemove The multi-material to remove * @returns The index of the removed multi-material */ removeMultiMaterial(toRemove) { const index = this.multiMaterials.indexOf(toRemove); if (index !== -1) { this.multiMaterials.splice(index, 1); } this.onMultiMaterialRemovedObservable.notifyObservers(toRemove); return index; } /** * Removes the given material from this scene. * @param toRemove The material to remove * @returns The index of the removed material */ removeMaterial(toRemove) { const index = toRemove._indexInSceneMaterialArray; if (index !== -1 && index < this.materials.length) { if (index !== this.materials.length - 1) { const lastMaterial = this.materials[this.materials.length - 1]; this.materials[index] = lastMaterial; lastMaterial._indexInSceneMaterialArray = index; } toRemove._indexInSceneMaterialArray = -1; this.materials.pop(); } this.onMaterialRemovedObservable.notifyObservers(toRemove); return index; } /** * Removes the given action manager from this scene. * @deprecated * @param toRemove The action manager to remove * @returns The index of the removed action manager */ removeActionManager(toRemove) { const index = this.actionManagers.indexOf(toRemove); if (index !== -1) { this.actionManagers.splice(index, 1); } return index; } /** * Removes the given texture from this scene. * @param toRemove The texture to remove * @returns The index of the removed texture */ removeTexture(toRemove) { const index = this.textures.indexOf(toRemove); if (index !== -1) { this.textures.splice(index, 1); } this.onTextureRemovedObservable.notifyObservers(toRemove); return index; } /** * Removes the given frame graph from this scene. * @param toRemove The frame graph to remove * @returns The index of the removed frame graph */ removeFrameGraph(toRemove) { const index = this.frameGraphs.indexOf(toRemove); if (index !== -1) { this.frameGraphs.splice(index, 1); } this.onFrameGraphRemovedObservable.notifyObservers(toRemove); return index; } /** * Removes the given object renderer from this scene. * @param toRemove The object renderer to remove * @returns The index of the removed object renderer */ removeObjectRenderer(toRemove) { const index = this.objectRenderers.indexOf(toRemove); if (index !== -1) { this.objectRenderers.splice(index, 1); } this.onObjectRendererRemovedObservable.notifyObservers(toRemove); return index; } /** * Removes the given post-process from this scene. * @param toRemove The post-process to remove * @returns The index of the removed post-process */ removePostProcess(toRemove) { const index = this.postProcesses.indexOf(toRemove); if (index !== -1) { this.postProcesses.splice(index, 1); } this.onPostProcessRemovedObservable.notifyObservers(toRemove); return index; } /** * Removes the given layer from this scene. * @param toRemove The layer to remove * @returns The index of the removed layer */ removeEffectLayer(toRemove) { const index = this.effectLayers.indexOf(toRemove); if (index !== -1) { this.effectLayers.splice(index, 1); } this.onEffectLayerRemovedObservable.notifyObservers(toRemove); return index; } /** * Adds the given light to this scene * @param newLight The light to add */ addLight(newLight) { if (this._blockEntityCollection) { return; } this.lights.push(newLight); this.sortLightsByPriority(); if (!newLight.parent) { newLight._addToSceneRootNodes(); } for (const mesh of this.meshes) { if (mesh.lightSources.indexOf(newLight) === -1) { mesh.lightSources.push(newLight); mesh._resyncLightSources(); } } Tools.SetImmediate(() => { this.onNewLightAddedObservable.notifyObservers(newLight); }); } /** * Sorts the list list based on light priorities */ sortLightsByPriority() { if (this.requireLightSorting) { this.lights.sort(LightConstants.CompareLightsPriority); } } /** * Adds the given camera to this scene * @param newCamera The camera to add */ addCamera(newCamera) { if (this._blockEntityCollection) { return; } this.cameras.push(newCamera); Tools.SetImmediate(() => { this.onNewCameraAddedObservable.notifyObservers(newCamera); }); if (!newCamera.parent) { newCamera._addToSceneRootNodes(); } } /** * Adds the given skeleton to this scene * @param newSkeleton The skeleton to add */ addSkeleton(newSkeleton) { if (this._blockEntityCollection) { return; } this.skeletons.push(newSkeleton); Tools.SetImmediate(() => { this.onNewSkeletonAddedObservable.notifyObservers(newSkeleton); }); } /** * Adds the given particle system to this scene * @param newParticleSystem The particle system to add */ addParticleSystem(newParticleSystem) { if (this._blockEntityCollection) { return; } this.particleSystems.push(newParticleSystem); Tools.SetImmediate(() => { this.onNewParticleSystemAddedObservable.notifyObservers(newParticleSystem); }); } /** * Adds the given animation to this scene * @param newAnimation The animation to add */ addAnimation(newAnimation) { if (this._blockEntityCollection) { return; } this.animations.push(newAnimation); } /** * Adds the given animation group to this scene. * @param newAnimationGroup The animation group to add */ addAnimationGroup(newAnimationGroup) { if (this._blockEntityCollection) { return; } this.animationGroups.push(newAnimationGroup); Tools.SetImmediate(() => { this.onNewAnimationGroupAddedObservable.notifyObservers(newAnimationGroup); }); } /** * Adds the given multi-material to this scene * @param newMultiMaterial The multi-material to add */ addMultiMaterial(newMultiMaterial) { if (this._blockEntityCollection) { return; } this.multiMaterials.push(newMultiMaterial); Tools.SetImmediate(() => { this.onNewMultiMaterialAddedObservable.notifyObservers(newMultiMaterial); }); } /** * Adds the given material to this scene * @param newMaterial The material to add */ addMaterial(newMaterial) { if (this._blockEntityCollection) { return; } if (newMaterial.getScene() === this && newMaterial._indexInSceneMaterialArray !== -1) { return; } newMaterial._indexInSceneMaterialArray = this.materials.length; this.materials.push(newMaterial); Tools.SetImmediate(() => { this.onNewMaterialAddedObservable.notifyObservers(newMaterial); }); } /** * Adds the given morph target to this scene * @param newMorphTargetManager The morph target to add */ addMorphTargetManager(newMorphTargetManager) { if (this._blockEntityCollection) { return; } this.morphTargetManagers.push(newMorphTargetManager); } /** * Adds the given geometry to this scene * @param newGeometry The geometry to add */ addGeometry(newGeometry) { if (this._blockEntityCollection) { return; } if (this._geometriesByUniqueId) { this._geometriesByUniqueId[newGeometry.uniqueId] = this.geometries.length; } this.geometries.push(newGeometry); } /** * Adds the given action manager to this scene * @deprecated * @param newActionManager The action manager to add */ addActionManager(newActionManager) { this.actionManagers.push(newActionManager); } /** * Adds the given texture to this scene. * @param newTexture The texture to add */ addTexture(newTexture) { if (this._blockEntityCollection) { return; } this.textures.push(newTexture); this.onNewTextureAddedObservable.notifyObservers(newTexture); } /** * Adds the given frame graph to this scene. * @param newFrameGraph The frame graph to add */ addFrameGraph(newFrameGraph) { this.frameGraphs.push(newFrameGraph); Tools.SetImmediate(() => { this.onNewFrameGraphAddedObservable.notifyObservers(newFrameGraph); }); } /** * Adds the given object renderer to this scene. * @param objectRenderer The object renderer to add */ addObjectRenderer(objectRenderer) { this.objectRenderers.push(objectRenderer); Tools.SetImmediate(() => { this.onNewObjectRendererAddedObservable.notifyObservers(objectRenderer); }); } /** * Adds the given post process to this scene. * @param newPostProcess The post process to add */ addPostProcess(newPostProcess) { if (this._blockEntityCollection) { return; } this.postProcesses.push(newPostProcess); Tools.SetImmediate(() => { this.onNewPostProcessAddedObservable.notifyObservers(newPostProcess); }); } /** * Adds the given effect layer to this scene. * @param newEffectLayer The effect layer to add */ addEffectLayer(newEffectLayer) { if (this._blockEntityCollection) { return; } this.effectLayers.push(newEffectLayer); Tools.SetImmediate(() => { this.onNewEffectLayerAddedObservable.notifyObservers(newEffectLayer); }); } /** * Switch active camera * @param newCamera defines the new active camera * @param attachControl defines if attachControl must be called for the new active camera (default: true) */ switchActiveCamera(newCamera, attachControl = true) { const canvas = this._engine.getInputElement(); if (!canvas) { return; } if (this.activeCamera) { this.activeCamera.detachControl(); } this.activeCamera = newCamera; if (attachControl) { newCamera.attachControl(); } } /** * sets the active camera of the scene using its Id * @param id defines the camera's Id * @returns the new active camera or null if none found. */ setActiveCameraById(id) { const camera = this.getCameraById(id); if (camera) { this.activeCamera = camera; return camera; } return null; } /** * sets the active camera of the scene using its name * @param name defines the camera's name * @returns the new active camera or null if none found. */ setActiveCameraByName(name260) { const camera = this.getCameraByName(name260); if (camera) { this.activeCamera = camera; return camera; } return null; } /** * get an animation group using its name * @param name defines the material's name * @returns the animation group or null if none found. */ getAnimationGroupByName(name260) { for (let index = 0; index < this.animationGroups.length; index++) { if (this.animationGroups[index].name === name260) { return this.animationGroups[index]; } } return null; } _getMaterial(allowMultiMaterials, predicate) { for (let index = 0; index < this.materials.length; index++) { const material = this.materials[index]; if (predicate(material)) { return material; } } if (allowMultiMaterials) { for (let index = 0; index < this.multiMaterials.length; index++) { const material = this.multiMaterials[index]; if (predicate(material)) { return material; } } } return null; } /** * Get a material using its unique id * @param uniqueId defines the material's unique id * @param allowMultiMaterials determines whether multimaterials should be considered * @returns the material or null if none found. * @deprecated Please use getMaterialByUniqueId instead. */ // eslint-disable-next-line @typescript-eslint/naming-convention getMaterialByUniqueID(uniqueId, allowMultiMaterials = false) { return this.getMaterialByUniqueId(uniqueId, allowMultiMaterials); } /** * Get a material using its unique id * @param uniqueId defines the material's unique id * @param allowMultiMaterials determines whether multimaterials should be considered * @returns the material or null if none found. */ getMaterialByUniqueId(uniqueId, allowMultiMaterials = false) { return this._getMaterial(allowMultiMaterials, (m) => m.uniqueId === uniqueId); } /** * get a material using its id * @param id defines the material's Id * @param allowMultiMaterials determines whether multimaterials should be considered * @returns the material or null if none found. */ getMaterialById(id, allowMultiMaterials = false) { return this._getMaterial(allowMultiMaterials, (m) => m.id === id); } /** * Gets a material using its name * @param name defines the material's name * @param allowMultiMaterials determines whether multimaterials should be considered * @returns the material or null if none found. */ getMaterialByName(name260, allowMultiMaterials = false) { return this._getMaterial(allowMultiMaterials, (m) => m.name === name260); } /** * Gets a last added material using a given id * @param id defines the material's id * @param allowMultiMaterials determines whether multimaterials should be considered * @returns the last material with the given id or null if none found. */ getLastMaterialById(id, allowMultiMaterials = false) { for (let index = this.materials.length - 1; index >= 0; index--) { if (this.materials[index].id === id) { return this.materials[index]; } } if (allowMultiMaterials) { for (let index = this.multiMaterials.length - 1; index >= 0; index--) { if (this.multiMaterials[index].id === id) { return this.multiMaterials[index]; } } } return null; } /** * Get a texture using its unique id * @param uniqueId defines the texture's unique id * @returns the texture or null if none found. */ getTextureByUniqueId(uniqueId) { for (let index = 0; index < this.textures.length; index++) { if (this.textures[index].uniqueId === uniqueId) { return this.textures[index]; } } return null; } /** * Gets a texture using its name * @param name defines the texture's name * @returns the texture or null if none found. */ getTextureByName(name260) { for (let index = 0; index < this.textures.length; index++) { if (this.textures[index].name === name260) { return this.textures[index]; } } return null; } /** * Gets a camera using its Id * @param id defines the Id to look for * @returns the camera or null if not found */ getCameraById(id) { for (let index = 0; index < this.cameras.length; index++) { if (this.cameras[index].id === id) { return this.cameras[index]; } } return null; } /** * Gets a camera using its unique Id * @param uniqueId defines the unique Id to look for * @returns the camera or null if not found */ getCameraByUniqueId(uniqueId) { for (let index = 0; index < this.cameras.length; index++) { if (this.cameras[index].uniqueId === uniqueId) { return this.cameras[index]; } } return null; } /** * Gets a camera using its name * @param name defines the camera's name * @returns the camera or null if none found. */ getCameraByName(name260) { for (let index = 0; index < this.cameras.length; index++) { if (this.cameras[index].name === name260) { return this.cameras[index]; } } return null; } /** * Gets a bone using its Id * @param id defines the bone's Id * @returns the bone or null if not found */ getBoneById(id) { for (let skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) { const skeleton = this.skeletons[skeletonIndex]; for (let boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) { if (skeleton.bones[boneIndex].id === id) { return skeleton.bones[boneIndex]; } } } return null; } /** * Gets a bone using its id * @param name defines the bone's name * @returns the bone or null if not found */ getBoneByName(name260) { for (let skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) { const skeleton = this.skeletons[skeletonIndex]; for (let boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) { if (skeleton.bones[boneIndex].name === name260) { return skeleton.bones[boneIndex]; } } } return null; } /** * Gets a light node using its name * @param name defines the light's name * @returns the light or null if none found. */ getLightByName(name260) { for (let index = 0; index < this.lights.length; index++) { if (this.lights[index].name === name260) { return this.lights[index]; } } return null; } /** * Gets a light node using its Id * @param id defines the light's Id * @returns the light or null if none found. */ getLightById(id) { for (let index = 0; index < this.lights.length; index++) { if (this.lights[index].id === id) { return this.lights[index]; } } return null; } /** * Gets a light node using its scene-generated unique Id * @param uniqueId defines the light's unique Id * @returns the light or null if none found. */ getLightByUniqueId(uniqueId) { for (let index = 0; index < this.lights.length; index++) { if (this.lights[index].uniqueId === uniqueId) { return this.lights[index]; } } return null; } /** * Gets a particle system by Id * @param id defines the particle system Id * @returns the corresponding system or null if none found */ getParticleSystemById(id) { for (let index = 0; index < this.particleSystems.length; index++) { if (this.particleSystems[index].id === id) { return this.particleSystems[index]; } } return null; } /** * Gets a geometry using its Id * @param id defines the geometry's Id * @returns the geometry or null if none found. */ getGeometryById(id) { for (let index = 0; index < this.geometries.length; index++) { if (this.geometries[index].id === id) { return this.geometries[index]; } } return null; } _getGeometryByUniqueId(uniqueId) { if (this._geometriesByUniqueId) { const index = this._geometriesByUniqueId[uniqueId]; if (index !== void 0) { return this.geometries[index]; } } else { for (let index = 0; index < this.geometries.length; index++) { if (this.geometries[index].uniqueId === uniqueId) { return this.geometries[index]; } } } return null; } /** * Gets a frame graph using its name * @param name defines the frame graph's name * @returns the frame graph or null if none found. */ getFrameGraphByName(name260) { for (let index = 0; index < this.frameGraphs.length; index++) { if (this.frameGraphs[index].name === name260) { return this.frameGraphs[index]; } } return null; } /** * Add a new geometry to this scene * @param geometry defines the geometry to be added to the scene. * @param force defines if the geometry must be pushed even if a geometry with this id already exists * @returns a boolean defining if the geometry was added or not */ pushGeometry(geometry, force) { if (!force && this._getGeometryByUniqueId(geometry.uniqueId)) { return false; } this.addGeometry(geometry); Tools.SetImmediate(() => { this.onNewGeometryAddedObservable.notifyObservers(geometry); }); return true; } /** * Removes an existing geometry * @param geometry defines the geometry to be removed from the scene * @returns a boolean defining if the geometry was removed or not */ removeGeometry(geometry) { let index; if (this._geometriesByUniqueId) { index = this._geometriesByUniqueId[geometry.uniqueId]; if (index === void 0) { return false; } } else { index = this.geometries.indexOf(geometry); if (index < 0) { return false; } } if (index !== this.geometries.length - 1) { const lastGeometry = this.geometries[this.geometries.length - 1]; if (lastGeometry) { this.geometries[index] = lastGeometry; if (this._geometriesByUniqueId) { this._geometriesByUniqueId[lastGeometry.uniqueId] = index; } } } if (this._geometriesByUniqueId) { this._geometriesByUniqueId[geometry.uniqueId] = void 0; } this.geometries.pop(); this.onGeometryRemovedObservable.notifyObservers(geometry); return true; } /** * Gets the list of geometries attached to the scene * @returns an array of Geometry */ getGeometries() { return this.geometries; } /** * Gets the first added mesh found of a given Id * @param id defines the Id to search for * @returns the mesh found or null if not found at all */ getMeshById(id) { for (let index = 0; index < this.meshes.length; index++) { if (this.meshes[index].id === id) { return this.meshes[index]; } } return null; } /** * Gets a list of meshes using their Id * @param id defines the Id to search for * @returns a list of meshes */ getMeshesById(id) { return this.meshes.filter(function(m) { return m.id === id; }); } /** * Gets the first added transform node found of a given Id * @param id defines the Id to search for * @returns the found transform node or null if not found at all. */ getTransformNodeById(id) { for (let index = 0; index < this.transformNodes.length; index++) { if (this.transformNodes[index].id === id) { return this.transformNodes[index]; } } return null; } /** * Gets a transform node with its auto-generated unique Id * @param uniqueId defines the unique Id to search for * @returns the found transform node or null if not found at all. */ getTransformNodeByUniqueId(uniqueId) { for (let index = 0; index < this.transformNodes.length; index++) { if (this.transformNodes[index].uniqueId === uniqueId) { return this.transformNodes[index]; } } return null; } /** * Gets a list of transform nodes using their Id * @param id defines the Id to search for * @returns a list of transform nodes */ getTransformNodesById(id) { return this.transformNodes.filter(function(m) { return m.id === id; }); } /** * Gets a mesh with its auto-generated unique Id * @param uniqueId defines the unique Id to search for * @returns the found mesh or null if not found at all. */ getMeshByUniqueId(uniqueId) { for (let index = 0; index < this.meshes.length; index++) { if (this.meshes[index].uniqueId === uniqueId) { return this.meshes[index]; } } return null; } /** * Gets a the last added mesh using a given Id * @param id defines the Id to search for * @returns the found mesh or null if not found at all. */ getLastMeshById(id) { for (let index = this.meshes.length - 1; index >= 0; index--) { if (this.meshes[index].id === id) { return this.meshes[index]; } } return null; } /** * Gets a the last transform node using a given Id * @param id defines the Id to search for * @returns the found mesh or null if not found at all. */ getLastTransformNodeById(id) { for (let index = this.transformNodes.length - 1; index >= 0; index--) { if (this.transformNodes[index].id === id) { return this.transformNodes[index]; } } return null; } /** * Gets a the last added node (Mesh, Camera, Light) using a given Id * @param id defines the Id to search for * @returns the found node or null if not found at all */ getLastEntryById(id) { let index; for (index = this.meshes.length - 1; index >= 0; index--) { if (this.meshes[index].id === id) { return this.meshes[index]; } } for (index = this.transformNodes.length - 1; index >= 0; index--) { if (this.transformNodes[index].id === id) { return this.transformNodes[index]; } } for (index = this.cameras.length - 1; index >= 0; index--) { if (this.cameras[index].id === id) { return this.cameras[index]; } } for (index = this.lights.length - 1; index >= 0; index--) { if (this.lights[index].id === id) { return this.lights[index]; } } return null; } /** * Gets a node (Mesh, Camera, Light) using a given Id * @param id defines the Id to search for * @returns the found node or null if not found at all */ getNodeById(id) { const mesh = this.getMeshById(id); if (mesh) { return mesh; } const transformNode = this.getTransformNodeById(id); if (transformNode) { return transformNode; } const light = this.getLightById(id); if (light) { return light; } const camera = this.getCameraById(id); if (camera) { return camera; } const bone = this.getBoneById(id); if (bone) { return bone; } return null; } /** * Gets a node (Mesh, Camera, Light) using a given name * @param name defines the name to search for * @returns the found node or null if not found at all. */ getNodeByName(name260) { const mesh = this.getMeshByName(name260); if (mesh) { return mesh; } const transformNode = this.getTransformNodeByName(name260); if (transformNode) { return transformNode; } const light = this.getLightByName(name260); if (light) { return light; } const camera = this.getCameraByName(name260); if (camera) { return camera; } const bone = this.getBoneByName(name260); if (bone) { return bone; } return null; } /** * Gets a mesh using a given name * @param name defines the name to search for * @returns the found mesh or null if not found at all. */ getMeshByName(name260) { for (let index = 0; index < this.meshes.length; index++) { if (this.meshes[index].name === name260) { return this.meshes[index]; } } return null; } /** * Gets a transform node using a given name * @param name defines the name to search for * @returns the found transform node or null if not found at all. */ getTransformNodeByName(name260) { for (let index = 0; index < this.transformNodes.length; index++) { if (this.transformNodes[index].name === name260) { return this.transformNodes[index]; } } return null; } /** * Gets a skeleton using a given Id (if many are found, this function will pick the last one) * @param id defines the Id to search for * @returns the found skeleton or null if not found at all. */ getLastSkeletonById(id) { for (let index = this.skeletons.length - 1; index >= 0; index--) { if (this.skeletons[index].id === id) { return this.skeletons[index]; } } return null; } /** * Gets a skeleton using a given auto generated unique id * @param uniqueId defines the unique id to search for * @returns the found skeleton or null if not found at all. */ getSkeletonByUniqueId(uniqueId) { for (let index = 0; index < this.skeletons.length; index++) { if (this.skeletons[index].uniqueId === uniqueId) { return this.skeletons[index]; } } return null; } /** * Gets a skeleton using a given id (if many are found, this function will pick the first one) * @param id defines the id to search for * @returns the found skeleton or null if not found at all. */ getSkeletonById(id) { for (let index = 0; index < this.skeletons.length; index++) { if (this.skeletons[index].id === id) { return this.skeletons[index]; } } return null; } /** * Gets a skeleton using a given name * @param name defines the name to search for * @returns the found skeleton or null if not found at all. */ getSkeletonByName(name260) { for (let index = 0; index < this.skeletons.length; index++) { if (this.skeletons[index].name === name260) { return this.skeletons[index]; } } return null; } /** * Gets a morph target manager using a given id (if many are found, this function will pick the last one) * @param id defines the id to search for * @returns the found morph target manager or null if not found at all. */ getMorphTargetManagerById(id) { for (let index = 0; index < this.morphTargetManagers.length; index++) { if (this.morphTargetManagers[index].uniqueId === id) { return this.morphTargetManagers[index]; } } return null; } /** * Gets a morph target using a given id (if many are found, this function will pick the first one) * @param id defines the id to search for * @returns the found morph target or null if not found at all. */ getMorphTargetById(id) { for (let managerIndex = 0; managerIndex < this.morphTargetManagers.length; ++managerIndex) { const morphTargetManager = this.morphTargetManagers[managerIndex]; for (let index = 0; index < morphTargetManager.numTargets; ++index) { const target = morphTargetManager.getTarget(index); if (target.id === id) { return target; } } } return null; } /** * Gets a morph target using a given name (if many are found, this function will pick the first one) * @param name defines the name to search for * @returns the found morph target or null if not found at all. */ getMorphTargetByName(name260) { for (let managerIndex = 0; managerIndex < this.morphTargetManagers.length; ++managerIndex) { const morphTargetManager = this.morphTargetManagers[managerIndex]; for (let index = 0; index < morphTargetManager.numTargets; ++index) { const target = morphTargetManager.getTarget(index); if (target.name === name260) { return target; } } } return null; } /** * Gets a post process using a given name (if many are found, this function will pick the first one) * @param name defines the name to search for * @returns the found post process or null if not found at all. */ getPostProcessByName(name260) { for (let postProcessIndex = 0; postProcessIndex < this.postProcesses.length; ++postProcessIndex) { const postProcess = this.postProcesses[postProcessIndex]; if (postProcess.name === name260) { return postProcess; } } return null; } /** * Gets a boolean indicating if the given mesh is active * @param mesh defines the mesh to look for * @returns true if the mesh is in the active list */ isActiveMesh(mesh) { return this._activeMeshes.indexOf(mesh) !== -1; } /** * Return a unique id as a string which can serve as an identifier for the scene */ get uid() { if (!this._uid) { this._uid = Tools.RandomId(); } return this._uid; } /** * Add an externally attached data from its key. * This method call will fail and return false, if such key already exists. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method. * @param key the unique key that identifies the data * @param data the data object to associate to the key for this Engine instance * @returns true if no such key were already present and the data was added successfully, false otherwise */ addExternalData(key, data) { if (!this._externalData) { this._externalData = new StringDictionary(); } return this._externalData.add(key, data); } /** * Get an externally attached data from its key * @param key the unique key that identifies the data * @returns the associated data, if present (can be null), or undefined if not present */ getExternalData(key) { if (!this._externalData) { return null; } return this._externalData.get(key); } /** * Get an externally attached data from its key, create it using a factory if it's not already present * @param key the unique key that identifies the data * @param factory the factory that will be called to create the instance if and only if it doesn't exists * @returns the associated data, can be null if the factory returned null. */ getOrAddExternalDataWithFactory(key, factory) { if (!this._externalData) { this._externalData = new StringDictionary(); } return this._externalData.getOrAddWithFactory(key, factory); } /** * Remove an externally attached data from the Engine instance * @param key the unique key that identifies the data * @returns true if the data was successfully removed, false if it doesn't exist */ removeExternalData(key) { return this._externalData.remove(key); } _evaluateSubMesh(subMesh, mesh, initialMesh, forcePush) { if (forcePush || subMesh.isInFrustum(this._frustumPlanes)) { for (const step of this._evaluateSubMeshStage) { step.action(mesh, subMesh); } const material = subMesh.getMaterial(); if (material !== null && material !== void 0) { if (material.hasRenderTargetTextures && material.getRenderTargetTextures != null) { if (this._processedMaterials.indexOf(material) === -1) { this._processedMaterials.push(material); this._materialsRenderTargets.concatWithNoDuplicate(material.getRenderTargetTextures()); } } this._renderingManager.dispatch(subMesh, mesh, material); } } } /** * Clear the processed materials smart array preventing retention point in material dispose. */ freeProcessedMaterials() { this._processedMaterials.dispose(); } /** Gets or sets a boolean blocking all the calls to freeActiveMeshes and freeRenderingGroups * It can be used in order to prevent going through methods freeRenderingGroups and freeActiveMeshes several times to improve performance * when disposing several meshes in a row or a hierarchy of meshes. * When used, it is the responsibility of the user to blockfreeActiveMeshesAndRenderingGroups back to false. */ get blockfreeActiveMeshesAndRenderingGroups() { return this._preventFreeActiveMeshesAndRenderingGroups; } set blockfreeActiveMeshesAndRenderingGroups(value) { if (this._preventFreeActiveMeshesAndRenderingGroups === value) { return; } if (value) { this.freeActiveMeshes(); this.freeRenderingGroups(); } this._preventFreeActiveMeshesAndRenderingGroups = value; } /** * Clear the active meshes smart array preventing retention point in mesh dispose. */ freeActiveMeshes() { if (this.blockfreeActiveMeshesAndRenderingGroups) { return; } this._activeMeshes.dispose(); if (this.activeCamera && this.activeCamera._activeMeshes) { this.activeCamera._activeMeshes.dispose(); } if (this.activeCameras) { for (let i = 0; i < this.activeCameras.length; i++) { const activeCamera = this.activeCameras[i]; if (activeCamera && activeCamera._activeMeshes) { activeCamera._activeMeshes.dispose(); } } } } /** * Clear the info related to rendering groups preventing retention points during dispose. */ freeRenderingGroups() { if (this.blockfreeActiveMeshesAndRenderingGroups) { return; } if (this._renderingManager) { this._renderingManager.freeRenderingGroups(); } if (this.textures) { for (let i = 0; i < this.textures.length; i++) { const texture = this.textures[i]; if (texture && texture.renderList) { texture.freeRenderingGroups(); } } } } /** @internal */ _isInIntermediateRendering() { return this._intermediateRendering; } /** * Use this function to stop evaluating active meshes. The current list will be keep alive between frames * @param skipEvaluateActiveMeshes defines an optional boolean indicating that the evaluate active meshes step must be completely skipped * @param onSuccess optional success callback * @param onError optional error callback * @param freezeMeshes defines if meshes should be frozen (true by default) * @param keepFrustumCulling defines if you want to keep running the frustum clipping (false by default) * @returns the current scene */ freezeActiveMeshes(skipEvaluateActiveMeshes = false, onSuccess, onError, freezeMeshes = true, keepFrustumCulling = false) { if (this.frameGraph) { this._renderWithFrameGraph(true, false, true); const objectRendererTasks = this.frameGraph.getTasksByType(FrameGraphObjectRendererTask); for (const task of objectRendererTasks) { task.objectRenderer._freezeActiveMeshes(freezeMeshes); } this._freezeActiveMeshesCancel = _RetryWithInterval(() => { let ok = true; let notCancelled = true; for (const task of objectRendererTasks) { ok && (ok = task.objectRenderer._isFrozen); notCancelled && (notCancelled = task.objectRenderer._freezeActiveMeshesCancel !== null); } if (ok) { return true; } else if (!notCancelled) { throw new Error("Freezing active meshes was cancelled"); } return false; }, () => { this._freezeActiveMeshesCancel = null; this._activeMeshesFrozen = true; this._activeMeshesFrozenButKeepClipping = keepFrustumCulling; this._skipEvaluateActiveMeshesCompletely = skipEvaluateActiveMeshes; onSuccess?.(); }, (err, isTimeout) => { this._freezeActiveMeshesCancel = null; this.unfreezeActiveMeshes(); if (!isTimeout) { const errMsg = "Scene: An unexpected error occurred while trying to freeze active meshes."; if (onError) { onError(errMsg); } else { Logger.Error(errMsg); if (err) { Logger.Error(err); if (err.stack) { Logger.Error(err.stack); } } } } else { const errMsg = "Scene: Timeout while waiting for meshes to be frozen."; if (onError) { onError(errMsg); } else { Logger.Error(errMsg); if (err) { Logger.Error(err); } } } }); return this; } this.executeWhenReady(() => { if (!this.activeCamera) { if (onError) { onError("No active camera found"); } return; } if (!this._frustumPlanes) { this.updateTransformMatrix(); } this._evaluateActiveMeshes(); this._activeMeshesFrozen = true; this._activeMeshesFrozenButKeepClipping = keepFrustumCulling; this._skipEvaluateActiveMeshesCompletely = skipEvaluateActiveMeshes; if (freezeMeshes) { for (let index = 0; index < this._activeMeshes.length; index++) { this._activeMeshes.data[index]._freeze(); } } if (onSuccess) { onSuccess(); } }); return this; } /** * Use this function to restart evaluating active meshes on every frame * @returns the current scene */ unfreezeActiveMeshes() { for (let index = 0; index < this.meshes.length; index++) { const mesh = this.meshes[index]; if (mesh._internalAbstractMeshDataInfo) { mesh._internalAbstractMeshDataInfo._isActive = false; } } this._freezeActiveMeshesCancel?.(); this._freezeActiveMeshesCancel = null; if (this.frameGraph) { const objectRendererTasks = this.frameGraph.getTasksByType(FrameGraphObjectRendererTask); for (const task of objectRendererTasks) { task.objectRenderer._unfreezeActiveMeshes(); } } else { for (let index = 0; index < this._activeMeshes.length; index++) { this._activeMeshes.data[index]._unFreeze(); } } this._activeMeshesFrozen = false; return this; } _executeActiveContainerCleanup(container) { const isInFastMode = this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1; if (!isInFastMode && this._activeMeshesFrozen && this._activeMeshes.length) { return; } this.onBeforeRenderObservable.addOnce(() => container.dispose()); } _evaluateActiveMeshes() { if (this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1) { if (this._activeMeshes.length > 0) { this.activeCamera?._activeMeshes.reset(); this._activeMeshes.reset(); this._renderingManager.reset(); this._processedMaterials.reset(); this._activeParticleSystems.reset(); this._activeSkeletons.reset(); this._softwareSkinnedMeshes.reset(); } return; } if (this._activeMeshesFrozen && this._activeMeshes.length) { if (!this._skipEvaluateActiveMeshesCompletely) { const len2 = this._activeMeshes.length; for (let i = 0; i < len2; i++) { const mesh = this._activeMeshes.data[i]; mesh.computeWorldMatrix(); } } if (this._activeParticleSystems) { const psLength = this._activeParticleSystems.length; for (let i = 0; i < psLength; i++) { this._activeParticleSystems.data[i].animate(); } } this._renderingManager.resetSprites(); return; } if (!this.activeCamera) { return; } this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this); this.activeCamera._activeMeshes.reset(); this._activeMeshes.reset(); this._renderingManager.reset(); this._processedMaterials.reset(); this._activeParticleSystems.reset(); this._activeSkeletons.reset(); this._softwareSkinnedMeshes.reset(); this._materialsRenderTargets.reset(); for (const step of this._beforeEvaluateActiveMeshStage) { step.action(); } const meshes = this.getActiveMeshCandidates(); const len = meshes.length; for (let i = 0; i < len; i++) { const mesh = meshes.data[i]; let currentLOD = mesh._internalAbstractMeshDataInfo._currentLOD.get(this.activeCamera); if (currentLOD) { currentLOD[1] = -1; } else { currentLOD = [mesh, -1]; mesh._internalAbstractMeshDataInfo._currentLOD.set(this.activeCamera, currentLOD); } if (mesh.isBlocked) { continue; } this._totalVertices.addCount(mesh.getTotalVertices(), false); if (!mesh.isReady() || !mesh.isEnabled() || mesh.scaling.hasAZeroComponent) { continue; } mesh.computeWorldMatrix(); if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(12, 13)) { this._meshesForIntersections.pushNoDuplicate(mesh); } let meshToRender = this.customLODSelector ? this.customLODSelector(mesh, this.activeCamera) : mesh.getLOD(this.activeCamera); currentLOD[0] = meshToRender; currentLOD[1] = this._frameId; if (meshToRender === void 0 || meshToRender === null) { continue; } if (meshToRender !== mesh && meshToRender.billboardMode !== 0) { meshToRender.computeWorldMatrix(); } mesh._preActivate(); if (mesh.isVisible && mesh.visibility > 0 && (mesh.layerMask & this.activeCamera.layerMask) !== 0 && (this._skipFrustumClipping || mesh.alwaysSelectAsActiveMesh || mesh.isInFrustum(this._frustumPlanes))) { this._activeMeshes.push(mesh); this.activeCamera._activeMeshes.push(mesh); if (meshToRender !== mesh) { meshToRender._activate(this._renderId, false); } for (const step of this._preActiveMeshStage) { step.action(mesh); } if (mesh._activate(this._renderId, false)) { if (!mesh.isAnInstance) { meshToRender._internalAbstractMeshDataInfo._onlyForInstances = false; } else { if (mesh._internalAbstractMeshDataInfo._actAsRegularMesh) { meshToRender = mesh; } } meshToRender._internalAbstractMeshDataInfo._isActive = true; this._activeMesh(mesh, meshToRender); } mesh._postActivate(); } } this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this); if (this.particlesEnabled) { this.onBeforeParticlesRenderingObservable.notifyObservers(this); for (let particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) { const particleSystem = this.particleSystems[particleIndex]; if (!particleSystem.isStarted() || !particleSystem.emitter) { continue; } const emitter = particleSystem.emitter; if (!emitter.position || emitter.isEnabled()) { this._activeParticleSystems.push(particleSystem); particleSystem.animate(); this._renderingManager.dispatchParticles(particleSystem); } } this.onAfterParticlesRenderingObservable.notifyObservers(this); } } /** @internal */ _prepareSkeleton(mesh) { if (!this._skeletonsEnabled || !mesh.skeleton) { return; } if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) { mesh.skeleton.prepare(); this._activeBones.addCount(mesh.skeleton.bones.length, false); } if (!mesh.computeBonesUsingShaders) { if (this._softwareSkinnedMeshes.pushNoDuplicate(mesh) && this.frameGraph) { mesh.applySkeleton(mesh.skeleton); } } } _activeMesh(sourceMesh, mesh) { this._prepareSkeleton(mesh); let forcePush = sourceMesh.hasInstances || sourceMesh.isAnInstance || this.dispatchAllSubMeshesOfActiveMeshes || this._skipFrustumClipping || mesh.alwaysSelectAsActiveMesh; if (mesh && mesh.subMeshes && mesh.subMeshes.length > 0) { const subMeshes = this.getActiveSubMeshCandidates(mesh); const len = subMeshes.length; forcePush = forcePush || len === 1; for (let i = 0; i < len; i++) { const subMesh = subMeshes.data[i]; this._evaluateSubMesh(subMesh, mesh, sourceMesh, forcePush); } } } /** * Update the transform matrix to update from the current active camera * @param force defines a boolean used to force the update even if cache is up to date */ updateTransformMatrix(force) { const activeCamera = this.activeCamera; if (!activeCamera) { return; } if (activeCamera._renderingMultiview) { const leftCamera = activeCamera._rigCameras[0]; const rightCamera = activeCamera._rigCameras[1]; this.setTransformMatrix(leftCamera.getViewMatrix(), leftCamera.getProjectionMatrix(force), rightCamera.getViewMatrix(), rightCamera.getProjectionMatrix(force)); } else { this.setTransformMatrix(activeCamera.getViewMatrix(), activeCamera.getProjectionMatrix(force)); } } _bindFrameBuffer(camera, clear = true) { if (!this._useCurrentFrameBuffer) { if (camera && camera._multiviewTexture) { camera._multiviewTexture._bindFrameBuffer(); } else if (camera && camera.outputRenderTarget) { camera.outputRenderTarget._bindFrameBuffer(); } else { if (!this._engine._currentFrameBufferIsDefaultFrameBuffer()) { this._engine.restoreDefaultFramebuffer(); } } } if (clear) { this._clearFrameBuffer(camera); } } _clearFrameBuffer(camera) { if (camera && camera._multiviewTexture) { } else if (camera && camera.outputRenderTarget && !camera._renderingMultiview) { const rtt = camera.outputRenderTarget; if (rtt.onClearObservable.hasObservers()) { rtt.onClearObservable.notifyObservers(this._engine); } else if (!rtt.skipInitialClear && !camera.isRightCamera) { if (this.autoClear) { this._engine.clear(rtt.clearColor || this._clearColor, !rtt._cleared, true, true); } rtt._cleared = true; } } else { if (!this._defaultFrameBufferCleared) { this._defaultFrameBufferCleared = true; this._clear(); } else { this._engine.clear(null, false, true, true); } } } /** * @internal */ _renderForCamera(camera, rigParent, bindFrameBuffer = true) { if (camera && camera._skipRendering) { return; } const engine = this._engine; this._activeCamera = camera; if (!this.activeCamera) { throw new Error("Active camera not set"); } engine.setViewport(this.activeCamera.viewport); this.resetCachedMaterial(); this._renderId++; if (!this.prePass && bindFrameBuffer) { let skipInitialClear = true; if (camera._renderingMultiview && camera.outputRenderTarget) { skipInitialClear = camera.outputRenderTarget.skipInitialClear; if (this.autoClear) { this._defaultFrameBufferCleared = false; camera.outputRenderTarget.skipInitialClear = false; } } this._bindFrameBuffer(this._activeCamera); if (camera._renderingMultiview && camera.outputRenderTarget) { camera.outputRenderTarget.skipInitialClear = skipInitialClear; } } this.updateTransformMatrix(); this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera); this._evaluateActiveMeshes(); for (let softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) { const mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex]; mesh.applySkeleton(mesh.skeleton); } this.onBeforeRenderTargetsRenderObservable.notifyObservers(this); this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets); if (camera.customRenderTargets && camera.customRenderTargets.length > 0) { this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets); } if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) { this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets); } if (this.environmentTexture && this.environmentTexture.isRenderTarget) { this._renderTargets.pushNoDuplicate(this.environmentTexture); } for (const step of this._gatherActiveCameraRenderTargetsStage) { step.action(this._renderTargets); } let needRebind = false; if (this.renderTargetsEnabled) { this._intermediateRendering = true; if (this._renderTargets.length > 0) { Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0); const boundingBoxRenderer = this.getBoundingBoxRenderer?.(); let currentBoundingBoxMeshList; for (let renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) { const renderTarget = this._renderTargets.data[renderIndex]; if (renderTarget._shouldRender()) { this._renderId++; const hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera; if (boundingBoxRenderer && !currentBoundingBoxMeshList) { currentBoundingBoxMeshList = boundingBoxRenderer.renderList.length > 0 ? boundingBoxRenderer.renderList.data.slice() : []; currentBoundingBoxMeshList.length = boundingBoxRenderer.renderList.length; } renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets); needRebind = true; } } if (boundingBoxRenderer && currentBoundingBoxMeshList) { boundingBoxRenderer.renderList.data = currentBoundingBoxMeshList; boundingBoxRenderer.renderList.length = currentBoundingBoxMeshList.length; } Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0); this._renderId++; } for (const step of this._cameraDrawRenderTargetStage) { needRebind = step.action(this.activeCamera) || needRebind; } this._intermediateRendering = false; } this._engine.currentRenderPassId = camera.outputRenderTarget?.renderPassId ?? camera.renderPassId ?? 0; if (needRebind && !this.prePass) { this._bindFrameBuffer(this._activeCamera, false); this.updateTransformMatrix(); } this.onAfterRenderTargetsRenderObservable.notifyObservers(this); if (this.postProcessManager && !camera._multiviewTexture && !this.prePass) { this.postProcessManager._prepareFrame(); } for (const step of this._beforeCameraDrawStage) { step.action(this.activeCamera); } this.onBeforeDrawPhaseObservable.notifyObservers(this); const fastSnapshotMode = engine.snapshotRendering && engine.snapshotRenderingMode === 1; if (fastSnapshotMode) { this.finalizeSceneUbo(); } this._renderingManager.render(null, null, true, !fastSnapshotMode); this.onAfterDrawPhaseObservable.notifyObservers(this); for (const step of this._afterCameraDrawStage) { step.action(this.activeCamera); } if (this.postProcessManager && !camera._multiviewTexture) { const texture = camera.outputRenderTarget ? camera.outputRenderTarget.renderTarget : void 0; this.postProcessManager._finalizeFrame(camera.isIntermediate, texture); } for (const step of this._afterCameraPostProcessStage) { step.action(this.activeCamera); } this._renderTargets.reset(); this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera); } _processSubCameras(camera, bindFrameBuffer = true) { if (camera.cameraRigMode === 0 || camera._renderingMultiview) { if (camera._renderingMultiview && !this._multiviewSceneUbo) { this._createMultiviewUbo(); } this._renderForCamera(camera, void 0, bindFrameBuffer); this.onAfterRenderCameraObservable.notifyObservers(camera); return; } if (camera._useMultiviewToSingleView) { this._renderMultiviewToSingleView(camera); } else { this.onBeforeCameraRenderObservable.notifyObservers(camera); for (let index = 0; index < camera._rigCameras.length; index++) { this._renderForCamera(camera._rigCameras[index], camera); } } this._activeCamera = camera; this.updateTransformMatrix(); this.onAfterRenderCameraObservable.notifyObservers(camera); } _checkIntersections() { for (let index = 0; index < this._meshesForIntersections.length; index++) { const sourceMesh = this._meshesForIntersections.data[index]; if (!sourceMesh.actionManager) { continue; } for (let actionIndex = 0; sourceMesh.actionManager && actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) { const action = sourceMesh.actionManager.actions[actionIndex]; if (action.trigger === 12 || action.trigger === 13) { const parameters = action.getTriggerParameter(); const otherMesh = parameters.mesh ? parameters.mesh : parameters; const areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection); const currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh); if (areIntersecting && currentIntersectionInProgress === -1) { if (action.trigger === 12) { action._executeCurrent(ActionEvent.CreateNew(sourceMesh, void 0, otherMesh)); sourceMesh._intersectionsInProgress.push(otherMesh); } else if (action.trigger === 13) { sourceMesh._intersectionsInProgress.push(otherMesh); } } else if (!areIntersecting && currentIntersectionInProgress > -1) { if (action.trigger === 13) { action._executeCurrent(ActionEvent.CreateNew(sourceMesh, void 0, otherMesh)); } if (!sourceMesh.actionManager.hasSpecificTrigger(13, (parameter) => { const parameterMesh = parameter.mesh ? parameter.mesh : parameter; return otherMesh === parameterMesh; }) || action.trigger === 13) { sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1); } } } } } } /** * @internal */ _advancePhysicsEngineStep(step) { } /** @internal */ _animate(customDeltaTime) { } /** Execute all animations (for a frame) */ animate() { if (this._engine.isDeterministicLockStep()) { let deltaTime = Math.max(_Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), _Scene.MaxDeltaTime)) + this._timeAccumulator; const defaultFrameTime = this._engine.getTimeStep(); const defaultFPS = 1e3 / defaultFrameTime / 1e3; let stepsTaken = 0; const maxSubSteps = this._engine.getLockstepMaxSteps(); let internalSteps = Math.floor(deltaTime / defaultFrameTime); internalSteps = Math.min(internalSteps, maxSubSteps); while (deltaTime > 0 && stepsTaken < internalSteps) { this.onBeforeStepObservable.notifyObservers(this); this._animationRatio = defaultFrameTime * defaultFPS; this._animate(defaultFrameTime); this.onAfterAnimationsObservable.notifyObservers(this); if (this.physicsEnabled) { this._advancePhysicsEngineStep(defaultFrameTime); } this.onAfterStepObservable.notifyObservers(this); this._currentStepId++; stepsTaken++; deltaTime -= defaultFrameTime; } this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime; } else { const deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(_Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), _Scene.MaxDeltaTime)); this._animationRatio = deltaTime * (60 / 1e3); this._animate(); this.onAfterAnimationsObservable.notifyObservers(this); if (this.physicsEnabled) { this._advancePhysicsEngineStep(deltaTime); } } } _clear() { if (this.autoClearDepthAndStencil || this.autoClear) { this._engine.clear(this._clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil); } } _checkCameraRenderTarget(camera) { if (camera?.outputRenderTarget && !camera?.isRigCamera) { camera.outputRenderTarget._cleared = false; } if (camera?.rigCameras?.length) { for (let i = 0; i < camera.rigCameras.length; ++i) { const rtt = camera.rigCameras[i].outputRenderTarget; if (rtt) { rtt._cleared = false; } } } } /** * Resets the draw wrappers cache of all meshes * @param passId If provided, releases only the draw wrapper corresponding to this render pass id */ resetDrawCache(passId) { if (!this.meshes) { return; } for (const mesh of this.meshes) { mesh.resetDrawCache(passId); } } _renderWithFrameGraph(updateCameras = true, _ignoreAnimations = false, forceUpdateWorldMatrix = false) { this.activeCamera = null; this.activeCameras = null; if (updateCameras) { for (const camera of this.cameras) { camera.update(); if (camera.cameraRigMode !== 0) { for (let index = 0; index < camera._rigCameras.length; index++) { camera._rigCameras[index].update(); } } } } this.onBeforeRenderObservable.notifyObservers(this); for (const step of this._beforeClearStage) { step.action(); } if (this._engine.snapshotRendering && this._engine.snapshotRenderingMode === 1) { this._activeParticleSystems.reset(); this._activeSkeletons.reset(); this._softwareSkinnedMeshes.reset(); } else { const meshes = this.getActiveMeshCandidates(); const len = meshes.length; if (!this._activeMeshesFrozen) { this._activeParticleSystems.reset(); this._activeSkeletons.reset(); this._softwareSkinnedMeshes.reset(); for (let i = 0; i < len; i++) { const mesh = meshes.data[i]; mesh._internalAbstractMeshDataInfo._wasActiveLastFrame = false; if (mesh.isBlocked) { continue; } this._totalVertices.addCount(mesh.getTotalVertices(), false); if (!mesh.isReady() || !mesh.isEnabled() || mesh.scaling.hasAZeroComponent) { continue; } mesh.computeWorldMatrix(forceUpdateWorldMatrix); if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(12, 13)) { this._meshesForIntersections.pushNoDuplicate(mesh); } } if (this.particlesEnabled) { for (let particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) { const particleSystem = this.particleSystems[particleIndex]; if (!particleSystem.isStarted() || !particleSystem.emitter) { continue; } const emitter = particleSystem.emitter; if (!emitter.position || emitter.isEnabled()) { this._activeParticleSystems.push(particleSystem); particleSystem.animate(); } } } } else { if (!this._skipEvaluateActiveMeshesCompletely) { for (let i = 0; i < len; i++) { const mesh = meshes.data[i]; if (mesh._internalAbstractMeshDataInfo._wasActiveLastFrame) { mesh.computeWorldMatrix(); } } } if (this.particlesEnabled) { const psLength = this._activeParticleSystems.length; for (let i = 0; i < psLength; i++) { this._activeParticleSystems.data[i].animate(); } } } } this.frameGraph?.execute(); } /** * @internal */ _renderRenderTarget(renderTarget, activeCamera, useCameraPostProcess = false, dumpForDebug = false) { this._intermediateRendering = true; if (renderTarget._shouldRender()) { this._renderId++; this.activeCamera = activeCamera; if (!this.activeCamera) { throw new Error("Active camera not set"); } this._engine.setViewport(this.activeCamera.viewport); this.updateTransformMatrix(); renderTarget.render(useCameraPostProcess, dumpForDebug); } this._intermediateRendering = false; } /** * Render the scene * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default) * @param ignoreAnimations defines a boolean indicating if animations should not be executed (false by default) */ render(updateCameras = true, ignoreAnimations = false) { if (this.isDisposed) { return; } if (this.onReadyObservable.hasObservers() && this._executeWhenReadyTimeoutId === null) { this._checkIsReady(); } FloatingOriginCurrentScene.getScene = this._getFloatingOriginScene; this._frameId++; this._defaultFrameBufferCleared = false; this._checkCameraRenderTarget(this.activeCamera); if (this.activeCameras?.length) { for (const c of this.activeCameras) { this._checkCameraRenderTarget(c); } } this._registerTransientComponents(); this._activeParticles.fetchNewFrame(); this._totalVertices.fetchNewFrame(); this._activeIndices.fetchNewFrame(); this._activeBones.fetchNewFrame(); this._meshesForIntersections.reset(); this.resetCachedMaterial(); this.onBeforeAnimationsObservable.notifyObservers(this); if (this.actionManager) { this.actionManager.processTrigger(11); } if (!ignoreAnimations) { this.animate(); } for (const step of this._beforeCameraUpdateStage) { step.action(); } if (updateCameras) { if (this.activeCameras && this.activeCameras.length > 0) { for (let cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) { const camera = this.activeCameras[cameraIndex]; camera.update(); if (camera.cameraRigMode !== 0) { for (let index = 0; index < camera._rigCameras.length; index++) { camera._rigCameras[index].update(); } } } } else if (this.activeCamera) { this.activeCamera.update(); if (this.activeCamera.cameraRigMode !== 0) { for (let index = 0; index < this.activeCamera._rigCameras.length; index++) { this.activeCamera._rigCameras[index].update(); } } } } if (this.customRenderFunction) { this._renderId++; this._engine.currentRenderPassId = 0; this.customRenderFunction(updateCameras, ignoreAnimations); } else { this.onBeforeRenderObservable.notifyObservers(this); this.onBeforeRenderTargetsRenderObservable.notifyObservers(this); const currentActiveCamera = this.activeCameras?.length ? this.activeCameras[0] : this.activeCamera; if (this.renderTargetsEnabled) { Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0); for (let customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) { const renderTarget = this.customRenderTargets[customIndex]; const activeCamera = renderTarget.activeCamera || this.activeCamera; this._renderRenderTarget(renderTarget, activeCamera, currentActiveCamera !== activeCamera, this.dumpNextRenderTargets); } Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0); this._renderId++; } this._engine.currentRenderPassId = currentActiveCamera?.renderPassId ?? 0; this.activeCamera = currentActiveCamera; if (this._activeCamera && this._activeCamera.cameraRigMode !== 22 && !this.prePass) { this._bindFrameBuffer(this._activeCamera, false); } this.onAfterRenderTargetsRenderObservable.notifyObservers(this); for (const step of this._beforeClearStage) { step.action(); } this._clearFrameBuffer(this.activeCamera); for (const step of this._gatherRenderTargetsStage) { step.action(this._renderTargets); } if (this.activeCameras && this.activeCameras.length > 0) { for (let cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) { this._processSubCameras(this.activeCameras[cameraIndex], cameraIndex > 0); } } else { if (!this.activeCamera) { throw new Error("No camera defined"); } this._processSubCameras(this.activeCamera, !!this.activeCamera.outputRenderTarget); } } this._checkIntersections(); for (const step of this._afterRenderStage) { step.action(); } if (this.afterRender) { this.afterRender(); } this.onAfterRenderObservable.notifyObservers(this); if (this._toBeDisposed.length) { for (let index = 0; index < this._toBeDisposed.length; index++) { const data = this._toBeDisposed[index]; if (data) { data.dispose(); } } this._toBeDisposed.length = 0; } if (this.dumpNextRenderTargets) { this.dumpNextRenderTargets = false; } this._activeBones.addCount(0, true); this._activeIndices.addCount(0, true); this._activeParticles.addCount(0, true); this._engine.restoreDefaultFramebuffer(); } /** * Freeze all materials * A frozen material will not be updatable but should be faster to render * Note: multimaterials will not be frozen, but their submaterials will */ freezeMaterials() { for (let i = 0; i < this.materials.length; i++) { this.materials[i].freeze(); } } /** * Unfreeze all materials * A frozen material will not be updatable but should be faster to render */ unfreezeMaterials() { for (let i = 0; i < this.materials.length; i++) { this.materials[i].unfreeze(); } } /** * Releases all held resources */ dispose() { if (this.isDisposed) { return; } this.beforeRender = null; this.afterRender = null; this.metadata = null; this.skeletons.length = 0; this.morphTargetManagers.length = 0; this._transientComponents.length = 0; this._isReadyForMeshStage.clear(); this._beforeEvaluateActiveMeshStage.clear(); this._evaluateSubMeshStage.clear(); this._preActiveMeshStage.clear(); this._cameraDrawRenderTargetStage.clear(); this._beforeCameraDrawStage.clear(); this._beforeRenderTargetDrawStage.clear(); this._beforeRenderingGroupDrawStage.clear(); this._beforeRenderingMeshStage.clear(); this._afterRenderingMeshStage.clear(); this._afterRenderingGroupDrawStage.clear(); this._afterCameraDrawStage.clear(); this._afterRenderTargetDrawStage.clear(); this._afterRenderStage.clear(); this._beforeCameraUpdateStage.clear(); this._beforeClearStage.clear(); this._gatherRenderTargetsStage.clear(); this._gatherActiveCameraRenderTargetsStage.clear(); this._pointerMoveStage.clear(); this._pointerDownStage.clear(); this._pointerUpStage.clear(); this.importedMeshesFiles = []; if (this._activeAnimatables && this.stopAllAnimations) { for (const animatable of this._activeAnimatables) { animatable.onAnimationEndObservable.clear(); animatable.onAnimationEnd = null; } this.stopAllAnimations(); } this.resetCachedMaterial(); if (this.activeCamera) { this.activeCamera._activeMeshes.dispose(); this.activeCamera = null; } this.activeCameras = null; this._activeMeshes.dispose(); this._renderingManager.dispose(); this._processedMaterials.dispose(); this._activeParticleSystems.dispose(); this._activeSkeletons.dispose(); this._softwareSkinnedMeshes.dispose(); this._renderTargets.dispose(); this._materialsRenderTargets.dispose(); this._registeredForLateAnimationBindings.dispose(); this._meshesForIntersections.dispose(); this._toBeDisposed.length = 0; const activeRequests = this._activeRequests.slice(); for (const request of activeRequests) { request.abort(); } this._activeRequests.length = 0; try { this.onDisposeObservable.notifyObservers(this); } catch (e) { Logger.Error("An error occurred while calling onDisposeObservable!", e); } this.detachControl(); const canvas = this._engine.getInputElement(); if (canvas) { for (let index2 = 0; index2 < this.cameras.length; index2++) { this.cameras[index2].detachControl(); } } this._disposeList(this.animationGroups); this._disposeList(this.lights); if (this._defaultMaterial) { this._defaultMaterial.dispose(); } this._disposeList(this.multiMaterials); this._disposeList(this.materials); this._disposeList(this.meshes, (item) => item.dispose(true)); this._disposeList(this.transformNodes, (item) => item.dispose(true)); const cameras = this.cameras; this._disposeList(cameras); this._disposeList(this.particleSystems); this._disposeList(this.postProcesses); this._disposeList(this.textures); this._disposeList(this.morphTargetManagers); this._disposeList(this.frameGraphs); this._sceneUbo.dispose(); if (this._multiviewSceneUbo) { this._multiviewSceneUbo.dispose(); } this.postProcessManager.dispose(); this._disposeList(this._components); let index = this._engine.scenes.indexOf(this); if (index > -1) { this._engine.scenes.splice(index, 1); } this._floatingOriginScene = void 0; if (this._engine.scenes.length === 0) { ResetMatrixFunctions(); } if (EngineStore._LastCreatedScene === this) { EngineStore._LastCreatedScene = null; let engineIndex = EngineStore.Instances.length - 1; while (engineIndex >= 0) { const engine = EngineStore.Instances[engineIndex]; if (engine.scenes.length > 0) { EngineStore._LastCreatedScene = engine.scenes[this._engine.scenes.length - 1]; break; } engineIndex--; } } index = this._engine._virtualScenes.indexOf(this); if (index > -1) { this._engine._virtualScenes.splice(index, 1); } this._engine.wipeCaches(true); this.onDisposeObservable.clear(); this.onBeforeRenderObservable.clear(); this.onAfterRenderObservable.clear(); this.onBeforeRenderTargetsRenderObservable.clear(); this.onAfterRenderTargetsRenderObservable.clear(); this.onAfterStepObservable.clear(); this.onBeforeStepObservable.clear(); this.onBeforeActiveMeshesEvaluationObservable.clear(); this.onAfterActiveMeshesEvaluationObservable.clear(); this.onBeforeParticlesRenderingObservable.clear(); this.onAfterParticlesRenderingObservable.clear(); this.onBeforeDrawPhaseObservable.clear(); this.onAfterDrawPhaseObservable.clear(); this.onBeforeAnimationsObservable.clear(); this.onAfterAnimationsObservable.clear(); this.onDataLoadedObservable.clear(); this.onBeforeRenderingGroupObservable.clear(); this.onAfterRenderingGroupObservable.clear(); this.onMeshImportedObservable.clear(); this.onBeforeCameraRenderObservable.clear(); this.onAfterCameraRenderObservable.clear(); this.onAfterRenderCameraObservable.clear(); this.onReadyObservable.clear(); this.onNewCameraAddedObservable.clear(); this.onCameraRemovedObservable.clear(); this.onNewLightAddedObservable.clear(); this.onLightRemovedObservable.clear(); this.onNewGeometryAddedObservable.clear(); this.onGeometryRemovedObservable.clear(); this.onNewTransformNodeAddedObservable.clear(); this.onTransformNodeRemovedObservable.clear(); this.onNewMeshAddedObservable.clear(); this.onMeshRemovedObservable.clear(); this.onNewSkeletonAddedObservable.clear(); this.onSkeletonRemovedObservable.clear(); this.onNewMaterialAddedObservable.clear(); this.onNewMultiMaterialAddedObservable.clear(); this.onMaterialRemovedObservable.clear(); this.onMultiMaterialRemovedObservable.clear(); this.onNewTextureAddedObservable.clear(); this.onTextureRemovedObservable.clear(); this.onNewFrameGraphAddedObservable.clear(); this.onFrameGraphRemovedObservable.clear(); this.onNewObjectRendererAddedObservable.clear(); this.onObjectRendererRemovedObservable.clear(); this.onPrePointerObservable.clear(); this.onPointerObservable.clear(); this.onPreKeyboardObservable.clear(); this.onKeyboardObservable.clear(); this.onActiveCameraChanged.clear(); this.onScenePerformancePriorityChangedObservable.clear(); this.onClearColorChangedObservable.clear(); this.onEnvironmentTextureChangedObservable.clear(); this.onMeshUnderPointerUpdatedObservable.clear(); this._isDisposed = true; } _disposeList(items, callback) { const itemsCopy = items.slice(0); callback = callback ?? ((item) => item.dispose()); for (const item of itemsCopy) { callback(item); } items.length = 0; } /** * Gets if the scene is already disposed */ get isDisposed() { return this._isDisposed; } /** * Call this function to reduce memory footprint of the scene. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly) */ clearCachedVertexData() { for (let meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) { const mesh = this.meshes[meshIndex]; const geometry = mesh.geometry; if (geometry) { geometry.clearCachedData(); } } } /** * This function will remove the local cached buffer data from texture. * It will save memory but will prevent the texture from being rebuilt */ cleanCachedTextureBuffer() { for (const baseTexture of this.textures) { const buffer = baseTexture._buffer; if (buffer) { baseTexture._buffer = null; } } } /** * Get the world extend vectors with an optional filter * * @param filterPredicate the predicate - which meshes should be included when calculating the world size * @returns {{ min: Vector3; max: Vector3 }} min and max vectors */ getWorldExtends(filterPredicate) { const min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); const max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); filterPredicate = filterPredicate || (() => true); const meshes = this.meshes.filter(filterPredicate); for (const mesh of meshes) { mesh.computeWorldMatrix(true); if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) { continue; } const boundingInfo = mesh.getBoundingInfo(); const minBox = boundingInfo.boundingBox.minimumWorld; const maxBox = boundingInfo.boundingBox.maximumWorld; Vector3.CheckExtends(minBox, min, max); Vector3.CheckExtends(maxBox, min, max); } return { min, max }; } // Picking // eslint-disable-next-line jsdoc/require-returns-check /** * Creates a ray that can be used to pick in the scene * @param x defines the x coordinate of the origin (on-screen) * @param y defines the y coordinate of the origin (on-screen) * @param world defines the world matrix to use if you want to pick in object space (instead of world space) * @param camera defines the camera to use for the picking * @param cameraViewSpace defines if picking will be done in view space (false by default) * @returns a Ray */ createPickingRay(x, y, world, camera, cameraViewSpace = false) { throw _WarnImport("Ray"); } // eslint-disable-next-line jsdoc/require-returns-check /** * Creates a ray that can be used to pick in the scene * @param x defines the x coordinate of the origin (on-screen) * @param y defines the y coordinate of the origin (on-screen) * @param world defines the world matrix to use if you want to pick in object space (instead of world space) * @param result defines the ray where to store the picking ray * @param camera defines the camera to use for the picking * @param cameraViewSpace defines if picking will be done in view space (false by default) * @param enableDistantPicking defines if picking should handle large values for mesh position/scaling (false by default) * @returns the current scene */ createPickingRayToRef(x, y, world, result, camera, cameraViewSpace = false, enableDistantPicking = false) { throw _WarnImport("Ray"); } // eslint-disable-next-line jsdoc/require-returns-check /** * Creates a ray that can be used to pick in the scene * @param x defines the x coordinate of the origin (on-screen) * @param y defines the y coordinate of the origin (on-screen) * @param camera defines the camera to use for the picking * @returns a Ray */ createPickingRayInCameraSpace(x, y, camera) { throw _WarnImport("Ray"); } // eslint-disable-next-line jsdoc/require-returns-check /** * Creates a ray that can be used to pick in the scene * @param x defines the x coordinate of the origin (on-screen) * @param y defines the y coordinate of the origin (on-screen) * @param result defines the ray where to store the picking ray * @param camera defines the camera to use for the picking * @returns the current scene */ createPickingRayInCameraSpaceToRef(x, y, result, camera) { throw _WarnImport("Ray"); } /** Launch a ray to try to pick a mesh in the scene * @param x position on screen * @param y position on screen * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced * @param fastCheck defines if the first intersection will be used (and not the closest) * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected * @returns a PickingInfo */ pick(x, y, predicate, fastCheck, camera, trianglePredicate) { const warn = _WarnImport("Ray", true); if (warn) { Logger.Warn(warn); } return new PickingInfo(); } /** Launch a ray to try to pick a mesh in the scene using only bounding information of the main mesh (not using submeshes) * @param x position on screen * @param y position on screen * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced * @param fastCheck defines if the first intersection will be used (and not the closest) * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used * @returns a PickingInfo (Please note that some info will not be set like distance, bv, bu and everything that cannot be capture by only using bounding infos) */ pickWithBoundingInfo(x, y, predicate, fastCheck, camera) { const warn = _WarnImport("Ray", true); if (warn) { Logger.Warn(warn); } return new PickingInfo(); } // eslint-disable-next-line jsdoc/require-returns-check /** * Use the given ray to pick a mesh in the scene. A mesh triangle can be picked both from its front and back sides, * irrespective of orientation. * @param ray The ray to use to pick meshes * @param predicate Predicate function used to determine eligible meshes. Can be set to null. In this case, a mesh must have isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced * @param fastCheck defines if the first intersection will be used (and not the closest) * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected * @returns a PickingInfo */ pickWithRay(ray, predicate, fastCheck, trianglePredicate) { throw _WarnImport("Ray"); } // eslint-disable-next-line jsdoc/require-returns-check /** * Launch a ray to try to pick a mesh in the scene. A mesh triangle can be picked both from its front and back sides, * irrespective of orientation. * @param x X position on screen * @param y Y position on screen * @param predicate Predicate function used to determine eligible meshes and instances. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected * @returns an array of PickingInfo */ multiPick(x, y, predicate, camera, trianglePredicate) { throw _WarnImport("Ray"); } // eslint-disable-next-line jsdoc/require-returns-check /** * Launch a ray to try to pick a mesh in the scene * @param ray Ray to use * @param predicate Predicate function used to determine eligible meshes and instances. Can be set to null. In this case, a mesh must be enabled, visible and with isPickable set to true. thinInstanceIndex is -1 when the mesh is non-instanced * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected * @returns an array of PickingInfo */ multiPickWithRay(ray, predicate, trianglePredicate) { throw _WarnImport("Ray"); } /** * Force the value of meshUnderPointer * @param mesh defines the mesh to use * @param pointerId optional pointer id when using more than one pointer * @param pickResult optional pickingInfo data used to find mesh */ setPointerOverMesh(mesh, pointerId, pickResult) { this._inputManager.setPointerOverMesh(mesh, pointerId, pickResult); } /** * Gets the mesh under the pointer * @returns a Mesh or null if no mesh is under the pointer */ getPointerOverMesh() { return this._inputManager.getPointerOverMesh(); } // Misc. /** @internal */ _rebuildGeometries() { for (const geometry of this.geometries) { geometry._rebuild(); } for (const mesh of this.meshes) { mesh._rebuild(); } if (this.postProcessManager) { this.postProcessManager._rebuild(); } for (const component of this._components) { component.rebuild(); } for (const system of this.particleSystems) { system.rebuild(); } if (this.spriteManagers) { for (const spriteMgr of this.spriteManagers) { spriteMgr.rebuild(); } } } /** @internal */ _rebuildTextures() { for (const texture of this.textures) { texture._rebuild(true); } this.markAllMaterialsAsDirty(1); } /** * Get from a list of objects by tags * @param list the list of objects to use * @param tagsQuery the query to use * @param filter a predicate to filter for tags * @returns */ _getByTags(list, tagsQuery, filter) { if (tagsQuery === void 0) { return list; } const listByTags = []; for (const i in list) { const item = list[i]; if (Tags && Tags.MatchesQuery(item, tagsQuery) && (!filter || filter(item))) { listByTags.push(item); } } return listByTags; } /** * Get a list of meshes by tags * @param tagsQuery defines the tags query to use * @param filter defines a predicate used to filter results * @returns an array of Mesh */ getMeshesByTags(tagsQuery, filter) { return this._getByTags(this.meshes, tagsQuery, filter); } /** * Get a list of cameras by tags * @param tagsQuery defines the tags query to use * @param filter defines a predicate used to filter results * @returns an array of Camera */ getCamerasByTags(tagsQuery, filter) { return this._getByTags(this.cameras, tagsQuery, filter); } /** * Get a list of lights by tags * @param tagsQuery defines the tags query to use * @param filter defines a predicate used to filter results * @returns an array of Light */ getLightsByTags(tagsQuery, filter) { return this._getByTags(this.lights, tagsQuery, filter); } /** * Get a list of materials by tags * @param tagsQuery defines the tags query to use * @param filter defines a predicate used to filter results * @returns an array of Material */ getMaterialByTags(tagsQuery, filter) { return this._getByTags(this.materials, tagsQuery, filter).concat(this._getByTags(this.multiMaterials, tagsQuery, filter)); } /** * Get a list of transform nodes by tags * @param tagsQuery defines the tags query to use * @param filter defines a predicate used to filter results * @returns an array of TransformNode */ getTransformNodesByTags(tagsQuery, filter) { return this._getByTags(this.transformNodes, tagsQuery, filter); } /** * Overrides the default sort function applied in the rendering group to prepare the meshes. * This allowed control for front to back rendering or reversly depending of the special needs. * * @param renderingGroupId The rendering group id corresponding to its index * @param opaqueSortCompareFn The opaque queue comparison function use to sort. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort. * @param transparentSortCompareFn The transparent queue comparison function use to sort. */ setRenderingOrder(renderingGroupId, opaqueSortCompareFn = null, alphaTestSortCompareFn = null, transparentSortCompareFn = null) { this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn); } /** * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups. * * @param renderingGroupId The rendering group id corresponding to its index * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true. * @param depth Automatically clears depth between groups if true and autoClear is true. * @param stencil Automatically clears stencil between groups if true and autoClear is true. */ setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth = true, stencil = true) { this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil); } /** * Gets the current auto clear configuration for one rendering group of the rendering * manager. * @param index the rendering group index to get the information for * @returns The auto clear setup for the requested rendering group */ getAutoClearDepthStencilSetup(index) { return this._renderingManager.getAutoClearDepthStencilSetup(index); } /** @internal */ _forceBlockMaterialDirtyMechanism(value) { this._blockMaterialDirtyMechanism = value; } /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */ get blockMaterialDirtyMechanism() { return this._blockMaterialDirtyMechanism; } set blockMaterialDirtyMechanism(value) { if (this._blockMaterialDirtyMechanism === value) { return; } this._blockMaterialDirtyMechanism = value; if (!value) { this.markAllMaterialsAsDirty(127); } } /** * Will flag all materials as dirty to trigger new shader compilation * @param flag defines the flag used to specify which material part must be marked as dirty * @param predicate If not null, it will be used to specify if a material has to be marked as dirty */ markAllMaterialsAsDirty(flag, predicate) { if (this._blockMaterialDirtyMechanism) { return; } for (const material of this.materials) { if (predicate && !predicate(material)) { continue; } material.markAsDirty(flag); } } /** * @internal */ _loadFile(fileOrUrl, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError, onOpened) { const request = LoadFile(fileOrUrl, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : void 0, useArrayBuffer, onError, onOpened); this._activeRequests.push(request); request.onCompleteObservable.add((request2) => { this._activeRequests.splice(this._activeRequests.indexOf(request2), 1); }); return request; } /** * @internal */ async _loadFileAsync(fileOrUrl, onProgress, useOfflineSupport, useArrayBuffer, onOpened) { return await new Promise((resolve, reject) => { this._loadFile(fileOrUrl, (data) => { resolve(data); }, onProgress, useOfflineSupport, useArrayBuffer, (request, exception) => { reject(exception); }, onOpened); }); } /** * @internal */ _requestFile(url, onSuccess, onProgress, useOfflineSupport, useArrayBuffer, onError, onOpened) { const request = RequestFile(url, onSuccess, onProgress, useOfflineSupport ? this.offlineProvider : void 0, useArrayBuffer, onError, onOpened); this._activeRequests.push(request); request.onCompleteObservable.add((request2) => { this._activeRequests.splice(this._activeRequests.indexOf(request2), 1); }); return request; } /** * @internal */ async _requestFileAsync(url, onProgress, useOfflineSupport, useArrayBuffer, onOpened) { return await new Promise((resolve, reject) => { this._requestFile(url, (data) => { resolve(data); }, onProgress, useOfflineSupport, useArrayBuffer, (error) => { reject(error); }, onOpened); }); } /** * @internal */ _readFile(file, onSuccess, onProgress, useArrayBuffer, onError) { const request = ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError); this._activeRequests.push(request); request.onCompleteObservable.add((request2) => { this._activeRequests.splice(this._activeRequests.indexOf(request2), 1); }); return request; } /** * @internal */ async _readFileAsync(file, onProgress, useArrayBuffer) { return await new Promise((resolve, reject) => { this._readFile(file, (data) => { resolve(data); }, onProgress, useArrayBuffer, (error) => { reject(error); }); }); } // eslint-disable-next-line jsdoc/require-returns-check /** * This method gets the performance collector belonging to the scene, which is generally shared with the inspector. * @returns the perf collector belonging to the scene. */ getPerfCollector() { throw _WarnImport("performanceViewerSceneExtension"); } // deprecated /** * Sets the active camera of the scene using its Id * @param id defines the camera's Id * @returns the new active camera or null if none found. * @deprecated Please use setActiveCameraById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention setActiveCameraByID(id) { return this.setActiveCameraById(id); } /** * Get a material using its id * @param id defines the material's Id * @returns the material or null if none found. * @deprecated Please use getMaterialById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getMaterialByID(id) { return this.getMaterialById(id); } /** * Gets a the last added material using a given id * @param id defines the material's Id * @returns the last material with the given id or null if none found. * @deprecated Please use getLastMaterialById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getLastMaterialByID(id) { return this.getLastMaterialById(id); } /** * Get a texture using its unique id * @param uniqueId defines the texture's unique id * @returns the texture or null if none found. * @deprecated Please use getTextureByUniqueId instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getTextureByUniqueID(uniqueId) { return this.getTextureByUniqueId(uniqueId); } /** * Gets a camera using its Id * @param id defines the Id to look for * @returns the camera or null if not found * @deprecated Please use getCameraById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getCameraByID(id) { return this.getCameraById(id); } /** * Gets a camera using its unique Id * @param uniqueId defines the unique Id to look for * @returns the camera or null if not found * @deprecated Please use getCameraByUniqueId instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getCameraByUniqueID(uniqueId) { return this.getCameraByUniqueId(uniqueId); } /** * Gets a bone using its Id * @param id defines the bone's Id * @returns the bone or null if not found * @deprecated Please use getBoneById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getBoneByID(id) { return this.getBoneById(id); } /** * Gets a light node using its Id * @param id defines the light's Id * @returns the light or null if none found. * @deprecated Please use getLightById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getLightByID(id) { return this.getLightById(id); } /** * Gets a light node using its scene-generated unique Id * @param uniqueId defines the light's unique Id * @returns the light or null if none found. * @deprecated Please use getLightByUniqueId instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getLightByUniqueID(uniqueId) { return this.getLightByUniqueId(uniqueId); } /** * Gets a particle system by Id * @param id defines the particle system Id * @returns the corresponding system or null if none found * @deprecated Please use getParticleSystemById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getParticleSystemByID(id) { return this.getParticleSystemById(id); } /** * Gets a geometry using its Id * @param id defines the geometry's Id * @returns the geometry or null if none found. * @deprecated Please use getGeometryById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getGeometryByID(id) { return this.getGeometryById(id); } /** * Gets the first added mesh found of a given Id * @param id defines the Id to search for * @returns the mesh found or null if not found at all * @deprecated Please use getMeshById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getMeshByID(id) { return this.getMeshById(id); } /** * Gets a mesh with its auto-generated unique Id * @param uniqueId defines the unique Id to search for * @returns the found mesh or null if not found at all. * @deprecated Please use getMeshByUniqueId instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getMeshByUniqueID(uniqueId) { return this.getMeshByUniqueId(uniqueId); } /** * Gets a the last added mesh using a given Id * @param id defines the Id to search for * @returns the found mesh or null if not found at all. * @deprecated Please use getLastMeshById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getLastMeshByID(id) { return this.getLastMeshById(id); } /** * Gets a list of meshes using their Id * @param id defines the Id to search for * @returns a list of meshes * @deprecated Please use getMeshesById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getMeshesByID(id) { return this.getMeshesById(id); } /** * Gets the first added transform node found of a given Id * @param id defines the Id to search for * @returns the found transform node or null if not found at all. * @deprecated Please use getTransformNodeById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getTransformNodeByID(id) { return this.getTransformNodeById(id); } /** * Gets a transform node with its auto-generated unique Id * @param uniqueId defines the unique Id to search for * @returns the found transform node or null if not found at all. * @deprecated Please use getTransformNodeByUniqueId instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getTransformNodeByUniqueID(uniqueId) { return this.getTransformNodeByUniqueId(uniqueId); } /** * Gets a list of transform nodes using their Id * @param id defines the Id to search for * @returns a list of transform nodes * @deprecated Please use getTransformNodesById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getTransformNodesByID(id) { return this.getTransformNodesById(id); } /** * Gets a node (Mesh, Camera, Light) using a given Id * @param id defines the Id to search for * @returns the found node or null if not found at all * @deprecated Please use getNodeById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getNodeByID(id) { return this.getNodeById(id); } /** * Gets a the last added node (Mesh, Camera, Light) using a given Id * @param id defines the Id to search for * @returns the found node or null if not found at all * @deprecated Please use getLastEntryById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getLastEntryByID(id) { return this.getLastEntryById(id); } /** * Gets a skeleton using a given Id (if many are found, this function will pick the last one) * @param id defines the Id to search for * @returns the found skeleton or null if not found at all. * @deprecated Please use getLastSkeletonById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention getLastSkeletonByID(id) { return this.getLastSkeletonById(id); } }; Scene.FOGMODE_NONE = 0; Scene.FOGMODE_EXP = 1; Scene.FOGMODE_EXP2 = 2; Scene.FOGMODE_LINEAR = 3; Scene.MinDeltaTime = 1; Scene.MaxDeltaTime = 1e3; Scene._OriginalDefaultMaterialFactory = Scene.DefaultMaterialFactory; RegisterClass("BABYLON.Scene", Scene); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/rgbdEncode.fragment.js var rgbdEncode_fragment_exports = {}; __export(rgbdEncode_fragment_exports, { rgbdEncodePixelShader: () => rgbdEncodePixelShader }); var name93, shader93, rgbdEncodePixelShader; var init_rgbdEncode_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/rgbdEncode.fragment.js"() { init_shaderStore(); init_helperFunctions2(); name93 = "rgbdEncodePixelShader"; shader93 = `varying vec2 vUV;uniform sampler2D textureSampler; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);}`; if (!ShaderStore.ShadersStore[name93]) { ShaderStore.ShadersStore[name93] = shader93; } rgbdEncodePixelShader = { name: name93, shader: shader93 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/rgbdEncode.fragment.js var rgbdEncode_fragment_exports2 = {}; __export(rgbdEncode_fragment_exports2, { rgbdEncodePixelShaderWGSL: () => rgbdEncodePixelShaderWGSL }); var name94, shader94, rgbdEncodePixelShaderWGSL; var init_rgbdEncode_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/rgbdEncode.fragment.js"() { init_shaderStore(); init_helperFunctions(); name94 = "rgbdEncodePixelShader"; shader94 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=toRGBD(textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb);}`; if (!ShaderStore.ShadersStoreWGSL[name94]) { ShaderStore.ShadersStoreWGSL[name94] = shader94; } rgbdEncodePixelShaderWGSL = { name: name94, shader: shader94 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/rgbdTextureTools.js var RGBDTextureTools; var init_rgbdTextureTools = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/rgbdTextureTools.js"() { init_postProcess(); init_textureTools(); RGBDTextureTools = class { static { __name(this, "RGBDTextureTools"); } /** * Expand the RGBD Texture from RGBD to Half Float if possible. * @param texture the texture to expand. */ static ExpandRGBDTexture(texture) { const internalTexture = texture._texture; if (!internalTexture || !texture.isRGBD) { return; } const engine = internalTexture.getEngine(); const caps = engine.getCaps(); const isReady = internalTexture.isReady; let expandTexture = false; if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { expandTexture = true; internalTexture.type = 2; } else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { expandTexture = true; internalTexture.type = 1; } if (expandTexture) { internalTexture.isReady = false; internalTexture._isRGBD = false; internalTexture.invertY = false; } const expandRgbdTextureAsync = /* @__PURE__ */ __name(async () => { const isWebGpu = engine.isWebGPU; const shaderLanguage = isWebGpu ? 1 : 0; internalTexture.isReady = false; if (isWebGpu) { await Promise.resolve().then(() => (init_rgbdDecode_fragment(), rgbdDecode_fragment_exports)); } else { await Promise.resolve().then(() => (init_rgbdDecode_fragment2(), rgbdDecode_fragment_exports2)); } const rgbdPostProcess = new PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, 3, engine, false, void 0, internalTexture.type, void 0, null, false, void 0, shaderLanguage); rgbdPostProcess.externalTextureSamplerBinding = true; const expandedTexture = engine.createRenderTargetTexture(internalTexture.width, { generateDepthBuffer: false, generateMipMaps: false, generateStencilBuffer: false, samplingMode: internalTexture.samplingMode, type: internalTexture.type, format: 5 }); rgbdPostProcess.onEffectCreatedObservable.addOnce((e) => { e.executeWhenCompiled(() => { rgbdPostProcess.onApply = (effect) => { effect._bindTexture("textureSampler", internalTexture); effect.setFloat2("scale", 1, 1); }; texture.getScene().postProcessManager.directRender([rgbdPostProcess], expandedTexture, true); engine.restoreDefaultFramebuffer(); engine._releaseTexture(internalTexture); if (rgbdPostProcess) { rgbdPostProcess.dispose(); } expandedTexture._swapAndDie(internalTexture); internalTexture.isReady = true; }); }); }, "expandRgbdTextureAsync"); if (expandTexture) { if (isReady) { expandRgbdTextureAsync(); } else { texture.onLoadObservable.addOnce(expandRgbdTextureAsync); } } } /** * Encode the texture to RGBD if possible. * @param internalTexture the texture to encode * @param scene the scene hosting the texture * @param outputTextureType type of the texture in which the encoding is performed * @returns a promise with the internalTexture having its texture replaced by the result of the processing */ // Should have "Async" in the name but this is a breaking change. // eslint-disable-next-line no-restricted-syntax static async EncodeTextureToRGBD(internalTexture, scene, outputTextureType = 0) { if (!scene.getEngine().isWebGPU) { await Promise.resolve().then(() => (init_rgbdEncode_fragment(), rgbdEncode_fragment_exports)); } else { await Promise.resolve().then(() => (init_rgbdEncode_fragment2(), rgbdEncode_fragment_exports2)); } return await ApplyPostProcess("rgbdEncode", internalTexture, scene, outputTextureType, 1, 5); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/baseTexture.polynomial.js var init_baseTexture_polynomial = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/baseTexture.polynomial.js"() { init_cubemapToSphericalPolynomial(); init_baseTexture(); BaseTexture.prototype.forceSphericalPolynomialsRecompute = function() { if (this._texture) { this._texture._sphericalPolynomial = null; this._texture._sphericalPolynomialPromise = null; this._texture._sphericalPolynomialComputed = false; } }; Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", { get: /* @__PURE__ */ __name(function() { if (this._texture) { if (this._texture._sphericalPolynomial || this._texture._sphericalPolynomialComputed) { return this._texture._sphericalPolynomial; } if (this._texture.isReady) { if (!this._texture._sphericalPolynomialPromise) { this._texture._sphericalPolynomialPromise = CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this); if (this._texture._sphericalPolynomialPromise === null) { this._texture._sphericalPolynomialComputed = true; } else { this._texture._sphericalPolynomialPromise.then((sphericalPolynomial) => { this._texture._sphericalPolynomial = sphericalPolynomial; this._texture._sphericalPolynomialComputed = true; }); } } return null; } } return null; }, "get"), set: /* @__PURE__ */ __name(function(value) { if (this._texture) { this._texture._sphericalPolynomial = value; } }, "set"), enumerable: true, configurable: true }); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/environmentTextureTools.js function GetEnvInfo(data) { const dataView = new DataView(data.buffer, data.byteOffset, data.byteLength); let pos = 0; for (let i = 0; i < MagicBytes.length; i++) { if (dataView.getUint8(pos++) !== MagicBytes[i]) { Logger.Error("Not a babylon environment map"); return null; } } let manifestString = ""; let charCode = 0; while (charCode = dataView.getUint8(pos++)) { manifestString += String.fromCharCode(charCode); } let manifest = JSON.parse(manifestString); manifest = normalizeEnvInfo(manifest); manifest.binaryDataPosition = pos; if (manifest.specular) { manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8; } return manifest; } function normalizeEnvInfo(info) { if (info.version > CurrentVersion) { throw new Error(`Unsupported babylon environment map version "${info.version}". Latest supported version is "${CurrentVersion}".`); } if (info.version === 2) { return info; } info = { ...info, version: 2, imageType: DefaultEnvironmentTextureImageType }; return info; } async function CreateEnvTextureAsync(texture, options = {}) { const internalTexture = texture.getInternalTexture(); if (!internalTexture) { return await Promise.reject("The cube texture is invalid."); } const engine = internalTexture.getEngine(); if (texture.textureType !== 2 && texture.textureType !== 1 && texture.textureType !== 0 && texture.textureType !== 0 && texture.textureType !== 7 && texture.textureType !== -1) { return await Promise.reject("The cube texture should allow HDR (Full Float or Half Float)."); } let textureType = 1; if (!engine.getCaps().textureFloatRender) { textureType = 2; if (!engine.getCaps().textureHalfFloatRender) { return await Promise.reject("Env texture can only be created when the browser supports half float or full float rendering."); } } texture.sphericalPolynomial; const sphericalPolynomialPromise = texture.getInternalTexture()?._sphericalPolynomialPromise; const cubeWidth = internalTexture.width; const hostingScene = new Scene(engine); const specularTextures = {}; const diffuseTextures = {}; engine.flushFramebuffer(); const imageType = options.imageType ?? DefaultEnvironmentTextureImageType; const mipmapsCount = ILog2(internalTexture.width); for (let i = 0; i <= mipmapsCount; i++) { const faceWidth = Math.pow(2, mipmapsCount - i); for (let face = 0; face < 6; face++) { specularTextures[i * 6 + face] = await _GetTextureEncodedDataAsync(hostingScene, texture, textureType, face, i, faceWidth, imageType, options.imageQuality); } } const irradianceTexture = options.disableIrradianceTexture ? null : texture.irradianceTexture; if (irradianceTexture) { const faceWidth = irradianceTexture.getSize().width; for (let face = 0; face < 6; face++) { diffuseTextures[face] = await _GetTextureEncodedDataAsync(hostingScene, irradianceTexture, textureType, face, 0, faceWidth, imageType, options.imageQuality); } } hostingScene.dispose(); if (sphericalPolynomialPromise) { await sphericalPolynomialPromise; } const info = { version: CurrentVersion, width: cubeWidth, imageType, irradiance: CreateEnvTextureIrradiance(texture), specular: { mipmaps: [], lodGenerationScale: texture.lodGenerationScale } }; let position = 0; for (let i = 0; i <= mipmapsCount; i++) { for (let face = 0; face < 6; face++) { const byteLength = specularTextures[i * 6 + face].byteLength; info.specular.mipmaps.push({ length: byteLength, position }); position += byteLength; } } if (irradianceTexture) { info.irradiance = info.irradiance || { x: [0, 0, 0], xx: [0, 0, 0], y: [0, 0, 0], yy: [0, 0, 0], z: [0, 0, 0], zz: [0, 0, 0], yz: [0, 0, 0], zx: [0, 0, 0], xy: [0, 0, 0] }; info.irradiance.irradianceTexture = { size: irradianceTexture.getSize().width, faces: [], dominantDirection: irradianceTexture._dominantDirection?.asArray() }; for (let face = 0; face < 6; face++) { const byteLength = diffuseTextures[face].byteLength; info.irradiance.irradianceTexture.faces.push({ length: byteLength, position }); position += byteLength; } } const infoString = JSON.stringify(info); const infoBuffer = new ArrayBuffer(infoString.length + 1); const infoView = new Uint8Array(infoBuffer); for (let i = 0, strLen = infoString.length; i < strLen; i++) { infoView[i] = infoString.charCodeAt(i); } infoView[infoString.length] = 0; const totalSize = MagicBytes.length + position + infoBuffer.byteLength; const finalBuffer = new ArrayBuffer(totalSize); const finalBufferView = new Uint8Array(finalBuffer); const dataView = new DataView(finalBuffer); let pos = 0; for (let i = 0; i < MagicBytes.length; i++) { dataView.setUint8(pos++, MagicBytes[i]); } finalBufferView.set(new Uint8Array(infoBuffer), pos); pos += infoBuffer.byteLength; for (let i = 0; i <= mipmapsCount; i++) { for (let face = 0; face < 6; face++) { const dataBuffer = specularTextures[i * 6 + face]; finalBufferView.set(new Uint8Array(dataBuffer), pos); pos += dataBuffer.byteLength; } } if (irradianceTexture) { for (let face = 0; face < 6; face++) { const dataBuffer = diffuseTextures[face]; finalBufferView.set(new Uint8Array(dataBuffer), pos); pos += dataBuffer.byteLength; } } return finalBuffer; } async function _GetTextureEncodedDataAsync(hostingScene, texture, textureType, face, i, size, imageType, imageQuality) { let faceData = await texture.readPixels(face, i, void 0, false); if (faceData && faceData.byteLength === faceData.length) { const faceDataFloat = new Float32Array(faceData.byteLength * 4); for (let i2 = 0; i2 < faceData.byteLength; i2++) { faceDataFloat[i2] = faceData[i2] / 255; faceDataFloat[i2] = Math.pow(faceDataFloat[i2], 2.2); } faceData = faceDataFloat; } else if (faceData && texture.gammaSpace) { const floatData = faceData; for (let i2 = 0; i2 < floatData.length; i2++) { floatData[i2] = Math.pow(floatData[i2], 2.2); } } const engine = hostingScene.getEngine(); const tempTexture = engine.createRawTexture(faceData, size, size, 5, false, true, 1, null, textureType); await RGBDTextureTools.EncodeTextureToRGBD(tempTexture, hostingScene, textureType); const rgbdEncodedData = await engine._readTexturePixels(tempTexture, size, size); const imageEncodedData = await DumpDataAsync(size, size, rgbdEncodedData, imageType, void 0, false, true, imageQuality); tempTexture.dispose(); return imageEncodedData; } function CreateEnvTextureIrradiance(texture) { const polynmials = texture.sphericalPolynomial; if (polynmials == null) { return null; } return { x: [polynmials.x.x, polynmials.x.y, polynmials.x.z], y: [polynmials.y.x, polynmials.y.y, polynmials.y.z], z: [polynmials.z.x, polynmials.z.y, polynmials.z.z], xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z], yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z], zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z], yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z], zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z], xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z] }; } function CreateRadianceImageDataArrayBufferViews(data, info) { info = normalizeEnvInfo(info); const specularInfo = info.specular; let mipmapsCount = Math.log2(info.width); mipmapsCount = Math.round(mipmapsCount) + 1; if (specularInfo.mipmaps.length !== 6 * mipmapsCount) { throw new Error(`Unsupported specular mipmaps number "${specularInfo.mipmaps.length}"`); } const imageData = new Array(mipmapsCount); for (let i = 0; i < mipmapsCount; i++) { imageData[i] = new Array(6); for (let face = 0; face < 6; face++) { const imageInfo = specularInfo.mipmaps[i * 6 + face]; imageData[i][face] = new Uint8Array(data.buffer, data.byteOffset + info.binaryDataPosition + imageInfo.position, imageInfo.length); } } return imageData; } function CreateIrradianceImageDataArrayBufferViews(data, info) { info = normalizeEnvInfo(info); const imageData = new Array(6); const irradianceTexture = info.irradiance?.irradianceTexture; if (irradianceTexture) { if (irradianceTexture.faces.length !== 6) { throw new Error(`Incorrect irradiance texture faces number "${irradianceTexture.faces.length}"`); } for (let face = 0; face < 6; face++) { const imageInfo = irradianceTexture.faces[face]; imageData[face] = new Uint8Array(data.buffer, data.byteOffset + info.binaryDataPosition + imageInfo.position, imageInfo.length); } } return imageData; } function UploadEnvLevelsAsync(texture, data, info) { info = normalizeEnvInfo(info); const specularInfo = info.specular; if (!specularInfo) { return Promise.resolve([]); } texture._lodGenerationScale = specularInfo.lodGenerationScale; const promises = []; const radianceImageData = CreateRadianceImageDataArrayBufferViews(data, info); promises.push(UploadRadianceLevelsAsync(texture, radianceImageData, info.imageType)); const irradianceTexture = info.irradiance?.irradianceTexture; if (irradianceTexture) { const irradianceImageData = CreateIrradianceImageDataArrayBufferViews(data, info); let dominantDirection = null; if (info.irradiance?.irradianceTexture?.dominantDirection) { dominantDirection = Vector3.FromArray(info.irradiance.irradianceTexture.dominantDirection); } promises.push(UploadIrradianceLevelsAsync(texture, irradianceImageData, irradianceTexture.size, info.imageType, dominantDirection)); } return Promise.all(promises); } async function _OnImageReadyAsync(image, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture) { return await new Promise((resolve, reject) => { if (expandTexture) { const tempTexture = engine.createTexture(null, true, true, null, 1, null, (message) => { reject(message); }, image); rgbdPostProcess?.onEffectCreatedObservable.addOnce((effect) => { effect.executeWhenCompiled(() => { rgbdPostProcess.externalTextureSamplerBinding = true; rgbdPostProcess.onApply = (effect2) => { effect2._bindTexture("textureSampler", tempTexture); effect2.setFloat2("scale", 1, engine._features.needsInvertingBitmap && image instanceof ImageBitmap ? -1 : 1); }; if (!engine.scenes.length) { return; } engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i); engine.restoreDefaultFramebuffer(); tempTexture.dispose(); URL.revokeObjectURL(url); resolve(); }); }); } else { engine._uploadImageToTexture(texture, image, face, i); if (generateNonLODTextures) { const lodTexture = lodTextures[i]; if (lodTexture) { engine._uploadImageToTexture(lodTexture._texture, image, face, 0); } } resolve(); } }); } async function UploadRadianceLevelsAsync(texture, imageData, imageType = DefaultEnvironmentTextureImageType) { const engine = texture.getEngine(); texture.format = 5; texture.type = 0; texture.generateMipMaps = true; texture._cachedAnisotropicFilteringLevel = null; engine.updateTextureSamplingMode(3, texture); await _UploadLevelsAsync(texture, imageData, true, imageType); texture.isReady = true; } async function UploadIrradianceLevelsAsync(mainTexture, imageData, size, imageType = DefaultEnvironmentTextureImageType, dominantDirection = null) { const engine = mainTexture.getEngine(); const texture = new InternalTexture( engine, 5 /* InternalTextureSource.RenderTarget */ ); const baseTexture = new BaseTexture(engine, texture); mainTexture._irradianceTexture = baseTexture; baseTexture._dominantDirection = dominantDirection; texture.isCube = true; texture.format = 5; texture.type = 0; texture.generateMipMaps = true; texture._cachedAnisotropicFilteringLevel = null; texture.generateMipMaps = true; texture.width = size; texture.height = size; engine.updateTextureSamplingMode(3, texture); await _UploadLevelsAsync(texture, [imageData], false, imageType); engine.generateMipMapsForCubemap(texture); texture.isReady = true; } async function _UploadLevelsAsync(texture, imageData, canGenerateNonLODTextures, imageType = DefaultEnvironmentTextureImageType) { if (!Tools.IsExponentOfTwo(texture.width)) { throw new Error("Texture size must be a power of two"); } const mipmapsCount = ILog2(texture.width) + 1; const engine = texture.getEngine(); let expandTexture = false; let generateNonLODTextures = false; let rgbdPostProcess = null; let cubeRtt = null; let lodTextures = null; const caps = engine.getCaps(); if (!caps.textureLOD) { expandTexture = false; generateNonLODTextures = canGenerateNonLODTextures; } else if (!engine._features.supportRenderAndCopyToLodForFloatTextures) { expandTexture = false; } else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) { expandTexture = true; texture.type = 2; } else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) { expandTexture = true; texture.type = 1; } let shaderLanguage = 0; if (expandTexture) { if (engine.isWebGPU) { shaderLanguage = 1; await Promise.resolve().then(() => (init_rgbdDecode_fragment(), rgbdDecode_fragment_exports)); } else { await Promise.resolve().then(() => (init_rgbdDecode_fragment2(), rgbdDecode_fragment_exports2)); } rgbdPostProcess = new PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, 3, engine, false, void 0, texture.type, void 0, null, false, void 0, shaderLanguage); texture._isRGBD = false; texture.invertY = false; cubeRtt = engine.createRenderTargetCubeTexture(texture.width, { generateDepthBuffer: false, generateMipMaps: true, generateStencilBuffer: false, samplingMode: 3, type: texture.type, format: 5 }); } else { texture._isRGBD = true; texture.invertY = true; if (generateNonLODTextures) { const mipSlices = 3; lodTextures = {}; const scale = texture._lodGenerationScale; const offset = texture._lodGenerationOffset; for (let i = 0; i < mipSlices; i++) { const smoothness = i / (mipSlices - 1); const roughness = 1 - smoothness; const minLODIndex = offset; const maxLODIndex = (mipmapsCount - 1) * scale + offset; const lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness; const mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex)); const glTextureFromLod = new InternalTexture( engine, 2 /* InternalTextureSource.Temp */ ); glTextureFromLod.isCube = true; glTextureFromLod.invertY = true; glTextureFromLod.generateMipMaps = false; engine.updateTextureSamplingMode(2, glTextureFromLod); const lodTexture = new BaseTexture(null); lodTexture._isCube = true; lodTexture._texture = glTextureFromLod; lodTextures[mipmapIndex] = lodTexture; switch (i) { case 0: texture._lodTextureLow = lodTexture; break; case 1: texture._lodTextureMid = lodTexture; break; case 2: texture._lodTextureHigh = lodTexture; break; } } } } const promises = []; for (let i = 0; i < imageData.length; i++) { for (let face = 0; face < 6; face++) { const bytes = imageData[i][face]; const blob = new Blob([bytes], { type: imageType }); const url = URL.createObjectURL(blob); let promise; if (engine._features.forceBitmapOverHTMLImageElement) { promise = engine.createImageBitmap(blob, { premultiplyAlpha: "none" }).then(async (img) => { return await _OnImageReadyAsync(img, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture); }); } else { const image = new Image(); image.src = url; promise = new Promise((resolve, reject) => { image.onload = () => { _OnImageReadyAsync(image, engine, expandTexture, rgbdPostProcess, url, face, i, generateNonLODTextures, lodTextures, cubeRtt, texture).then(() => resolve()).catch((reason) => { reject(reason); }); }; image.onerror = (error) => { reject(error); }; }); } promises.push(promise); } } await Promise.all(promises); if (imageData.length < mipmapsCount) { let data; const size = Math.pow(2, mipmapsCount - 1 - imageData.length); const dataLength = size * size * 4; switch (texture.type) { case 0: { data = new Uint8Array(dataLength); break; } case 2: { data = new Uint16Array(dataLength); break; } case 1: { data = new Float32Array(dataLength); break; } } for (let i = imageData.length; i < mipmapsCount; i++) { for (let face = 0; face < 6; face++) { engine._uploadArrayBufferViewToTexture(cubeRtt?.texture || texture, data, face, i); } } } if (cubeRtt) { const irradiance = texture._irradianceTexture; texture._irradianceTexture = null; engine._releaseTexture(texture); cubeRtt._swapAndDie(texture); texture._irradianceTexture = irradiance; } if (rgbdPostProcess) { rgbdPostProcess.dispose(); } if (generateNonLODTextures) { if (texture._lodTextureHigh && texture._lodTextureHigh._texture) { texture._lodTextureHigh._texture.isReady = true; } if (texture._lodTextureMid && texture._lodTextureMid._texture) { texture._lodTextureMid._texture.isReady = true; } if (texture._lodTextureLow && texture._lodTextureLow._texture) { texture._lodTextureLow._texture.isReady = true; } } } function UploadEnvSpherical(texture, info) { info = normalizeEnvInfo(info); const irradianceInfo = info.irradiance; if (!irradianceInfo) { return; } const sp = new SphericalPolynomial(); Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x); Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y); Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z); Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx); Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy); Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz); Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz); Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx); Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy); texture._sphericalPolynomial = sp; } function _UpdateRGBDAsync(internalTexture, data, sphericalPolynomial, lodScale, lodOffset) { const proxy = internalTexture.getEngine().createRawCubeTexture(null, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression); const proxyPromise = UploadRadianceLevelsAsync(proxy, data).then(() => internalTexture); internalTexture.onRebuildCallback = (_internalTexture) => { return { proxy: proxyPromise, isReady: true, isAsync: true }; }; internalTexture._source = 13; internalTexture._bufferViewArrayArray = data; internalTexture._lodGenerationScale = lodScale; internalTexture._lodGenerationOffset = lodOffset; internalTexture._sphericalPolynomial = sphericalPolynomial; return UploadRadianceLevelsAsync(internalTexture, data).then(() => { internalTexture.isReady = true; return internalTexture; }); } var DefaultEnvironmentTextureImageType, CurrentVersion, MagicBytes, EnvironmentTextureTools; var init_environmentTextureTools = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/environmentTextureTools.js"() { init_tools(); init_math_vector(); init_math_scalar_functions(); init_sphericalPolynomial(); init_internalTexture(); init_baseTexture(); init_scene(); init_postProcess(); init_logger(); init_rgbdTextureTools(); init_dumpTools(); init_baseTexture_polynomial(); DefaultEnvironmentTextureImageType = "image/png"; CurrentVersion = 2; MagicBytes = [134, 22, 135, 150, 246, 214, 150, 54]; __name(GetEnvInfo, "GetEnvInfo"); __name(normalizeEnvInfo, "normalizeEnvInfo"); __name(CreateEnvTextureAsync, "CreateEnvTextureAsync"); __name(_GetTextureEncodedDataAsync, "_GetTextureEncodedDataAsync"); __name(CreateEnvTextureIrradiance, "CreateEnvTextureIrradiance"); __name(CreateRadianceImageDataArrayBufferViews, "CreateRadianceImageDataArrayBufferViews"); __name(CreateIrradianceImageDataArrayBufferViews, "CreateIrradianceImageDataArrayBufferViews"); __name(UploadEnvLevelsAsync, "UploadEnvLevelsAsync"); __name(_OnImageReadyAsync, "_OnImageReadyAsync"); __name(UploadRadianceLevelsAsync, "UploadRadianceLevelsAsync"); __name(UploadIrradianceLevelsAsync, "UploadIrradianceLevelsAsync"); __name(_UploadLevelsAsync, "_UploadLevelsAsync"); __name(UploadEnvSpherical, "UploadEnvSpherical"); __name(_UpdateRGBDAsync, "_UpdateRGBDAsync"); EnvironmentTextureTools = { /** * Gets the environment info from an env file. * @param data The array buffer containing the .env bytes. * @returns the environment file info (the json header) if successfully parsed, normalized to the latest supported version. */ GetEnvInfo, /** * Creates an environment texture from a loaded cube texture. * @param texture defines the cube texture to convert in env file * @param options options for the conversion process * @param options.imageType the mime type for the encoded images, with support for "image/png" (default) and "image/webp" * @param options.imageQuality the image quality of encoded WebP images. * @returns a promise containing the environment data if successful. */ CreateEnvTextureAsync, /** * Creates the ArrayBufferViews used for initializing environment texture image data. * @param data the image data * @param info parameters that determine what views will be created for accessing the underlying buffer * @returns the views described by info providing access to the underlying buffer */ CreateRadianceImageDataArrayBufferViews, /** * Creates the ArrayBufferViews used for initializing environment texture image data. * @param data the image data * @param info parameters that determine what views will be created for accessing the underlying buffer * @returns the views described by info providing access to the underlying buffer */ CreateIrradianceImageDataArrayBufferViews, /** * Uploads the texture info contained in the env file to the GPU. * @param texture defines the internal texture to upload to * @param data defines the data to load * @param info defines the texture info retrieved through the GetEnvInfo method * @returns a promise */ UploadEnvLevelsAsync, /** * Uploads the levels of image data to the GPU. * @param texture defines the internal texture to upload to * @param imageData defines the array buffer views of image data [mipmap][face] * @param imageType the mime type of the image data * @returns a promise */ UploadRadianceLevelsAsync, /** * Uploads the levels of image data to the GPU. * @param texture defines the internal texture to upload to * @param imageData defines the array buffer views of image data [mipmap][face] * @param imageType the mime type of the image data * @param dominantDirection the dominant direction of light in the environment texture, if available * @returns a promise */ UploadIrradianceLevelsAsync, /** * Uploads spherical polynomials information to the texture. * @param texture defines the texture we are trying to upload the information to * @param info defines the environment texture info retrieved through the GetEnvInfo method */ UploadEnvSpherical }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/envTextureLoader.js var envTextureLoader_exports = {}; __export(envTextureLoader_exports, { _ENVTextureLoader: () => _ENVTextureLoader }); var _ENVTextureLoader; var init_envTextureLoader = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/envTextureLoader.js"() { init_environmentTextureTools(); _ENVTextureLoader = class { static { __name(this, "_ENVTextureLoader"); } constructor() { this.supportCascades = false; } /** * 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 */ loadCubeData(data, texture, createPolynomials, onLoad, onError) { if (Array.isArray(data)) { return; } const info = GetEnvInfo(data); if (info) { texture.width = info.width; texture.height = info.width; try { UploadEnvSpherical(texture, info); UploadEnvLevelsAsync(texture, data, info).then(() => { texture.isReady = true; texture.onLoadedObservable.notifyObservers(texture); texture.onLoadedObservable.clear(); if (onLoad) { onLoad(); } }, (reason) => { onError?.("Can not upload environment levels", reason); }); } catch (e) { onError?.("Can not upload environment file", e); } } 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. */ loadData() { throw ".env not supported in 2d."; } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/HighDynamicRange/panoramaToCubemap.js var PanoramaToCubeMapTools; var init_panoramaToCubemap = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/HighDynamicRange/panoramaToCubemap.js"() { init_math_vector(); PanoramaToCubeMapTools = class { static { __name(this, "PanoramaToCubeMapTools"); } /** * Converts a panorama stored in RGB right to left up to down format into a cubemap (6 faces). * * @param float32Array The source data. * @param inputWidth The width of the input panorama. * @param inputHeight The height of the input panorama. * @param size The willing size of the generated cubemap (each faces will be size * size pixels) * @param supersample enable supersampling the cubemap * @param invertY defines if the Y axis must be inverted * @returns The cubemap data */ static ConvertPanoramaToCubemap(float32Array, inputWidth, inputHeight, size, supersample = false, invertY = true) { if (!float32Array) { throw "ConvertPanoramaToCubemap: input cannot be null"; } let stride = 0; if (float32Array.length != inputWidth * inputHeight * 3) { if (float32Array.length != inputWidth * inputHeight * 4) { throw "ConvertPanoramaToCubemap: input size is wrong"; } else { stride = 4; } } else { stride = 3; } const textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight, supersample, invertY, stride); const textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight, supersample, invertY, stride); const textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight, supersample, invertY, stride); const textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight, supersample, invertY, stride); const textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight, supersample, invertY, stride); const textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight, supersample, invertY, stride); return { front: textureFront, back: textureBack, left: textureLeft, right: textureRight, up: textureUp, down: textureDown, size, type: 1, format: 4, gammaSpace: false }; } static CreateCubemapTexture(texSize, faceData, float32Array, inputWidth, inputHeight, supersample, invertY, stride) { const buffer = new ArrayBuffer(texSize * texSize * 4 * 3); const textureArray = new Float32Array(buffer); const samples = supersample ? Math.max(1, Math.round(inputWidth / 4 / texSize)) : 1; const sampleFactor = 1 / samples; const sampleFactorSqr = sampleFactor * sampleFactor; const rotDX1 = faceData[1].subtract(faceData[0]).scale(sampleFactor / texSize); const rotDX2 = faceData[3].subtract(faceData[2]).scale(sampleFactor / texSize); const dy = 1 / texSize; let fy = 0; for (let y = 0; y < texSize; y++) { for (let sy = 0; sy < samples; sy++) { let xv1 = faceData[0]; let xv2 = faceData[2]; for (let x = 0; x < texSize; x++) { for (let sx = 0; sx < samples; sx++) { const v = xv2.subtract(xv1).scale(fy).add(xv1); v.normalize(); const color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight, stride, invertY); textureArray[y * texSize * 3 + x * 3 + 0] += color.r * sampleFactorSqr; textureArray[y * texSize * 3 + x * 3 + 1] += color.g * sampleFactorSqr; textureArray[y * texSize * 3 + x * 3 + 2] += color.b * sampleFactorSqr; xv1 = xv1.add(rotDX1); xv2 = xv2.add(rotDX2); } } fy += dy * sampleFactor; } } return textureArray; } static CalcProjectionSpherical(vDir, float32Array, inputWidth, inputHeight, stride, invertY) { let theta = Math.atan2(vDir.z, vDir.x); const phi = Math.acos(vDir.y); while (theta < -Math.PI) { theta += 2 * Math.PI; } while (theta > Math.PI) { theta -= 2 * Math.PI; } let dx = theta / Math.PI; const dy = phi / Math.PI; dx = dx * 0.5 + 0.5; let px = Math.round(dx * inputWidth); if (px < 0) { px = 0; } else if (px >= inputWidth) { px = inputWidth - 1; } let py = Math.round(dy * inputHeight); if (py < 0) { py = 0; } else if (py >= inputHeight) { py = inputHeight - 1; } const inputY = invertY ? inputHeight - py - 1 : py; const r = float32Array[inputY * inputWidth * stride + px * stride + 0]; const g = float32Array[inputY * inputWidth * stride + px * stride + 1]; const b = float32Array[inputY * inputWidth * stride + px * stride + 2]; return { r, g, b }; } }; PanoramaToCubeMapTools.FACE_LEFT = [new Vector3(-1, -1, -1), new Vector3(1, -1, -1), new Vector3(-1, 1, -1), new Vector3(1, 1, -1)]; PanoramaToCubeMapTools.FACE_RIGHT = [new Vector3(1, -1, 1), new Vector3(-1, -1, 1), new Vector3(1, 1, 1), new Vector3(-1, 1, 1)]; PanoramaToCubeMapTools.FACE_FRONT = [new Vector3(1, -1, -1), new Vector3(1, -1, 1), new Vector3(1, 1, -1), new Vector3(1, 1, 1)]; PanoramaToCubeMapTools.FACE_BACK = [new Vector3(-1, -1, 1), new Vector3(-1, -1, -1), new Vector3(-1, 1, 1), new Vector3(-1, 1, -1)]; PanoramaToCubeMapTools.FACE_DOWN = [new Vector3(1, 1, -1), new Vector3(1, 1, 1), new Vector3(-1, 1, -1), new Vector3(-1, 1, 1)]; PanoramaToCubeMapTools.FACE_UP = [new Vector3(-1, -1, -1), new Vector3(-1, -1, 1), new Vector3(1, -1, -1), new Vector3(1, -1, 1)]; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/HighDynamicRange/hdr.js function Ldexp(mantissa, exponent) { if (exponent > 1023) { return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023); } if (exponent < -1074) { return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074); } return mantissa * Math.pow(2, exponent); } function Rgbe2float(float32array, red, green, blue, exponent, index) { if (exponent > 0) { exponent = Ldexp(1, exponent - (128 + 8)); float32array[index + 0] = red * exponent; float32array[index + 1] = green * exponent; float32array[index + 2] = blue * exponent; } else { float32array[index + 0] = 0; float32array[index + 1] = 0; float32array[index + 2] = 0; } } function ReadStringLine(uint8array, startIndex) { let line = ""; let character = ""; for (let i = startIndex; i < uint8array.length - startIndex; i++) { character = String.fromCharCode(uint8array[i]); if (character == "\n") { break; } line += character; } return line; } function RGBE_ReadHeader(uint8array) { let height = 0; let width = 0; let line = ReadStringLine(uint8array, 0); if (line[0] != "#" || line[1] != "?") { throw "Bad HDR Format."; } let endOfHeader = false; let findFormat = false; let lineIndex = 0; do { lineIndex += line.length + 1; line = ReadStringLine(uint8array, lineIndex); if (line == "FORMAT=32-bit_rle_rgbe") { findFormat = true; } else if (line.length == 0) { endOfHeader = true; } } while (!endOfHeader); if (!findFormat) { throw "HDR Bad header format, unsupported FORMAT"; } lineIndex += line.length + 1; line = ReadStringLine(uint8array, lineIndex); const sizeRegexp = /^-Y (.*) \+X (.*)$/g; const match = sizeRegexp.exec(line); if (!match || match.length < 3) { throw "HDR Bad header format, no size"; } width = parseInt(match[2]); height = parseInt(match[1]); if (width < 8 || width > 32767) { throw "HDR Bad header format, unsupported size"; } lineIndex += line.length + 1; return { height, width, dataPosition: lineIndex }; } function GetCubeMapTextureData(buffer, size, supersample = false) { const uint8array = new Uint8Array(buffer); const hdrInfo = RGBE_ReadHeader(uint8array); const data = RGBE_ReadPixels(uint8array, hdrInfo); const cubeMapData = PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size, supersample); return cubeMapData; } function RGBE_ReadPixels(uint8array, hdrInfo) { return ReadRGBEPixelsRLE(uint8array, hdrInfo); } function ReadRGBEPixelsRLE(uint8array, hdrInfo) { let numScanlines = hdrInfo.height; const scanlineWidth = hdrInfo.width; let a, b, c, d, count; let dataIndex = hdrInfo.dataPosition; let index = 0, endIndex = 0, i = 0; const scanLineArrayBuffer = new ArrayBuffer(scanlineWidth * 4); const scanLineArray = new Uint8Array(scanLineArrayBuffer); const resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3); const resultArray = new Float32Array(resultBuffer); while (numScanlines > 0) { a = uint8array[dataIndex++]; b = uint8array[dataIndex++]; c = uint8array[dataIndex++]; d = uint8array[dataIndex++]; if (a != 2 || b != 2 || c & 128 || hdrInfo.width < 8 || hdrInfo.width > 32767) { return ReadRGBEPixelsNotRLE(uint8array, hdrInfo); } if ((c << 8 | d) != scanlineWidth) { throw "HDR Bad header format, wrong scan line width"; } index = 0; for (i = 0; i < 4; i++) { endIndex = (i + 1) * scanlineWidth; while (index < endIndex) { a = uint8array[dataIndex++]; b = uint8array[dataIndex++]; if (a > 128) { count = a - 128; if (count == 0 || count > endIndex - index) { throw "HDR Bad Format, bad scanline data (run)"; } while (count-- > 0) { scanLineArray[index++] = b; } } else { count = a; if (count == 0 || count > endIndex - index) { throw "HDR Bad Format, bad scanline data (non-run)"; } scanLineArray[index++] = b; if (--count > 0) { for (let j = 0; j < count; j++) { scanLineArray[index++] = uint8array[dataIndex++]; } } } } } for (i = 0; i < scanlineWidth; i++) { a = scanLineArray[i]; b = scanLineArray[i + scanlineWidth]; c = scanLineArray[i + 2 * scanlineWidth]; d = scanLineArray[i + 3 * scanlineWidth]; Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - numScanlines) * scanlineWidth * 3 + i * 3); } numScanlines--; } return resultArray; } function ReadRGBEPixelsNotRLE(uint8array, hdrInfo) { let numScanlines = hdrInfo.height; const scanlineWidth = hdrInfo.width; let a, b, c, d, i; let dataIndex = hdrInfo.dataPosition; const resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3); const resultArray = new Float32Array(resultBuffer); while (numScanlines > 0) { for (i = 0; i < hdrInfo.width; i++) { a = uint8array[dataIndex++]; b = uint8array[dataIndex++]; c = uint8array[dataIndex++]; d = uint8array[dataIndex++]; Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - numScanlines) * scanlineWidth * 3 + i * 3); } numScanlines--; } return resultArray; } var HDRTools; var init_hdr = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/HighDynamicRange/hdr.js"() { init_panoramaToCubemap(); __name(Ldexp, "Ldexp"); __name(Rgbe2float, "Rgbe2float"); __name(ReadStringLine, "ReadStringLine"); __name(RGBE_ReadHeader, "RGBE_ReadHeader"); __name(GetCubeMapTextureData, "GetCubeMapTextureData"); __name(RGBE_ReadPixels, "RGBE_ReadPixels"); __name(ReadRGBEPixelsRLE, "ReadRGBEPixelsRLE"); __name(ReadRGBEPixelsNotRLE, "ReadRGBEPixelsNotRLE"); HDRTools = { // eslint-disable-next-line @typescript-eslint/naming-convention RGBE_ReadHeader, // eslint-disable-next-line @typescript-eslint/naming-convention GetCubeMapTextureData, // eslint-disable-next-line @typescript-eslint/naming-convention RGBE_ReadPixels }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/hdrTextureLoader.js var hdrTextureLoader_exports = {}; __export(hdrTextureLoader_exports, { _HDRTextureLoader: () => _HDRTextureLoader }); var _HDRTextureLoader; var init_hdrTextureLoader = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/hdrTextureLoader.js"() { init_hdr(); _HDRTextureLoader = class { static { __name(this, "_HDRTextureLoader"); } constructor() { this.supportCascades = false; } /** * Uploads the cube texture data to the WebGL texture. It has already been bound. * Cube texture are not supported by .hdr files */ loadCubeData() { throw ".hdr 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 */ loadData(data, texture, callback) { const uint8array = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); const hdrInfo = RGBE_ReadHeader(uint8array); const pixelsDataRGB32 = RGBE_ReadPixels(uint8array, hdrInfo); const pixels = hdrInfo.width * hdrInfo.height; const pixelsDataRGBA32 = new Float32Array(pixels * 4); for (let i = 0; i < pixels; i += 1) { pixelsDataRGBA32[i * 4] = pixelsDataRGB32[i * 3]; pixelsDataRGBA32[i * 4 + 1] = pixelsDataRGB32[i * 3 + 1]; pixelsDataRGBA32[i * 4 + 2] = pixelsDataRGB32[i * 3 + 2]; pixelsDataRGBA32[i * 4 + 3] = 1; } callback(hdrInfo.width, hdrInfo.height, texture.generateMipMaps, false, () => { const engine = texture.getEngine(); texture.type = 1; texture.format = 5; texture._gammaSpace = false; engine._uploadDataToTextureDirectly(texture, pixelsDataRGBA32); }); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/khronosTextureContainer.js var KhronosTextureContainer; var init_khronosTextureContainer = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/khronosTextureContainer.js"() { init_logger(); KhronosTextureContainer = class _KhronosTextureContainer { static { __name(this, "KhronosTextureContainer"); } /** * Creates a new KhronosTextureContainer * @param data contents of the KTX container file * @param facesExpected should be either 1 or 6, based whether a cube texture or or */ constructor(data, facesExpected) { this.data = data; this.isInvalid = false; if (!_KhronosTextureContainer.IsValid(data)) { this.isInvalid = true; Logger.Error("texture missing KTX identifier"); return; } const dataSize = Uint32Array.BYTES_PER_ELEMENT; const headerDataView = new DataView(this.data.buffer, this.data.byteOffset + 12, 13 * dataSize); const endianness = headerDataView.getUint32(0, true); const littleEndian = endianness === 67305985; this.glType = headerDataView.getUint32(1 * dataSize, littleEndian); this.glTypeSize = headerDataView.getUint32(2 * dataSize, littleEndian); this.glFormat = headerDataView.getUint32(3 * dataSize, littleEndian); this.glInternalFormat = headerDataView.getUint32(4 * dataSize, littleEndian); this.glBaseInternalFormat = headerDataView.getUint32(5 * dataSize, littleEndian); this.pixelWidth = headerDataView.getUint32(6 * dataSize, littleEndian); this.pixelHeight = headerDataView.getUint32(7 * dataSize, littleEndian); this.pixelDepth = headerDataView.getUint32(8 * dataSize, littleEndian); this.numberOfArrayElements = headerDataView.getUint32(9 * dataSize, littleEndian); this.numberOfFaces = headerDataView.getUint32(10 * dataSize, littleEndian); this.numberOfMipmapLevels = headerDataView.getUint32(11 * dataSize, littleEndian); this.bytesOfKeyValueData = headerDataView.getUint32(12 * dataSize, littleEndian); if (this.glType !== 0) { Logger.Error("only compressed formats currently supported"); this.isInvalid = true; return; } else { this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels); } if (this.pixelHeight === 0 || this.pixelDepth !== 0) { Logger.Error("only 2D textures currently supported"); this.isInvalid = true; return; } if (this.numberOfArrayElements !== 0) { Logger.Error("texture arrays not currently supported"); this.isInvalid = true; return; } if (this.numberOfFaces !== facesExpected) { Logger.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces); this.isInvalid = true; return; } this.loadType = _KhronosTextureContainer.COMPRESSED_2D; } /** * Uploads KTX content to a Babylon Texture. * It is assumed that the texture has already been created & is currently bound * @internal */ uploadLevels(texture, loadMipmaps) { switch (this.loadType) { case _KhronosTextureContainer.COMPRESSED_2D: this._upload2DCompressedLevels(texture, loadMipmaps); break; case _KhronosTextureContainer.TEX_2D: case _KhronosTextureContainer.COMPRESSED_3D: case _KhronosTextureContainer.TEX_3D: } } _upload2DCompressedLevels(texture, loadMipmaps) { let dataOffset = _KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData; let width = this.pixelWidth; let height = this.pixelHeight; const mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1; for (let level = 0; level < mipmapCount; level++) { const imageSize = new Int32Array(this.data.buffer, this.data.byteOffset + dataOffset, 1)[0]; dataOffset += 4; for (let face = 0; face < this.numberOfFaces; face++) { const byteArray = new Uint8Array(this.data.buffer, this.data.byteOffset + dataOffset, imageSize); const engine = texture.getEngine(); engine._uploadCompressedDataToTextureDirectly(texture, texture.format, width, height, byteArray, face, level); dataOffset += imageSize; dataOffset += 3 - (imageSize + 3) % 4; } width = Math.max(1, width * 0.5); height = Math.max(1, height * 0.5); } } /** * Checks if the given data starts with a KTX file identifier. * @param data the data to check * @returns true if the data is a KTX file or false otherwise */ static IsValid(data) { if (data.byteLength >= 12) { const identifier = new Uint8Array(data.buffer, data.byteOffset, 12); if (identifier[0] === 171 && identifier[1] === 75 && identifier[2] === 84 && identifier[3] === 88 && identifier[4] === 32 && identifier[5] === 49 && identifier[6] === 49 && identifier[7] === 187 && identifier[8] === 13 && identifier[9] === 10 && identifier[10] === 26 && identifier[11] === 10) { return true; } } return false; } }; KhronosTextureContainer.HEADER_LEN = 12 + 13 * 4; KhronosTextureContainer.COMPRESSED_2D = 0; KhronosTextureContainer.COMPRESSED_3D = 1; KhronosTextureContainer.TEX_2D = 2; KhronosTextureContainer.TEX_3D = 3; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/workerPool.js var WorkerPool, AutoReleaseWorkerPool; var init_workerPool = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/workerPool.js"() { WorkerPool = class { static { __name(this, "WorkerPool"); } /** * Constructor * @param workers Array of workers to use for actions */ constructor(workers) { this._pendingActions = new Array(); this._workerInfos = workers.map((worker) => ({ workerPromise: Promise.resolve(worker), idle: true })); } /** * Terminates all workers and clears any pending actions. */ dispose() { for (const workerInfo of this._workerInfos) { workerInfo.workerPromise.then((worker) => { worker.terminate(); }); } this._workerInfos.length = 0; this._pendingActions.length = 0; } /** * Pushes an action to the worker pool. If all the workers are active, the action will be * pended until a worker has completed its action. * @param action The action to perform. Call onComplete when the action is complete. */ push(action) { if (!this._executeOnIdleWorker(action)) { this._pendingActions.push(action); } } _executeOnIdleWorker(action) { for (const workerInfo of this._workerInfos) { if (workerInfo.idle) { this._execute(workerInfo, action); return true; } } return false; } _execute(workerInfo, action) { workerInfo.idle = false; workerInfo.workerPromise.then((worker) => { action(worker, () => { const nextAction = this._pendingActions.shift(); if (nextAction) { this._execute(workerInfo, nextAction); } else { workerInfo.idle = true; } }); }); } }; AutoReleaseWorkerPool = class _AutoReleaseWorkerPool extends WorkerPool { static { __name(this, "AutoReleaseWorkerPool"); } constructor(maxWorkers, createWorkerAsync, options = _AutoReleaseWorkerPool.DefaultOptions) { super([]); this._maxWorkers = maxWorkers; this._createWorkerAsync = createWorkerAsync; this._options = options; } push(action) { if (!this._executeOnIdleWorker(action)) { if (this._workerInfos.length < this._maxWorkers) { const workerInfo = { workerPromise: this._createWorkerAsync(), idle: false }; this._workerInfos.push(workerInfo); this._execute(workerInfo, action); } else { this._pendingActions.push(action); } } } _execute(workerInfo, action) { if (workerInfo.timeoutId) { clearTimeout(workerInfo.timeoutId); delete workerInfo.timeoutId; } super._execute(workerInfo, (worker, onComplete) => { action(worker, () => { onComplete(); if (workerInfo.idle) { workerInfo.timeoutId = setTimeout(() => { workerInfo.workerPromise.then((worker2) => { worker2.terminate(); }); const indexOf = this._workerInfos.indexOf(workerInfo); if (indexOf !== -1) { this._workerInfos.splice(indexOf, 1); } }, this._options.idleTimeElapsedBeforeRelease); } }); }); } }; AutoReleaseWorkerPool.DefaultOptions = { idleTimeElapsedBeforeRelease: 1e3 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/ktx2decoderTypes.js var SourceTextureFormat, TranscodeTarget, EngineFormat; var init_ktx2decoderTypes = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/ktx2decoderTypes.js"() { (function(SourceTextureFormat2) { SourceTextureFormat2[SourceTextureFormat2["ETC1S"] = 0] = "ETC1S"; SourceTextureFormat2[SourceTextureFormat2["UASTC4x4"] = 1] = "UASTC4x4"; })(SourceTextureFormat || (SourceTextureFormat = {})); (function(TranscodeTarget2) { TranscodeTarget2[TranscodeTarget2["ASTC_4X4_RGBA"] = 0] = "ASTC_4X4_RGBA"; TranscodeTarget2[TranscodeTarget2["ASTC_4x4_RGBA"] = 0] = "ASTC_4x4_RGBA"; TranscodeTarget2[TranscodeTarget2["BC7_RGBA"] = 1] = "BC7_RGBA"; TranscodeTarget2[TranscodeTarget2["BC3_RGBA"] = 2] = "BC3_RGBA"; TranscodeTarget2[TranscodeTarget2["BC1_RGB"] = 3] = "BC1_RGB"; TranscodeTarget2[TranscodeTarget2["PVRTC1_4_RGBA"] = 4] = "PVRTC1_4_RGBA"; TranscodeTarget2[TranscodeTarget2["PVRTC1_4_RGB"] = 5] = "PVRTC1_4_RGB"; TranscodeTarget2[TranscodeTarget2["ETC2_RGBA"] = 6] = "ETC2_RGBA"; TranscodeTarget2[TranscodeTarget2["ETC1_RGB"] = 7] = "ETC1_RGB"; TranscodeTarget2[TranscodeTarget2["RGBA32"] = 8] = "RGBA32"; TranscodeTarget2[TranscodeTarget2["R8"] = 9] = "R8"; TranscodeTarget2[TranscodeTarget2["RG8"] = 10] = "RG8"; })(TranscodeTarget || (TranscodeTarget = {})); (function(EngineFormat2) { EngineFormat2[EngineFormat2["COMPRESSED_RGBA_BPTC_UNORM_EXT"] = 36492] = "COMPRESSED_RGBA_BPTC_UNORM_EXT"; EngineFormat2[EngineFormat2["COMPRESSED_RGBA_ASTC_4X4_KHR"] = 37808] = "COMPRESSED_RGBA_ASTC_4X4_KHR"; EngineFormat2[EngineFormat2["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT"; EngineFormat2[EngineFormat2["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT"; EngineFormat2[EngineFormat2["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"; EngineFormat2[EngineFormat2["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG"; EngineFormat2[EngineFormat2["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC"; EngineFormat2[EngineFormat2["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2"; EngineFormat2[EngineFormat2["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL"; EngineFormat2[EngineFormat2["RGBA8Format"] = 32856] = "RGBA8Format"; EngineFormat2[EngineFormat2["R8Format"] = 33321] = "R8Format"; EngineFormat2[EngineFormat2["RG8Format"] = 33323] = "RG8Format"; })(EngineFormat || (EngineFormat = {})); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/khronosTextureContainer2Worker.js function applyConfig(urls, binariesAndModulesContainer) { const KTX2DecoderModule = binariesAndModulesContainer?.jsDecoderModule || KTX2DECODER; if (urls) { if (urls.wasmBaseUrl) { KTX2DecoderModule.Transcoder.WasmBaseUrl = urls.wasmBaseUrl; } if (urls.wasmUASTCToASTC) { KTX2DecoderModule.LiteTranscoder_UASTC_ASTC.WasmModuleURL = urls.wasmUASTCToASTC; } if (urls.wasmUASTCToBC7) { KTX2DecoderModule.LiteTranscoder_UASTC_BC7.WasmModuleURL = urls.wasmUASTCToBC7; } if (urls.wasmUASTCToRGBA_UNORM) { KTX2DecoderModule.LiteTranscoder_UASTC_RGBA_UNORM.WasmModuleURL = urls.wasmUASTCToRGBA_UNORM; } if (urls.wasmUASTCToRGBA_SRGB) { KTX2DecoderModule.LiteTranscoder_UASTC_RGBA_SRGB.WasmModuleURL = urls.wasmUASTCToRGBA_SRGB; } if (urls.wasmUASTCToR8_UNORM) { KTX2DecoderModule.LiteTranscoder_UASTC_R8_UNORM.WasmModuleURL = urls.wasmUASTCToR8_UNORM; } if (urls.wasmUASTCToRG8_UNORM) { KTX2DecoderModule.LiteTranscoder_UASTC_RG8_UNORM.WasmModuleURL = urls.wasmUASTCToRG8_UNORM; } if (urls.jsMSCTranscoder) { KTX2DecoderModule.MSCTranscoder.JSModuleURL = urls.jsMSCTranscoder; } if (urls.wasmMSCTranscoder) { KTX2DecoderModule.MSCTranscoder.WasmModuleURL = urls.wasmMSCTranscoder; } if (urls.wasmZSTDDecoder) { KTX2DecoderModule.ZSTDDecoder.WasmModuleURL = urls.wasmZSTDDecoder; } } if (binariesAndModulesContainer) { if (binariesAndModulesContainer.wasmUASTCToASTC) { KTX2DecoderModule.LiteTranscoder_UASTC_ASTC.WasmBinary = binariesAndModulesContainer.wasmUASTCToASTC; } if (binariesAndModulesContainer.wasmUASTCToBC7) { KTX2DecoderModule.LiteTranscoder_UASTC_BC7.WasmBinary = binariesAndModulesContainer.wasmUASTCToBC7; } if (binariesAndModulesContainer.wasmUASTCToRGBA_UNORM) { KTX2DecoderModule.LiteTranscoder_UASTC_RGBA_UNORM.WasmBinary = binariesAndModulesContainer.wasmUASTCToRGBA_UNORM; } if (binariesAndModulesContainer.wasmUASTCToRGBA_SRGB) { KTX2DecoderModule.LiteTranscoder_UASTC_RGBA_SRGB.WasmBinary = binariesAndModulesContainer.wasmUASTCToRGBA_SRGB; } if (binariesAndModulesContainer.wasmUASTCToR8_UNORM) { KTX2DecoderModule.LiteTranscoder_UASTC_R8_UNORM.WasmBinary = binariesAndModulesContainer.wasmUASTCToR8_UNORM; } if (binariesAndModulesContainer.wasmUASTCToRG8_UNORM) { KTX2DecoderModule.LiteTranscoder_UASTC_RG8_UNORM.WasmBinary = binariesAndModulesContainer.wasmUASTCToRG8_UNORM; } if (binariesAndModulesContainer.jsMSCTranscoder) { KTX2DecoderModule.MSCTranscoder.JSModule = binariesAndModulesContainer.jsMSCTranscoder; } if (binariesAndModulesContainer.wasmMSCTranscoder) { KTX2DecoderModule.MSCTranscoder.WasmBinary = binariesAndModulesContainer.wasmMSCTranscoder; } if (binariesAndModulesContainer.wasmZSTDDecoder) { KTX2DecoderModule.ZSTDDecoder.WasmBinary = binariesAndModulesContainer.wasmZSTDDecoder; } } } function workerFunction2(KTX2DecoderModule) { if (typeof KTX2DecoderModule === "undefined" && typeof KTX2DECODER !== "undefined") { KTX2DecoderModule = KTX2DECODER; } let ktx2Decoder; onmessage = /* @__PURE__ */ __name((event) => { if (!event.data) { return; } switch (event.data.action) { case "init": { const urls = event.data.urls; if (urls) { if (urls.jsDecoderModule && typeof KTX2DecoderModule === "undefined") { importScripts(urls.jsDecoderModule); KTX2DecoderModule = KTX2DECODER; } applyConfig(urls); } if (event.data.wasmBinaries) { applyConfig(void 0, { ...event.data.wasmBinaries, jsDecoderModule: KTX2DecoderModule }); } ktx2Decoder = new KTX2DecoderModule.KTX2Decoder(); postMessage({ action: "init" }); break; } case "setDefaultDecoderOptions": { KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions = event.data.options; break; } case "decode": ktx2Decoder.decode(event.data.data, event.data.caps, event.data.options).then((data) => { const buffers = []; for (let mip = 0; mip < data.mipmaps.length; ++mip) { const mipmap = data.mipmaps[mip]; if (mipmap && mipmap.data) { buffers.push(mipmap.data.buffer); } } postMessage({ action: "decoded", success: true, decodedData: data }, buffers); }).catch((reason) => { postMessage({ action: "decoded", success: false, msg: reason }); }); break; } }, "onmessage"); } async function initializeWebWorker2(worker, wasmBinaries, urls) { return await new Promise((resolve, reject) => { const onError = /* @__PURE__ */ __name((error) => { worker.removeEventListener("error", onError); worker.removeEventListener("message", onMessage); reject(error); }, "onError"); const onMessage = /* @__PURE__ */ __name((message) => { if (message.data.action === "init") { worker.removeEventListener("error", onError); worker.removeEventListener("message", onMessage); resolve(worker); } }, "onMessage"); worker.addEventListener("error", onError); worker.addEventListener("message", onMessage); worker.postMessage({ action: "init", urls, wasmBinaries }); }); } var init_khronosTextureContainer2Worker = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/khronosTextureContainer2Worker.js"() { __name(applyConfig, "applyConfig"); __name(workerFunction2, "workerFunction"); __name(initializeWebWorker2, "initializeWebWorker"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/khronosTextureContainer2.js var DefaultKTX2DecoderOptions, KhronosTextureContainer2; var init_khronosTextureContainer2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/khronosTextureContainer2.js"() { init_workerPool(); init_tools(); init_ktx2decoderTypes(); init_khronosTextureContainer2Worker(); DefaultKTX2DecoderOptions = class { static { __name(this, "DefaultKTX2DecoderOptions"); } constructor() { this._isDirty = true; this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC = true; this._ktx2DecoderOptions = {}; } /** * Gets the dirty flag */ get isDirty() { return this._isDirty; } /** * force a (uncompressed) RGBA transcoded format if transcoding a UASTC source format and ASTC + BC7 are not available as a compressed transcoded format */ get useRGBAIfASTCBC7NotAvailableWhenUASTC() { return this._useRGBAIfASTCBC7NotAvailableWhenUASTC; } set useRGBAIfASTCBC7NotAvailableWhenUASTC(value) { if (this._useRGBAIfASTCBC7NotAvailableWhenUASTC === value) { return; } this._useRGBAIfASTCBC7NotAvailableWhenUASTC = value; this._isDirty = true; } /** * force a (uncompressed) RGBA transcoded format if transcoding a UASTC source format and only BC1 or BC3 are available as a compressed transcoded format. * This property is true by default to favor speed over memory, because currently transcoding from UASTC to BC1/3 is slow because the transcoder transcodes * to uncompressed and then recompresses the texture */ get useRGBAIfOnlyBC1BC3AvailableWhenUASTC() { return this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC; } set useRGBAIfOnlyBC1BC3AvailableWhenUASTC(value) { if (this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC === value) { return; } this._useRGBAIfOnlyBC1BC3AvailableWhenUASTC = value; this._isDirty = true; } /** * force to always use (uncompressed) RGBA for transcoded format */ get forceRGBA() { return this._forceRGBA; } set forceRGBA(value) { if (this._forceRGBA === value) { return; } this._forceRGBA = value; this._isDirty = true; } /** * force to always use (uncompressed) R8 for transcoded format */ get forceR8() { return this._forceR8; } set forceR8(value) { if (this._forceR8 === value) { return; } this._forceR8 = value; this._isDirty = true; } /** * force to always use (uncompressed) RG8 for transcoded format */ get forceRG8() { return this._forceRG8; } set forceRG8(value) { if (this._forceRG8 === value) { return; } this._forceRG8 = value; this._isDirty = true; } /** * list of transcoders to bypass when looking for a suitable transcoder. The available transcoders are: * UniversalTranscoder_UASTC_ASTC * UniversalTranscoder_UASTC_BC7 * UniversalTranscoder_UASTC_RGBA_UNORM * UniversalTranscoder_UASTC_RGBA_SRGB * UniversalTranscoder_UASTC_R8_UNORM * UniversalTranscoder_UASTC_RG8_UNORM * MSCTranscoder */ get bypassTranscoders() { return this._bypassTranscoders; } set bypassTranscoders(value) { if (this._bypassTranscoders === value) { return; } this._bypassTranscoders = value; this._isDirty = true; } /** @internal */ _getKTX2DecoderOptions() { if (!this._isDirty) { return this._ktx2DecoderOptions; } this._isDirty = false; const options = {}; if (this._useRGBAIfASTCBC7NotAvailableWhenUASTC !== void 0) { options.useRGBAIfASTCBC7NotAvailableWhenUASTC = this._useRGBAIfASTCBC7NotAvailableWhenUASTC; } if (this._forceRGBA !== void 0) { options.forceRGBA = this._forceRGBA; } if (this._forceR8 !== void 0) { options.forceR8 = this._forceR8; } if (this._forceRG8 !== void 0) { options.forceRG8 = this._forceRG8; } if (this._bypassTranscoders !== void 0) { options.bypassTranscoders = this._bypassTranscoders; } if (this.useRGBAIfOnlyBC1BC3AvailableWhenUASTC) { options.transcodeFormatDecisionTree = { UASTC: { transcodeFormat: [TranscodeTarget.BC1_RGB, TranscodeTarget.BC3_RGBA], yes: { transcodeFormat: TranscodeTarget.RGBA32, engineFormat: 32856, roundToMultiple4: false } } }; } this._ktx2DecoderOptions = options; return options; } }; KhronosTextureContainer2 = class _KhronosTextureContainer2 { static { __name(this, "KhronosTextureContainer2"); } static GetDefaultNumWorkers() { if (typeof navigator !== "object" || !navigator.hardwareConcurrency) { return 1; } return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4); } static _Initialize(numWorkers) { if (_KhronosTextureContainer2._WorkerPoolPromise || _KhronosTextureContainer2._DecoderModulePromise) { return; } const urls = { wasmBaseUrl: Tools.ScriptBaseUrl, jsDecoderModule: Tools.GetBabylonScriptURL(this.URLConfig.jsDecoderModule, true), wasmUASTCToASTC: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToASTC, true), wasmUASTCToBC7: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToBC7, true), wasmUASTCToRGBA_UNORM: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_UNORM, true), wasmUASTCToRGBA_SRGB: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRGBA_SRGB, true), wasmUASTCToR8_UNORM: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToR8_UNORM, true), wasmUASTCToRG8_UNORM: Tools.GetBabylonScriptURL(this.URLConfig.wasmUASTCToRG8_UNORM, true), jsMSCTranscoder: Tools.GetBabylonScriptURL(this.URLConfig.jsMSCTranscoder, true), wasmMSCTranscoder: Tools.GetBabylonScriptURL(this.URLConfig.wasmMSCTranscoder, true), wasmZSTDDecoder: Tools.GetBabylonScriptURL(this.URLConfig.wasmZSTDDecoder, true) }; if (numWorkers && typeof Worker === "function" && typeof URL !== "undefined") { _KhronosTextureContainer2._WorkerPoolPromise = new Promise((resolve) => { const workerContent = `${applyConfig}(${workerFunction2})()`; const workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: "application/javascript" })); resolve(new AutoReleaseWorkerPool(numWorkers, async () => await initializeWebWorker2(new Worker(workerBlobUrl), void 0, urls))); }); } else { if (typeof _KhronosTextureContainer2._KTX2DecoderModule === "undefined") { _KhronosTextureContainer2._DecoderModulePromise = Tools.LoadBabylonScriptAsync(urls.jsDecoderModule).then(() => { _KhronosTextureContainer2._KTX2DecoderModule = KTX2DECODER; _KhronosTextureContainer2._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread = false; _KhronosTextureContainer2._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread = true; applyConfig(urls, _KhronosTextureContainer2._KTX2DecoderModule); return new _KhronosTextureContainer2._KTX2DecoderModule.KTX2Decoder(); }); } else { _KhronosTextureContainer2._KTX2DecoderModule.MSCTranscoder.UseFromWorkerThread = false; _KhronosTextureContainer2._KTX2DecoderModule.WASMMemoryManager.LoadBinariesFromCurrentThread = true; _KhronosTextureContainer2._DecoderModulePromise = Promise.resolve(new _KhronosTextureContainer2._KTX2DecoderModule.KTX2Decoder()); } } } /** * Constructor * @param engine The engine to use * @param numWorkersOrOptions The number of workers for async operations. Specify `0` to disable web workers and run synchronously in the current context. */ constructor(engine, numWorkersOrOptions = _KhronosTextureContainer2.DefaultNumWorkers) { this._engine = engine; const workerPoolOption = typeof numWorkersOrOptions === "object" && numWorkersOrOptions.workerPool || _KhronosTextureContainer2.WorkerPool; if (workerPoolOption) { _KhronosTextureContainer2._WorkerPoolPromise = Promise.resolve(workerPoolOption); } else { if (typeof numWorkersOrOptions === "object") { _KhronosTextureContainer2._KTX2DecoderModule = numWorkersOrOptions?.binariesAndModulesContainer?.jsDecoderModule; } else if (typeof KTX2DECODER !== "undefined") { _KhronosTextureContainer2._KTX2DecoderModule = KTX2DECODER; } const numberOfWorkers = typeof numWorkersOrOptions === "number" ? numWorkersOrOptions : numWorkersOrOptions.numWorkers ?? _KhronosTextureContainer2.DefaultNumWorkers; _KhronosTextureContainer2._Initialize(numberOfWorkers); } } /** * @internal */ async _uploadAsync(data, internalTexture, options) { const caps = this._engine.getCaps(); const compressedTexturesCaps = { astc: !!caps.astc, bptc: !!caps.bptc, s3tc: !!caps.s3tc, pvrtc: !!caps.pvrtc, etc2: !!caps.etc2, etc1: !!caps.etc1 }; if (_KhronosTextureContainer2._WorkerPoolPromise) { const workerPool = await _KhronosTextureContainer2._WorkerPoolPromise; return await new Promise((resolve, reject) => { workerPool.push((worker, onComplete) => { const onError = /* @__PURE__ */ __name((error) => { worker.removeEventListener("error", onError); worker.removeEventListener("message", onMessage); reject(error); onComplete(); }, "onError"); const onMessage = /* @__PURE__ */ __name((message) => { if (message.data.action === "decoded") { worker.removeEventListener("error", onError); worker.removeEventListener("message", onMessage); if (!message.data.success) { reject({ message: message.data.msg }); } else { try { this._createTexture(message.data.decodedData, internalTexture, options); resolve(); } catch (err) { reject({ message: err }); } } onComplete(); } }, "onMessage"); worker.addEventListener("error", onError); worker.addEventListener("message", onMessage); worker.postMessage({ action: "setDefaultDecoderOptions", options: _KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions() }); const dataCopy = new Uint8Array(data.byteLength); dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); worker.postMessage({ action: "decode", data: dataCopy, caps: compressedTexturesCaps, options }, [dataCopy.buffer]); }); }); } else if (_KhronosTextureContainer2._DecoderModulePromise) { const decoder = await _KhronosTextureContainer2._DecoderModulePromise; if (_KhronosTextureContainer2.DefaultDecoderOptions.isDirty) { _KhronosTextureContainer2._KTX2DecoderModule.KTX2Decoder.DefaultDecoderOptions = _KhronosTextureContainer2.DefaultDecoderOptions._getKTX2DecoderOptions(); } return await new Promise((resolve, reject) => { decoder.decode(data, caps).then((data2) => { this._createTexture(data2, internalTexture); resolve(); }).catch((reason) => { reject({ message: reason }); }); }); } throw new Error("KTX2 decoder module is not available"); } _createTexture(data, internalTexture, options) { const oglTexture2D = 3553; this._engine._bindTextureDirectly(oglTexture2D, internalTexture); if (options) { options.transcodedFormat = data.transcodedFormat; options.isInGammaSpace = data.isInGammaSpace; options.hasAlpha = data.hasAlpha; options.transcoderName = data.transcoderName; } let isUncompressedFormat = true; switch (data.transcodedFormat) { case 32856: internalTexture.type = 0; internalTexture.format = 5; break; case 33321: internalTexture.type = 0; internalTexture.format = 6; break; case 33323: internalTexture.type = 0; internalTexture.format = 7; break; default: internalTexture.format = data.transcodedFormat; isUncompressedFormat = false; break; } internalTexture._gammaSpace = data.isInGammaSpace; internalTexture.generateMipMaps = data.mipmaps.length > 1; internalTexture.width = data.mipmaps[0].width; internalTexture.height = data.mipmaps[0].height; if (data.errors) { throw new Error("KTX2 container - could not transcode the data. " + data.errors); } for (let t = 0; t < data.mipmaps.length; ++t) { const mipmap = data.mipmaps[t]; if (!mipmap || !mipmap.data) { throw new Error("KTX2 container - could not transcode one of the image"); } if (isUncompressedFormat) { internalTexture.width = mipmap.width; internalTexture.height = mipmap.height; this._engine._uploadDataToTextureDirectly(internalTexture, mipmap.data, 0, t, void 0, true); } else { this._engine._uploadCompressedDataToTextureDirectly(internalTexture, data.transcodedFormat, mipmap.width, mipmap.height, mipmap.data, 0, t); } } internalTexture._extension = ".ktx2"; internalTexture.isReady = true; this._engine._bindTextureDirectly(oglTexture2D, null); } /** * Checks if the given data starts with a KTX2 file identifier. * @param data the data to check * @returns true if the data is a KTX2 file or false otherwise */ static IsValid(data) { if (data.byteLength >= 12) { const identifier = new Uint8Array(data.buffer, data.byteOffset, 12); if (identifier[0] === 171 && identifier[1] === 75 && identifier[2] === 84 && identifier[3] === 88 && identifier[4] === 32 && identifier[5] === 50 && identifier[6] === 48 && identifier[7] === 187 && identifier[8] === 13 && identifier[9] === 10 && identifier[10] === 26 && identifier[11] === 10) { return true; } } return false; } }; KhronosTextureContainer2.URLConfig = { jsDecoderModule: "https://cdn.babylonjs.com/babylon.ktx2Decoder.js", wasmUASTCToASTC: null, wasmUASTCToBC7: null, wasmUASTCToRGBA_UNORM: null, wasmUASTCToRGBA_SRGB: null, wasmUASTCToR8_UNORM: null, wasmUASTCToRG8_UNORM: null, jsMSCTranscoder: null, wasmMSCTranscoder: null, wasmZSTDDecoder: null }; KhronosTextureContainer2.DefaultNumWorkers = KhronosTextureContainer2.GetDefaultNumWorkers(); KhronosTextureContainer2.DefaultDecoderOptions = new DefaultKTX2DecoderOptions(); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader.js var ktxTextureLoader_exports = {}; __export(ktxTextureLoader_exports, { _KTXTextureLoader: () => _KTXTextureLoader }); function MapSRGBToLinear(format) { switch (format) { case 35916: return 33776; case 35918: return 33778; case 35919: return 33779; case 37493: return 37492; case 37497: return 37496; case 37495: return 37494; case 37840: return 37808; case 36493: return 36492; } return null; } var _KTXTextureLoader; var init_ktxTextureLoader = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/ktxTextureLoader.js"() { init_khronosTextureContainer(); init_khronosTextureContainer2(); init_logger(); __name(MapSRGBToLinear, "MapSRGBToLinear"); _KTXTextureLoader = class { static { __name(this, "_KTXTextureLoader"); } constructor() { this.supportCascades = false; } /** * 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 */ loadCubeData(data, texture, createPolynomials, onLoad) { if (Array.isArray(data)) { return; } texture._invertVScale = !texture.invertY; const engine = texture.getEngine(); const ktx = new KhronosTextureContainer(data, 6); const loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps; engine._unpackFlipY(true); ktx.uploadLevels(texture, texture.generateMipMaps); texture.width = ktx.pixelWidth; texture.height = ktx.pixelHeight; engine._setCubeMapTextureParams(texture, loadMipmap, ktx.numberOfMipmapLevels - 1); 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 * @param options */ loadData(data, texture, callback, options) { if (KhronosTextureContainer.IsValid(data)) { texture._invertVScale = !texture.invertY; const ktx = new KhronosTextureContainer(data, 1); const mappedFormat = MapSRGBToLinear(ktx.glInternalFormat); if (mappedFormat) { texture.format = mappedFormat; texture._useSRGBBuffer = texture.getEngine()._getUseSRGBBuffer(true, texture.generateMipMaps); texture._gammaSpace = true; } else { texture.format = ktx.glInternalFormat; } callback(ktx.pixelWidth, ktx.pixelHeight, texture.generateMipMaps, true, () => { ktx.uploadLevels(texture, texture.generateMipMaps); }, ktx.isInvalid); } else if (KhronosTextureContainer2.IsValid(data)) { const ktx2 = new KhronosTextureContainer2(texture.getEngine()); ktx2._uploadAsync(data, texture, options).then(() => { callback(texture.width, texture.height, texture.generateMipMaps, true, () => { }, false); }, (error) => { Logger.Warn(`Failed to load KTX2 texture data: ${error.message}`); callback(0, 0, false, false, () => { }, true); }); } else { Logger.Error("texture missing KTX identifier"); callback(0, 0, false, false, () => { }, true); } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tga.js function GetTGAHeader(data) { let offset = 0; const header = { id_length: data[offset++], colormap_type: data[offset++], image_type: data[offset++], colormap_index: data[offset++] | data[offset++] << 8, colormap_length: data[offset++] | data[offset++] << 8, colormap_size: data[offset++], origin: [data[offset++] | data[offset++] << 8, data[offset++] | data[offset++] << 8], width: data[offset++] | data[offset++] << 8, height: data[offset++] | data[offset++] << 8, pixel_size: data[offset++], flags: data[offset++] }; return header; } function UploadContent(texture, data) { if (data.length < 19) { Logger.Error("Unable to load TGA file - Not enough data to contain header"); return; } let offset = 18; const header = GetTGAHeader(data); if (header.id_length + offset > data.length) { Logger.Error("Unable to load TGA file - Not enough data"); return; } offset += header.id_length; let use_rle = false; let use_pal = false; let use_grey = false; switch (header.image_type) { case _TYPE_RLE_INDEXED: use_rle = true; // eslint-disable-next-line no-fallthrough case _TYPE_INDEXED: use_pal = true; break; case _TYPE_RLE_RGB: use_rle = true; // eslint-disable-next-line no-fallthrough case _TYPE_RGB: break; case _TYPE_RLE_GREY: use_rle = true; // eslint-disable-next-line no-fallthrough case _TYPE_GREY: use_grey = true; break; } let pixel_data; const pixel_size = header.pixel_size >> 3; const pixel_total = header.width * header.height * pixel_size; let palettes; if (use_pal) { palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3)); } if (use_rle) { pixel_data = new Uint8Array(pixel_total); let c, count, i; let localOffset = 0; const pixels = new Uint8Array(pixel_size); while (offset < pixel_total && localOffset < pixel_total) { c = data[offset++]; count = (c & 127) + 1; if (c & 128) { for (i = 0; i < pixel_size; ++i) { pixels[i] = data[offset++]; } for (i = 0; i < count; ++i) { pixel_data.set(pixels, localOffset + i * pixel_size); } localOffset += pixel_size * count; } else { count *= pixel_size; for (i = 0; i < count; ++i) { pixel_data[localOffset + i] = data[offset++]; } localOffset += count; } } } else { pixel_data = data.subarray(offset, offset += use_pal ? header.width * header.height : pixel_total); } let x_start, y_start, x_step, y_step, y_end, x_end; switch ((header.flags & _ORIGIN_MASK) >> _ORIGIN_SHIFT) { default: case _ORIGIN_UL: x_start = 0; x_step = 1; x_end = header.width; y_start = 0; y_step = 1; y_end = header.height; break; case _ORIGIN_BL: x_start = 0; x_step = 1; x_end = header.width; y_start = header.height - 1; y_step = -1; y_end = -1; break; case _ORIGIN_UR: x_start = header.width - 1; x_step = -1; x_end = -1; y_start = 0; y_step = 1; y_end = header.height; break; case _ORIGIN_BR: x_start = header.width - 1; x_step = -1; x_end = -1; y_start = header.height - 1; y_step = -1; y_end = -1; break; } const func = "_getImageData" + (use_grey ? "Grey" : "") + header.pixel_size + "bits"; const imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end); const engine = texture.getEngine(); engine._uploadDataToTextureDirectly(texture, imageData); } function GetImageData8bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { const image = pixel_data, colormap = palettes; const width = header.width, height = header.height; let color, i = 0, x, y; const imageData = new Uint8Array(width * height * 4); for (y = y_start; y !== y_end; y += y_step) { for (x = x_start; x !== x_end; x += x_step, i++) { color = image[i]; imageData[(x + width * y) * 4 + 3] = 255; imageData[(x + width * y) * 4 + 2] = colormap[color * 3 + 0]; imageData[(x + width * y) * 4 + 1] = colormap[color * 3 + 1]; imageData[(x + width * y) * 4 + 0] = colormap[color * 3 + 2]; } } return imageData; } function GetImageData16bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { const image = pixel_data; const width = header.width, height = header.height; let color, i = 0, x, y; const imageData = new Uint8Array(width * height * 4); for (y = y_start; y !== y_end; y += y_step) { for (x = x_start; x !== x_end; x += x_step, i += 2) { color = image[i + 0] + (image[i + 1] << 8); const r = ((color & 31744) >> 10) * 255 / 31 | 0; const g = ((color & 992) >> 5) * 255 / 31 | 0; const b = (color & 31) * 255 / 31 | 0; imageData[(x + width * y) * 4 + 0] = r; imageData[(x + width * y) * 4 + 1] = g; imageData[(x + width * y) * 4 + 2] = b; imageData[(x + width * y) * 4 + 3] = color & 32768 ? 0 : 255; } } return imageData; } function GetImageData24bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { const image = pixel_data; const width = header.width, height = header.height; let i = 0, x, y; const imageData = new Uint8Array(width * height * 4); for (y = y_start; y !== y_end; y += y_step) { for (x = x_start; x !== x_end; x += x_step, i += 3) { imageData[(x + width * y) * 4 + 3] = 255; imageData[(x + width * y) * 4 + 2] = image[i + 0]; imageData[(x + width * y) * 4 + 1] = image[i + 1]; imageData[(x + width * y) * 4 + 0] = image[i + 2]; } } return imageData; } function GetImageData32bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { const image = pixel_data; const width = header.width, height = header.height; let i = 0, x, y; const imageData = new Uint8Array(width * height * 4); for (y = y_start; y !== y_end; y += y_step) { for (x = x_start; x !== x_end; x += x_step, i += 4) { imageData[(x + width * y) * 4 + 2] = image[i + 0]; imageData[(x + width * y) * 4 + 1] = image[i + 1]; imageData[(x + width * y) * 4 + 0] = image[i + 2]; imageData[(x + width * y) * 4 + 3] = image[i + 3]; } } return imageData; } function GetImageDataGrey8bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { const image = pixel_data; const width = header.width, height = header.height; let color, i = 0, x, y; const imageData = new Uint8Array(width * height * 4); for (y = y_start; y !== y_end; y += y_step) { for (x = x_start; x !== x_end; x += x_step, i++) { color = image[i]; imageData[(x + width * y) * 4 + 0] = color; imageData[(x + width * y) * 4 + 1] = color; imageData[(x + width * y) * 4 + 2] = color; imageData[(x + width * y) * 4 + 3] = 255; } } return imageData; } function GetImageDataGrey16bits(header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) { const image = pixel_data; const width = header.width, height = header.height; let i = 0, x, y; const imageData = new Uint8Array(width * height * 4); for (y = y_start; y !== y_end; y += y_step) { for (x = x_start; x !== x_end; x += x_step, i += 2) { imageData[(x + width * y) * 4 + 0] = image[i + 0]; imageData[(x + width * y) * 4 + 1] = image[i + 0]; imageData[(x + width * y) * 4 + 2] = image[i + 0]; imageData[(x + width * y) * 4 + 3] = image[i + 1]; } } return imageData; } var _TYPE_INDEXED, _TYPE_RGB, _TYPE_GREY, _TYPE_RLE_INDEXED, _TYPE_RLE_RGB, _TYPE_RLE_GREY, _ORIGIN_MASK, _ORIGIN_SHIFT, _ORIGIN_BL, _ORIGIN_BR, _ORIGIN_UL, _ORIGIN_UR, TGATools; var init_tga = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tga.js"() { init_logger(); _TYPE_INDEXED = 1; _TYPE_RGB = 2; _TYPE_GREY = 3; _TYPE_RLE_INDEXED = 9; _TYPE_RLE_RGB = 10; _TYPE_RLE_GREY = 11; _ORIGIN_MASK = 48; _ORIGIN_SHIFT = 4; _ORIGIN_BL = 0; _ORIGIN_BR = 1; _ORIGIN_UL = 2; _ORIGIN_UR = 3; __name(GetTGAHeader, "GetTGAHeader"); __name(UploadContent, "UploadContent"); __name(GetImageData8bits, "GetImageData8bits"); __name(GetImageData16bits, "GetImageData16bits"); __name(GetImageData24bits, "GetImageData24bits"); __name(GetImageData32bits, "GetImageData32bits"); __name(GetImageDataGrey8bits, "GetImageDataGrey8bits"); __name(GetImageDataGrey16bits, "GetImageDataGrey16bits"); TGATools = { /** * Gets the header of a TGA file * @param data defines the TGA data * @returns the header */ GetTGAHeader, /** * Uploads TGA content to a Babylon Texture * @internal */ UploadContent, /** @internal */ _getImageData8bits: GetImageData8bits, /** @internal */ _getImageData16bits: GetImageData16bits, /** @internal */ _getImageData24bits: GetImageData24bits, /** @internal */ _getImageData32bits: GetImageData32bits, /** @internal */ _getImageDataGrey8bits: GetImageDataGrey8bits, /** @internal */ _getImageDataGrey16bits: GetImageDataGrey16bits }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/tgaTextureLoader.js var tgaTextureLoader_exports = {}; __export(tgaTextureLoader_exports, { _TGATextureLoader: () => _TGATextureLoader }); var _TGATextureLoader; var init_tgaTextureLoader = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/tgaTextureLoader.js"() { init_tga(); _TGATextureLoader = class { static { __name(this, "_TGATextureLoader"); } constructor() { this.supportCascades = false; } /** * Uploads the cube texture data to the WebGL texture. It has already been bound. */ loadCubeData() { 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 */ loadData(data, texture, callback) { const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength); const header = GetTGAHeader(bytes); callback(header.width, header.height, texture.generateMipMaps, false, () => { UploadContent(texture, bytes); }); } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.interfaces.js var INT32_SIZE, FLOAT32_SIZE, INT8_SIZE, INT16_SIZE, ULONG_SIZE, USHORT_RANGE, BITMAP_SIZE, HUF_ENCBITS, HUF_DECBITS, HUF_ENCSIZE, HUF_DECSIZE, HUF_DECMASK, SHORT_ZEROCODE_RUN, LONG_ZEROCODE_RUN, SHORTEST_LONG_RUN; var init_exrLoader_interfaces = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.interfaces.js"() { INT32_SIZE = 4; FLOAT32_SIZE = 4; INT8_SIZE = 1; INT16_SIZE = 2; ULONG_SIZE = 8; USHORT_RANGE = 1 << 16; BITMAP_SIZE = USHORT_RANGE >> 3; HUF_ENCBITS = 16; HUF_DECBITS = 14; HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; HUF_DECSIZE = 1 << HUF_DECBITS; HUF_DECMASK = HUF_DECSIZE - 1; SHORT_ZEROCODE_RUN = 59; LONG_ZEROCODE_RUN = 63; SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.core.js function GenerateTables() { const buffer = new ArrayBuffer(4); const floatView2 = new Float32Array(buffer); const uint32View = new Uint32Array(buffer); const baseTable = new Uint32Array(512); const shiftTable = new Uint32Array(512); for (let i = 0; i < 256; ++i) { const e = i - 127; if (e < -27) { baseTable[i] = 0; baseTable[i | 256] = 32768; shiftTable[i] = 24; shiftTable[i | 256] = 24; } else if (e < -14) { baseTable[i] = 1024 >> -e - 14; baseTable[i | 256] = 1024 >> -e - 14 | 32768; shiftTable[i] = -e - 1; shiftTable[i | 256] = -e - 1; } else if (e <= 15) { baseTable[i] = e + 15 << 10; baseTable[i | 256] = e + 15 << 10 | 32768; shiftTable[i] = 13; shiftTable[i | 256] = 13; } else if (e < 128) { baseTable[i] = 31744; baseTable[i | 256] = 64512; shiftTable[i] = 24; shiftTable[i | 256] = 24; } else { baseTable[i] = 31744; baseTable[i | 256] = 64512; shiftTable[i] = 13; shiftTable[i | 256] = 13; } } const mantissaTable = new Uint32Array(2048); const exponentTable = new Uint32Array(64); const offsetTable = new Uint32Array(64); for (let i = 1; i < 1024; ++i) { let m = i << 13; let e = 0; while ((m & 8388608) === 0) { m <<= 1; e -= 8388608; } m &= ~8388608; e += 947912704; mantissaTable[i] = m | e; } for (let i = 1024; i < 2048; ++i) { mantissaTable[i] = 939524096 + (i - 1024 << 13); } for (let i = 1; i < 31; ++i) { exponentTable[i] = i << 23; } exponentTable[31] = 1199570944; exponentTable[32] = 2147483648; for (let i = 33; i < 63; ++i) { exponentTable[i] = 2147483648 + (i - 32 << 23); } exponentTable[63] = 3347054592; for (let i = 1; i < 64; ++i) { if (i !== 32) { offsetTable[i] = 1024; } } return { floatView: floatView2, uint32View, baseTable, shiftTable, mantissaTable, exponentTable, offsetTable }; } function ParseNullTerminatedString(buffer, offset) { const uintBuffer = new Uint8Array(buffer); let endOffset = 0; while (uintBuffer[offset.value + endOffset] != 0) { endOffset += 1; } const stringValue = new TextDecoder().decode(uintBuffer.slice(offset.value, offset.value + endOffset)); offset.value = offset.value + endOffset + 1; return stringValue; } function ParseInt32(dataView, offset) { const value = dataView.getInt32(offset.value, true); offset.value += INT32_SIZE; return value; } function ParseUint32(dataView, offset) { const value = dataView.getUint32(offset.value, true); offset.value += INT32_SIZE; return value; } function ParseUint8(dataView, offset) { const value = dataView.getUint8(offset.value); offset.value += INT8_SIZE; return value; } function ParseUint16(dataView, offset) { const value = dataView.getUint16(offset.value, true); offset.value += INT16_SIZE; return value; } function ParseUint8Array(array, offset) { const value = array[offset.value]; offset.value += INT8_SIZE; return value; } function ParseInt64(dataView, offset) { let int; if ("getBigInt64" in DataView.prototype) { int = Number(dataView.getBigInt64(offset.value, true)); } else { int = dataView.getUint32(offset.value + 4, true) + Number(dataView.getUint32(offset.value, true) << 32); } offset.value += ULONG_SIZE; return int; } function ParseFloat32(dataView, offset) { const value = dataView.getFloat32(offset.value, true); offset.value += FLOAT32_SIZE; return value; } function ParseFloat16(dataView, offset) { return DecodeFloat16(ParseUint16(dataView, offset)); } function DecodeFloat16(binary) { const exponent = (binary & 31744) >> 10; const fraction = binary & 1023; return (binary >> 15 ? -1 : 1) * (exponent ? exponent === 31 ? fraction ? NaN : Infinity : Math.pow(2, exponent - 15) * (1 + fraction / 1024) : 6103515625e-14 * (fraction / 1024)); } function ToHalfFloat2(value) { if (Math.abs(value) > 65504) { throw new Error("Value out of range.Consider using float instead of half-float."); } value = Clamp(value, -65504, 65504); Tables.floatView[0] = value; const f = Tables.uint32View[0]; const e = f >> 23 & 511; return Tables.baseTable[e] + ((f & 8388607) >> Tables.shiftTable[e]); } function DecodeFloat32(dataView, offset) { return ToHalfFloat2(ParseFloat32(dataView, offset)); } function ParseFixedLengthString(buffer, offset, size) { const stringValue = new TextDecoder().decode(new Uint8Array(buffer).slice(offset.value, offset.value + size)); offset.value = offset.value + size; return stringValue; } function ParseRational(dataView, offset) { const x = ParseInt32(dataView, offset); const y = ParseUint32(dataView, offset); return [x, y]; } function ParseTimecode(dataView, offset) { const x = ParseUint32(dataView, offset); const y = ParseUint32(dataView, offset); return [x, y]; } function ParseV2f(dataView, offset) { const x = ParseFloat32(dataView, offset); const y = ParseFloat32(dataView, offset); return [x, y]; } function ParseV3f(dataView, offset) { const x = ParseFloat32(dataView, offset); const y = ParseFloat32(dataView, offset); const z = ParseFloat32(dataView, offset); return [x, y, z]; } function ParseChlist(dataView, offset, size) { const startOffset = offset.value; const channels = []; while (offset.value < startOffset + size - 1) { const name260 = ParseNullTerminatedString(dataView.buffer, offset); const pixelType = ParseInt32(dataView, offset); const pLinear = ParseUint8(dataView, offset); offset.value += 3; const xSampling = ParseInt32(dataView, offset); const ySampling = ParseInt32(dataView, offset); channels.push({ name: name260, pixelType, pLinear, xSampling, ySampling }); } offset.value += 1; return channels; } function ParseChromaticities(dataView, offset) { const redX = ParseFloat32(dataView, offset); const redY = ParseFloat32(dataView, offset); const greenX = ParseFloat32(dataView, offset); const greenY = ParseFloat32(dataView, offset); const blueX = ParseFloat32(dataView, offset); const blueY = ParseFloat32(dataView, offset); const whiteX = ParseFloat32(dataView, offset); const whiteY = ParseFloat32(dataView, offset); return { redX, redY, greenX, greenY, blueX, blueY, whiteX, whiteY }; } function ParseCompression(dataView, offset) { return ParseUint8(dataView, offset); } function ParseBox2i(dataView, offset) { const xMin = ParseInt32(dataView, offset); const yMin = ParseInt32(dataView, offset); const xMax = ParseInt32(dataView, offset); const yMax = ParseInt32(dataView, offset); return { xMin, yMin, xMax, yMax }; } function ParseLineOrder(dataView, offset) { const lineOrder = ParseUint8(dataView, offset); return LineOrders[lineOrder]; } function ParseValue(dataView, offset, type, size) { switch (type) { case "string": case "stringvector": case "iccProfile": return ParseFixedLengthString(dataView.buffer, offset, size); case "chlist": return ParseChlist(dataView, offset, size); case "chromaticities": return ParseChromaticities(dataView, offset); case "compression": return ParseCompression(dataView, offset); case "box2i": return ParseBox2i(dataView, offset); case "lineOrder": return ParseLineOrder(dataView, offset); case "float": return ParseFloat32(dataView, offset); case "v2f": return ParseV2f(dataView, offset); case "v3f": return ParseV3f(dataView, offset); case "int": return ParseInt32(dataView, offset); case "rational": return ParseRational(dataView, offset); case "timecode": return ParseTimecode(dataView, offset); case "preview": offset.value += size; return "skipped"; default: offset.value += size; return void 0; } } function Predictor(source) { for (let t = 1; t < source.length; t++) { const d = source[t - 1] + source[t] - 128; source[t] = d; } } function InterleaveScalar(source, out) { let t1 = 0; let t2 = Math.floor((source.length + 1) / 2); let s = 0; const stop = source.length - 1; while (true) { if (s > stop) { break; } out[s++] = source[t1++]; if (s > stop) { break; } out[s++] = source[t2++]; } } var CompressionCodes, LineOrders, Tables; var init_exrLoader_core = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.core.js"() { init_math_scalar_functions(); init_exrLoader_interfaces(); (function(CompressionCodes2) { CompressionCodes2[CompressionCodes2["NO_COMPRESSION"] = 0] = "NO_COMPRESSION"; CompressionCodes2[CompressionCodes2["RLE_COMPRESSION"] = 1] = "RLE_COMPRESSION"; CompressionCodes2[CompressionCodes2["ZIPS_COMPRESSION"] = 2] = "ZIPS_COMPRESSION"; CompressionCodes2[CompressionCodes2["ZIP_COMPRESSION"] = 3] = "ZIP_COMPRESSION"; CompressionCodes2[CompressionCodes2["PIZ_COMPRESSION"] = 4] = "PIZ_COMPRESSION"; CompressionCodes2[CompressionCodes2["PXR24_COMPRESSION"] = 5] = "PXR24_COMPRESSION"; })(CompressionCodes || (CompressionCodes = {})); (function(LineOrders2) { LineOrders2[LineOrders2["INCREASING_Y"] = 0] = "INCREASING_Y"; LineOrders2[LineOrders2["DECREASING_Y"] = 1] = "DECREASING_Y"; })(LineOrders || (LineOrders = {})); Tables = GenerateTables(); __name(GenerateTables, "GenerateTables"); __name(ParseNullTerminatedString, "ParseNullTerminatedString"); __name(ParseInt32, "ParseInt32"); __name(ParseUint32, "ParseUint32"); __name(ParseUint8, "ParseUint8"); __name(ParseUint16, "ParseUint16"); __name(ParseUint8Array, "ParseUint8Array"); __name(ParseInt64, "ParseInt64"); __name(ParseFloat32, "ParseFloat32"); __name(ParseFloat16, "ParseFloat16"); __name(DecodeFloat16, "DecodeFloat16"); __name(ToHalfFloat2, "ToHalfFloat"); __name(DecodeFloat32, "DecodeFloat32"); __name(ParseFixedLengthString, "ParseFixedLengthString"); __name(ParseRational, "ParseRational"); __name(ParseTimecode, "ParseTimecode"); __name(ParseV2f, "ParseV2f"); __name(ParseV3f, "ParseV3f"); __name(ParseChlist, "ParseChlist"); __name(ParseChromaticities, "ParseChromaticities"); __name(ParseCompression, "ParseCompression"); __name(ParseBox2i, "ParseBox2i"); __name(ParseLineOrder, "ParseLineOrder"); __name(ParseValue, "ParseValue"); __name(Predictor, "Predictor"); __name(InterleaveScalar, "InterleaveScalar"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.header.js function GetExrHeader(dataView, offset) { if (dataView.getUint32(0, true) != EXR_MAGIC) { throw new Error("Incorrect OpenEXR format"); } const version = dataView.getUint8(4); const specData = dataView.getUint8(5); const spec = { singleTile: !!(specData & 2), longName: !!(specData & 4), deepFormat: !!(specData & 8), multiPart: !!(specData & 16) }; offset.value = 8; const headerData = {}; let keepReading = true; while (keepReading) { const attributeName = ParseNullTerminatedString(dataView.buffer, offset); if (!attributeName) { keepReading = false; } else { const attributeType = ParseNullTerminatedString(dataView.buffer, offset); const attributeSize = ParseUint32(dataView, offset); const attributeValue = ParseValue(dataView, offset, attributeType, attributeSize); if (attributeValue === void 0) { Logger.Warn(`Unknown header attribute type ${attributeType}'.`); } else { headerData[attributeName] = attributeValue; } } } if ((specData & ~4) != 0) { throw new Error("Unsupported file format"); } return { version, spec, ...headerData }; } var EXR_MAGIC; var init_exrLoader_header = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.header.js"() { init_logger(); init_exrLoader_core(); EXR_MAGIC = 20000630; __name(GetExrHeader, "GetExrHeader"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.huf.js function ReverseLutFromBitmap(bitmap, lut) { let k = 0; for (let i = 0; i < USHORT_RANGE; ++i) { if (i == 0 || bitmap[i >> 3] & 1 << (i & 7)) { lut[k++] = i; } } const n = k - 1; while (k < USHORT_RANGE) { lut[k++] = 0; } return n; } function HufClearDecTable(hdec) { for (let i = 0; i < HUF_DECSIZE; i++) { hdec[i] = {}; hdec[i].len = 0; hdec[i].lit = 0; hdec[i].p = null; } } function GetBits(nBits, c, lc, array, offset) { while (lc < nBits) { c = c << 8 | ParseUint8Array(array, offset); lc += 8; } lc -= nBits; return { l: c >> lc & (1 << nBits) - 1, c, lc }; } function GetChar(c, lc, array, offset) { c = c << 8 | ParseUint8Array(array, offset); lc += 8; return { c, lc }; } function GetCode(po, rlc, c, lc, array, offset, outBuffer, outBufferOffset, outBufferEndOffset) { if (po == rlc) { if (lc < 8) { const gc = GetChar(c, lc, array, offset); c = gc.c; lc = gc.lc; } lc -= 8; let cs = c >> lc; cs = new Uint8Array([cs])[0]; if (outBufferOffset.value + cs > outBufferEndOffset) { return null; } const s = outBuffer[outBufferOffset.value - 1]; while (cs-- > 0) { outBuffer[outBufferOffset.value++] = s; } } else if (outBufferOffset.value < outBufferEndOffset) { outBuffer[outBufferOffset.value++] = po; } else { return null; } return { c, lc }; } function HufCanonicalCodeTable(hcode) { for (let i = 0; i <= 58; ++i) { HufTableBuffer[i] = 0; } for (let i = 0; i < HUF_ENCSIZE; ++i) { HufTableBuffer[hcode[i]] += 1; } let c = 0; for (let i = 58; i > 0; --i) { const nc = c + HufTableBuffer[i] >> 1; HufTableBuffer[i] = c; c = nc; } for (let i = 0; i < HUF_ENCSIZE; ++i) { const l = hcode[i]; if (l > 0) { hcode[i] = l | HufTableBuffer[l]++ << 6; } } } function HufUnpackEncTable(array, offset, ni, im, iM, hcode) { const p = offset; let c = 0; let lc = 0; for (; im <= iM; im++) { if (p.value - offset.value > ni) { return; } let gb = GetBits(6, c, lc, array, p); const l = gb.l; c = gb.c; lc = gb.lc; hcode[im] = l; if (l == LONG_ZEROCODE_RUN) { if (p.value - offset.value > ni) { throw new Error("Error in HufUnpackEncTable"); } gb = GetBits(8, c, lc, array, p); let zerun = gb.l + SHORTEST_LONG_RUN; c = gb.c; lc = gb.lc; if (im + zerun > iM + 1) { throw new Error("Error in HufUnpackEncTable"); } while (zerun--) { hcode[im++] = 0; } im--; } else if (l >= SHORT_ZEROCODE_RUN) { let zerun = l - SHORT_ZEROCODE_RUN + 2; if (im + zerun > iM + 1) { throw new Error("Error in HufUnpackEncTable"); } while (zerun--) { hcode[im++] = 0; } im--; } } HufCanonicalCodeTable(hcode); } function HufLength(code) { return code & 63; } function HufCode(code) { return code >> 6; } function HufBuildDecTable(hcode, im, iM, hdecod) { for (; im <= iM; im++) { const c = HufCode(hcode[im]); const l = HufLength(hcode[im]); if (c >> l) { throw new Error("Invalid table entry"); } if (l > HUF_DECBITS) { const pl = hdecod[c >> l - HUF_DECBITS]; if (pl.len) { throw new Error("Invalid table entry"); } pl.lit++; if (pl.p) { const p = pl.p; pl.p = new Array(pl.lit); for (let i = 0; i < pl.lit - 1; ++i) { pl.p[i] = p[i]; } } else { pl.p = new Array(1); } pl.p[pl.lit - 1] = im; } else if (l) { let plOffset = 0; for (let i = 1 << HUF_DECBITS - l; i > 0; i--) { const pl = hdecod[(c << HUF_DECBITS - l) + plOffset]; if (pl.len || pl.p) { throw new Error("Invalid table entry"); } pl.len = l; pl.lit = im; plOffset++; } } } return true; } function HufDecode(encodingTable, decodingTable, array, offset, ni, rlc, no, outBuffer, outOffset) { let c = 0; let lc = 0; const outBufferEndOffset = no; const inOffsetEnd = Math.trunc(offset.value + (ni + 7) / 8); while (offset.value < inOffsetEnd) { let gc = GetChar(c, lc, array, offset); c = gc.c; lc = gc.lc; while (lc >= HUF_DECBITS) { const index = c >> lc - HUF_DECBITS & HUF_DECMASK; const pl = decodingTable[index]; if (pl.len) { lc -= pl.len; const gCode = GetCode(pl.lit, rlc, c, lc, array, offset, outBuffer, outOffset, outBufferEndOffset); if (gCode) { c = gCode.c; lc = gCode.lc; } } else { if (!pl.p) { throw new Error("hufDecode issues"); } let j; for (j = 0; j < pl.lit; j++) { const l = HufLength(encodingTable[pl.p[j]]); while (lc < l && offset.value < inOffsetEnd) { gc = GetChar(c, lc, array, offset); c = gc.c; lc = gc.lc; } if (lc >= l) { if (HufCode(encodingTable[pl.p[j]]) == (c >> lc - l & (1 << l) - 1)) { lc -= l; const gCode = GetCode(pl.p[j], rlc, c, lc, array, offset, outBuffer, outOffset, outBufferEndOffset); if (gCode) { c = gCode.c; lc = gCode.lc; } break; } } } if (j == pl.lit) { throw new Error("HufDecode issues"); } } } } const i = 8 - ni & 7; c >>= i; lc -= i; while (lc > 0) { const pl = decodingTable[c << HUF_DECBITS - lc & HUF_DECMASK]; if (pl.len) { lc -= pl.len; const gCode = GetCode(pl.lit, rlc, c, lc, array, offset, outBuffer, outOffset, outBufferEndOffset); if (gCode) { c = gCode.c; lc = gCode.lc; } } else { throw new Error("HufDecode issues"); } } return true; } function HufUncompress(array, dataView, offset, nCompressed, outBuffer, nRaw) { const outOffset = { value: 0 }; const initialInOffset = offset.value; const im = ParseUint32(dataView, offset); const iM = ParseUint32(dataView, offset); offset.value += 4; const nBits = ParseUint32(dataView, offset); offset.value += 4; if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) { throw new Error("Wrong HUF_ENCSIZE"); } const freq = new Array(HUF_ENCSIZE); const hdec = new Array(HUF_DECSIZE); HufClearDecTable(hdec); const ni = nCompressed - (offset.value - initialInOffset); HufUnpackEncTable(array, offset, ni, im, iM, freq); if (nBits > 8 * (nCompressed - (offset.value - initialInOffset))) { throw new Error("Wrong hufUncompress"); } HufBuildDecTable(freq, im, iM, hdec); HufDecode(freq, hdec, array, offset, nBits, iM, nRaw, outBuffer, outOffset); } function UInt16(value) { return value & 65535; } function Int16(value) { const ref = UInt16(value); return ref > 32767 ? ref - 65536 : ref; } function Wdec14(l, h) { const ls = Int16(l); const hs = Int16(h); const hi = hs; const ai = ls + (hi & 1) + (hi >> 1); const as = ai; const bs = ai - hi; return { a: as, b: bs }; } function Wdec16(l, h) { const m = UInt16(l); const d = UInt16(h); const bb = m - (d >> 1) & MOD_MASK; const aa = d + bb - A_OFFSET & MOD_MASK; return { a: aa, b: bb }; } function Wav2Decode(buffer, j, nx, ox, ny, oy, mx) { const w14 = mx < 1 << 14; const n = nx > ny ? ny : nx; let p = 1; let p2; let py; while (p <= n) { p <<= 1; } p >>= 1; p2 = p; p >>= 1; while (p >= 1) { py = 0; const ey = py + oy * (ny - p2); const oy1 = oy * p; const oy2 = oy * p2; const ox1 = ox * p; const ox2 = ox * p2; let i00, i01, i10, i11; for (; py <= ey; py += oy2) { let px = py; const ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { const p01 = px + ox1; const p10 = px + oy1; const p11 = p10 + ox1; if (w14) { let result = Wdec14(buffer[px + j], buffer[p10 + j]); i00 = result.a; i10 = result.b; result = Wdec14(buffer[p01 + j], buffer[p11 + j]); i01 = result.a; i11 = result.b; result = Wdec14(i00, i01); buffer[px + j] = result.a; buffer[p01 + j] = result.b; result = Wdec14(i10, i11); buffer[p10 + j] = result.a; buffer[p11 + j] = result.b; } else { let result = Wdec16(buffer[px + j], buffer[p10 + j]); i00 = result.a; i10 = result.b; result = Wdec16(buffer[p01 + j], buffer[p11 + j]); i01 = result.a; i11 = result.b; result = Wdec16(i00, i01); buffer[px + j] = result.a; buffer[p01 + j] = result.b; result = Wdec16(i10, i11); buffer[p10 + j] = result.a; buffer[p11 + j] = result.b; } } if (nx & p) { const p10 = px + oy1; let result; if (w14) { result = Wdec14(buffer[px + j], buffer[p10 + j]); } else { result = Wdec16(buffer[px + j], buffer[p10 + j]); } i00 = result.a; buffer[p10 + j] = result.b; buffer[px + j] = i00; } } if (ny & p) { let px = py; const ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { const p01 = px + ox1; let result; if (w14) { result = Wdec14(buffer[px + j], buffer[p01 + j]); } else { result = Wdec16(buffer[px + j], buffer[p01 + j]); } i00 = result.a; buffer[p01 + j] = result.b; buffer[px + j] = i00; } } p2 = p; p >>= 1; } return py; } function ApplyLut(lut, data, nData) { for (let i = 0; i < nData; ++i) { data[i] = lut[data[i]]; } } var NBITS, A_OFFSET, MOD_MASK, HufTableBuffer; var init_exrLoader_compression_huf = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.huf.js"() { init_exrLoader_core(); init_exrLoader_interfaces(); NBITS = 16; A_OFFSET = 1 << NBITS - 1; MOD_MASK = (1 << NBITS) - 1; __name(ReverseLutFromBitmap, "ReverseLutFromBitmap"); __name(HufClearDecTable, "HufClearDecTable"); __name(GetBits, "GetBits"); __name(GetChar, "GetChar"); __name(GetCode, "GetCode"); HufTableBuffer = new Array(59); __name(HufCanonicalCodeTable, "HufCanonicalCodeTable"); __name(HufUnpackEncTable, "HufUnpackEncTable"); __name(HufLength, "HufLength"); __name(HufCode, "HufCode"); __name(HufBuildDecTable, "HufBuildDecTable"); __name(HufDecode, "HufDecode"); __name(HufUncompress, "HufUncompress"); __name(UInt16, "UInt16"); __name(Int16, "Int16"); __name(Wdec14, "Wdec14"); __name(Wdec16, "Wdec16"); __name(Wav2Decode, "Wav2Decode"); __name(ApplyLut, "ApplyLut"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.rle.js function DecodeRunLength(source) { let size = source.byteLength; const out = []; let p = 0; const reader = new DataView(source); while (size > 0) { const l = reader.getInt8(p++); if (l < 0) { const count = -l; size -= count + 1; for (let i = 0; i < count; i++) { out.push(reader.getUint8(p++)); } } else { const count = l; size -= 2; const value = reader.getUint8(p++); for (let i = 0; i < count + 1; i++) { out.push(value); } } } return out; } var init_exrLoader_compression_rle = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.rle.js"() { __name(DecodeRunLength, "DecodeRunLength"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.js function UncompressRAW(decoder) { return new DataView(decoder.array.buffer, decoder.offset.value, decoder.size); } function UncompressRLE(decoder) { const compressed = decoder.viewer.buffer.slice(decoder.offset.value, decoder.offset.value + decoder.size); const rawBuffer = new Uint8Array(DecodeRunLength(compressed)); const tmpBuffer = new Uint8Array(rawBuffer.length); Predictor(rawBuffer); InterleaveScalar(rawBuffer, tmpBuffer); return new DataView(tmpBuffer.buffer); } function UncompressZIP(decoder) { const compressed = decoder.array.slice(decoder.offset.value, decoder.offset.value + decoder.size); const rawBuffer = fflate.unzlibSync(compressed); const tmpBuffer = new Uint8Array(rawBuffer.length); Predictor(rawBuffer); InterleaveScalar(rawBuffer, tmpBuffer); return new DataView(tmpBuffer.buffer); } function UncompressPXR(decoder) { const compressed = decoder.array.slice(decoder.offset.value, decoder.offset.value + decoder.size); const rawBuffer = fflate.unzlibSync(compressed); const sz = decoder.lines * decoder.channels * decoder.width; const tmpBuffer = decoder.type == 1 ? new Uint16Array(sz) : new Uint32Array(sz); let tmpBufferEnd = 0; let writePtr = 0; const ptr = new Array(4); for (let y = 0; y < decoder.lines; y++) { for (let c = 0; c < decoder.channels; c++) { let pixel = 0; switch (decoder.type) { case 1: ptr[0] = tmpBufferEnd; ptr[1] = ptr[0] + decoder.width; tmpBufferEnd = ptr[1] + decoder.width; for (let j = 0; j < decoder.width; ++j) { const diff = rawBuffer[ptr[0]++] << 8 | rawBuffer[ptr[1]++]; pixel += diff; tmpBuffer[writePtr] = pixel; writePtr++; } break; case 2: ptr[0] = tmpBufferEnd; ptr[1] = ptr[0] + decoder.width; ptr[2] = ptr[1] + decoder.width; tmpBufferEnd = ptr[2] + decoder.width; for (let j = 0; j < decoder.width; ++j) { const diff = rawBuffer[ptr[0]++] << 24 | rawBuffer[ptr[1]++] << 16 | rawBuffer[ptr[2]++] << 8; pixel += diff; tmpBuffer[writePtr] = pixel; writePtr++; } break; } } } return new DataView(tmpBuffer.buffer); } function UncompressPIZ(decoder) { const inDataView = decoder.viewer; const inOffset = { value: decoder.offset.value }; const outBuffer = new Uint16Array(decoder.width * decoder.scanlineBlockSize * (decoder.channels * decoder.type)); const bitmap = new Uint8Array(BITMAP_SIZE); let outBufferEnd = 0; const pizChannelData = new Array(decoder.channels); for (let i = 0; i < decoder.channels; i++) { pizChannelData[i] = {}; pizChannelData[i]["start"] = outBufferEnd; pizChannelData[i]["end"] = pizChannelData[i]["start"]; pizChannelData[i]["nx"] = decoder.width; pizChannelData[i]["ny"] = decoder.lines; pizChannelData[i]["size"] = decoder.type; outBufferEnd += pizChannelData[i].nx * pizChannelData[i].ny * pizChannelData[i].size; } const minNonZero = ParseUint16(inDataView, inOffset); const maxNonZero = ParseUint16(inDataView, inOffset); if (maxNonZero >= BITMAP_SIZE) { throw new Error("Wrong PIZ_COMPRESSION BITMAP_SIZE"); } if (minNonZero <= maxNonZero) { for (let i = 0; i < maxNonZero - minNonZero + 1; i++) { bitmap[i + minNonZero] = ParseUint8(inDataView, inOffset); } } const lut = new Uint16Array(USHORT_RANGE); const maxValue = ReverseLutFromBitmap(bitmap, lut); const length = ParseUint32(inDataView, inOffset); HufUncompress(decoder.array, inDataView, inOffset, length, outBuffer, outBufferEnd); for (let i = 0; i < decoder.channels; ++i) { const cd = pizChannelData[i]; for (let j = 0; j < pizChannelData[i].size; ++j) { Wav2Decode(outBuffer, cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } ApplyLut(lut, outBuffer, outBufferEnd); let tmpOffset = 0; const tmpBuffer = new Uint8Array(outBuffer.buffer.byteLength); for (let y = 0; y < decoder.lines; y++) { for (let c = 0; c < decoder.channels; c++) { const cd = pizChannelData[c]; const n = cd.nx * cd.size; const cp = new Uint8Array(outBuffer.buffer, cd.end * INT16_SIZE, n * INT16_SIZE); tmpBuffer.set(cp, tmpOffset); tmpOffset += n * INT16_SIZE; cd.end += n; } } return new DataView(tmpBuffer.buffer); } var init_exrLoader_compression = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.compression.js"() { init_exrLoader_compression_huf(); init_exrLoader_compression_rle(); init_exrLoader_core(); init_exrLoader_interfaces(); __name(UncompressRAW, "UncompressRAW"); __name(UncompressRLE, "UncompressRLE"); __name(UncompressZIP, "UncompressZIP"); __name(UncompressPXR, "UncompressPXR"); __name(UncompressPIZ, "UncompressPIZ"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.configuration.js var EXROutputType, ExrLoaderGlobalConfiguration; var init_exrLoader_configuration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.configuration.js"() { (function(EXROutputType2) { EXROutputType2[EXROutputType2["Float"] = 0] = "Float"; EXROutputType2[EXROutputType2["HalfFloat"] = 1] = "HalfFloat"; })(EXROutputType || (EXROutputType = {})); ExrLoaderGlobalConfiguration = class { static { __name(this, "ExrLoaderGlobalConfiguration"); } }; ExrLoaderGlobalConfiguration.DefaultOutputType = EXROutputType.HalfFloat; ExrLoaderGlobalConfiguration.FFLATEUrl = "https://unpkg.com/fflate@0.8.2"; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.decoder.js async function CreateDecoderAsync(header, dataView, offset, outputType) { const decoder = { size: 0, viewer: dataView, array: new Uint8Array(dataView.buffer), offset, width: header.dataWindow.xMax - header.dataWindow.xMin + 1, height: header.dataWindow.yMax - header.dataWindow.yMin + 1, channels: header.channels.length, channelLineOffsets: {}, scanOrder: /* @__PURE__ */ __name(() => 0, "scanOrder"), bytesPerLine: 0, outLineWidth: 0, lines: 0, scanlineBlockSize: 0, inputSize: null, type: 0, uncompress: null, getter: /* @__PURE__ */ __name(() => 0, "getter"), format: 5, outputChannels: 0, decodeChannels: {}, blockCount: null, byteArray: null, linearSpace: false, textureType: 0 }; switch (header.compression) { case CompressionCodes.NO_COMPRESSION: decoder.lines = 1; decoder.uncompress = UncompressRAW; break; case CompressionCodes.RLE_COMPRESSION: decoder.lines = 1; decoder.uncompress = UncompressRLE; break; case CompressionCodes.ZIPS_COMPRESSION: decoder.lines = 1; decoder.uncompress = UncompressZIP; await Tools.LoadScriptAsync(ExrLoaderGlobalConfiguration.FFLATEUrl); break; case CompressionCodes.ZIP_COMPRESSION: decoder.lines = 16; decoder.uncompress = UncompressZIP; await Tools.LoadScriptAsync(ExrLoaderGlobalConfiguration.FFLATEUrl); break; case CompressionCodes.PIZ_COMPRESSION: decoder.lines = 32; decoder.uncompress = UncompressPIZ; break; case CompressionCodes.PXR24_COMPRESSION: decoder.lines = 16; decoder.uncompress = UncompressPXR; await Tools.LoadScriptAsync(ExrLoaderGlobalConfiguration.FFLATEUrl); break; default: throw new Error(CompressionCodes[header.compression] + " is unsupported"); } decoder.scanlineBlockSize = decoder.lines; const channels = {}; for (const channel of header.channels) { switch (channel.name) { case "R": case "G": case "B": case "A": channels[channel.name] = true; decoder.type = channel.pixelType; break; case "Y": channels[channel.name] = true; decoder.type = channel.pixelType; break; default: break; } } let fillAlpha = false; if (channels.R && channels.G && channels.B && channels.A) { decoder.outputChannels = 4; decoder.decodeChannels = { R: 0, G: 1, B: 2, A: 3 }; } else if (channels.R && channels.G && channels.B) { fillAlpha = true; decoder.outputChannels = 4; decoder.decodeChannels = { R: 0, G: 1, B: 2, A: 3 }; } else if (channels.R && channels.G) { decoder.outputChannels = 2; decoder.decodeChannels = { R: 0, G: 1 }; } else if (channels.R) { decoder.outputChannels = 1; decoder.decodeChannels = { R: 0 }; } else if (channels.Y) { decoder.outputChannels = 1; decoder.decodeChannels = { Y: 0 }; } else { throw new Error("EXRLoader.parse: file contains unsupported data channels."); } if (decoder.type === 1) { switch (outputType) { case EXROutputType.Float: decoder.getter = ParseFloat16; decoder.inputSize = INT16_SIZE; break; case EXROutputType.HalfFloat: decoder.getter = ParseUint16; decoder.inputSize = INT16_SIZE; break; } } else if (decoder.type === 2) { switch (outputType) { case EXROutputType.Float: decoder.getter = ParseFloat32; decoder.inputSize = FLOAT32_SIZE; break; case EXROutputType.HalfFloat: decoder.getter = DecodeFloat32; decoder.inputSize = FLOAT32_SIZE; } } else { throw new Error("Unsupported pixelType " + decoder.type + " for " + header.compression); } decoder.blockCount = decoder.height / decoder.scanlineBlockSize; for (let i = 0; i < decoder.blockCount; i++) { ParseInt64(dataView, offset); } const size = decoder.width * decoder.height * decoder.outputChannels; switch (outputType) { case EXROutputType.Float: decoder.byteArray = new Float32Array(size); decoder.textureType = 1; if (fillAlpha) { decoder.byteArray.fill(1, 0, size); } break; case EXROutputType.HalfFloat: decoder.byteArray = new Uint16Array(size); decoder.textureType = 2; if (fillAlpha) { decoder.byteArray.fill(15360, 0, size); } break; default: throw new Error("Unsupported type: " + outputType); } let byteOffset = 0; for (const channel of header.channels) { if (decoder.decodeChannels[channel.name] !== void 0) { decoder.channelLineOffsets[channel.name] = byteOffset * decoder.width; } byteOffset += channel.pixelType * 2; } decoder.bytesPerLine = decoder.width * byteOffset; decoder.outLineWidth = decoder.width * decoder.outputChannels; if (header.lineOrder === "INCREASING_Y") { decoder.scanOrder = (y) => y; } else { decoder.scanOrder = (y) => decoder.height - 1 - y; } if (decoder.outputChannels == 4) { decoder.format = 5; decoder.linearSpace = true; } else { decoder.format = 6; decoder.linearSpace = false; } return decoder; } function ScanData(decoder, header, dataView, offset) { const tmpOffset = { value: 0 }; for (let scanlineBlockIdx = 0; scanlineBlockIdx < decoder.height / decoder.scanlineBlockSize; scanlineBlockIdx++) { const line = ParseInt32(dataView, offset) - header.dataWindow.yMin; decoder.size = ParseUint32(dataView, offset); decoder.lines = line + decoder.scanlineBlockSize > decoder.height ? decoder.height - line : decoder.scanlineBlockSize; const isCompressed = decoder.size < decoder.lines * decoder.bytesPerLine; const viewer = isCompressed && decoder.uncompress ? decoder.uncompress(decoder) : UncompressRAW(decoder); offset.value += decoder.size; for (let lineY = 0; lineY < decoder.scanlineBlockSize; lineY++) { const scanY = scanlineBlockIdx * decoder.scanlineBlockSize; const trueY = lineY + decoder.scanOrder(scanY); if (trueY >= decoder.height) { continue; } const lineOffset = lineY * decoder.bytesPerLine; const outLineOffset = (decoder.height - 1 - trueY) * decoder.outLineWidth; for (let channelID = 0; channelID < decoder.channels; channelID++) { const name260 = header.channels[channelID].name; const lOff = decoder.channelLineOffsets[name260]; const cOff = decoder.decodeChannels[name260]; if (cOff === void 0) { continue; } tmpOffset.value = lineOffset + lOff; for (let x = 0; x < decoder.width; x++) { const outIndex = outLineOffset + x * decoder.outputChannels + cOff; if (decoder.byteArray) { decoder.byteArray[outIndex] = decoder.getter(viewer, tmpOffset); } } } } } } var init_exrLoader_decoder = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/EXR/exrLoader.decoder.js"() { init_exrLoader_core(); init_exrLoader_compression(); init_exrLoader_interfaces(); init_tools(); init_exrLoader_configuration(); __name(CreateDecoderAsync, "CreateDecoderAsync"); __name(ScanData, "ScanData"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/exrTextureLoader.js var exrTextureLoader_exports = {}; __export(exrTextureLoader_exports, { ReadExrDataAsync: () => ReadExrDataAsync, _ExrTextureLoader: () => _ExrTextureLoader }); async function ReadExrDataAsync(data) { const dataView = new DataView(data); const offset = { value: 0 }; const header = GetExrHeader(dataView, offset); try { const decoder = await CreateDecoderAsync(header, dataView, offset, EXROutputType.Float); ScanData(decoder, header, dataView, offset); if (!decoder.byteArray) { Logger.Error("Failed to decode EXR data: No byte array available."); return { width: 0, height: 0, data: null }; } return { width: header.dataWindow.xMax - header.dataWindow.xMin + 1, height: header.dataWindow.yMax - header.dataWindow.yMin + 1, data: new Float32Array(decoder.byteArray) }; } catch (error) { Logger.Error("Failed to load EXR data: ", error); } return { width: 0, height: 0, data: null }; } var _ExrTextureLoader; var init_exrTextureLoader = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/exrTextureLoader.js"() { init_exrLoader_header(); init_exrLoader_decoder(); init_exrLoader_configuration(); init_logger(); _ExrTextureLoader = class { static { __name(this, "_ExrTextureLoader"); } constructor() { this.supportCascades = false; } /** * 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 * Cube texture are not supported by .exr files */ loadCubeData(_data, _texture, _createPolynomials, _onLoad, _onError) { throw ".exr 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 */ // eslint-disable-next-line @typescript-eslint/naming-convention loadData(data, texture, callback) { const dataView = new DataView(data.buffer); const offset = { value: 0 }; const header = GetExrHeader(dataView, offset); CreateDecoderAsync(header, dataView, offset, ExrLoaderGlobalConfiguration.DefaultOutputType).then((decoder) => { ScanData(decoder, header, dataView, offset); const width = header.dataWindow.xMax - header.dataWindow.xMin + 1; const height = header.dataWindow.yMax - header.dataWindow.yMin + 1; callback(width, height, texture.generateMipMaps, false, () => { const engine = texture.getEngine(); texture.format = header.format; texture.type = decoder.textureType; texture.invertY = false; texture._gammaSpace = !header.linearSpace; if (decoder.byteArray) { engine._uploadDataToTextureDirectly(texture, decoder.byteArray, 0, 0, void 0, true); } }); }).catch((error) => { Logger.Error("Failed to load EXR texture: ", error); }); } }; __name(ReadExrDataAsync, "ReadExrDataAsync"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/textureLoaderManager.js function registerTextureLoader(extension, loaderFactory) { if (unregisterTextureLoader(extension)) { Logger.Warn(`Extension with the name '${extension}' already exists`); } RegisteredTextureLoaders.set(extension, loaderFactory); } function unregisterTextureLoader(extension) { return RegisteredTextureLoaders.delete(extension); } function _GetCompatibleTextureLoader(extension, mimeType) { if (mimeType === "image/ktx" || mimeType === "image/ktx2") { extension = ".ktx"; } if (!RegisteredTextureLoaders.has(extension)) { if (extension.endsWith(".ies")) { registerTextureLoader(".ies", async () => await Promise.resolve().then(() => (init_iesTextureLoader(), iesTextureLoader_exports)).then((module2) => new module2._IESTextureLoader())); } if (extension.endsWith(".dds")) { registerTextureLoader(".dds", async () => await Promise.resolve().then(() => (init_ddsTextureLoader(), ddsTextureLoader_exports)).then((module2) => new module2._DDSTextureLoader())); } if (extension.endsWith(".basis")) { registerTextureLoader(".basis", async () => await Promise.resolve().then(() => (init_basisTextureLoader(), basisTextureLoader_exports)).then((module2) => new module2._BasisTextureLoader())); } if (extension.endsWith(".env")) { registerTextureLoader(".env", async () => await Promise.resolve().then(() => (init_envTextureLoader(), envTextureLoader_exports)).then((module2) => new module2._ENVTextureLoader())); } if (extension.endsWith(".hdr")) { registerTextureLoader(".hdr", async () => await Promise.resolve().then(() => (init_hdrTextureLoader(), hdrTextureLoader_exports)).then((module2) => new module2._HDRTextureLoader())); } if (extension.endsWith(".ktx") || extension.endsWith(".ktx2")) { registerTextureLoader(".ktx", async () => await Promise.resolve().then(() => (init_ktxTextureLoader(), ktxTextureLoader_exports)).then((module2) => new module2._KTXTextureLoader())); registerTextureLoader(".ktx2", async () => await Promise.resolve().then(() => (init_ktxTextureLoader(), ktxTextureLoader_exports)).then((module2) => new module2._KTXTextureLoader())); } if (extension.endsWith(".tga")) { registerTextureLoader(".tga", async () => await Promise.resolve().then(() => (init_tgaTextureLoader(), tgaTextureLoader_exports)).then((module2) => new module2._TGATextureLoader())); } if (extension.endsWith(".exr")) { registerTextureLoader(".exr", async () => await Promise.resolve().then(() => (init_exrTextureLoader(), exrTextureLoader_exports)).then((module2) => new module2._ExrTextureLoader())); } } const registered6 = RegisteredTextureLoaders.get(extension); return registered6 ? Promise.resolve(registered6(mimeType)) : null; } var RegisteredTextureLoaders; var init_textureLoaderManager = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/Loaders/textureLoaderManager.js"() { init_logger(); RegisteredTextureLoaders = /* @__PURE__ */ new Map(); __name(registerTextureLoader, "registerTextureLoader"); __name(unregisterTextureLoader, "unregisterTextureLoader"); __name(_GetCompatibleTextureLoader, "_GetCompatibleTextureLoader"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/abstractEngine.js function QueueNewFrame(func, requester) { if (!IsWindowObjectExist()) { if (typeof requestAnimationFrame === "function") { return requestAnimationFrame(func); } } else { const { requestAnimationFrame: requestAnimationFrame2 } = requester || window; if (typeof requestAnimationFrame2 === "function") { return requestAnimationFrame2(func); } } return setTimeout(func, 16); } var AbstractEngine; var init_abstractEngine = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/abstractEngine.js"() { init_engineStore(); init_logger(); init_effect(); init_performanceConfigurator(); init_precisionDate(); init_depthCullingState(); init_stencilStateComposer(); init_stencilState(); init_alphaCullingState(); init_devTools(); init_internalTexture(); init_domManagement(); init_observable(); init_abstractEngine_functions(); init_textureLoaderManager(); __name(QueueNewFrame, "QueueNewFrame"); AbstractEngine = class _AbstractEngine { static { __name(this, "AbstractEngine"); } /** * Gets the current frame id */ get frameId() { return this._frameId; } /** * Gets a boolean indicating if the engine runs in WebGPU or not. */ get isWebGPU() { return this._isWebGPU; } /** * @internal */ _getShaderProcessor(_shaderLanguage) { return this._shaderProcessor; } /** * @internal */ _resetAlphaMode() { this._alphaMode.fill(-1); this._alphaEquation.fill(-1); } /** * Gets the shader platform name used by the effects. */ get shaderPlatformName() { return this._shaderPlatformName; } _clearEmptyResources() { this._emptyTexture = null; this._emptyCubeTexture = null; this._emptyTexture3D = null; this._emptyTexture2DArray = null; } /** * 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. */ get useReverseDepthBuffer() { return this._useReverseDepthBuffer; } set useReverseDepthBuffer(useReverse) { if (useReverse === this._useReverseDepthBuffer) { return; } this._useReverseDepthBuffer = useReverse; if (useReverse) { this._depthCullingState.depthFunc = 518; } else { this._depthCullingState.depthFunc = 515; } } /** * Enable or disable color writing * @param enable defines the state to set */ setColorWrite(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 */ getColorWrite() { return this._colorWrite; } /** * Gets the depth culling state manager */ get depthCullingState() { return this._depthCullingState; } /** * Gets the alpha state manager */ get alphaState() { return this._alphaState; } /** * Gets the stencil state manager */ get stencilState() { return this._stencilState; } /** * Gets the stencil state composer */ get stencilStateComposer() { return this._stencilStateComposer; } /** @internal */ _getGlobalDefines(defines) { if (defines) { if (this.isNDCHalfZRange) { defines["IS_NDC_HALF_ZRANGE"] = ""; } else { delete defines["IS_NDC_HALF_ZRANGE"]; } if (this.useReverseDepthBuffer) { defines["USE_REVERSE_DEPTHBUFFER"] = ""; } else { delete defines["USE_REVERSE_DEPTHBUFFER"]; } if (this.useExactSrgbConversions) { defines["USE_EXACT_SRGB_CONVERSIONS"] = ""; } else { delete defines["USE_EXACT_SRGB_CONVERSIONS"]; } return; } else { let s = ""; if (this.isNDCHalfZRange) { s += "#define IS_NDC_HALF_ZRANGE"; } if (this.useReverseDepthBuffer) { if (s) { s += "\n"; } s += "#define USE_REVERSE_DEPTHBUFFER"; } if (this.useExactSrgbConversions) { if (s) { s += "\n"; } s += "#define USE_EXACT_SRGB_CONVERSIONS"; } return s; } } _rebuildInternalTextures() { const currentState = this._internalTexturesCache.slice(); for (const internalTexture of currentState) { internalTexture._rebuild(); } } _rebuildRenderTargetWrappers() { const currentState = this._renderTargetWrapperCache.slice(); for (const renderTargetWrapper of currentState) { renderTargetWrapper._rebuild(); } } _rebuildEffects() { for (const key in this._compiledEffects) { const effect = this._compiledEffects[key]; effect._pipelineContext = null; effect._prepareEffect(); } Effect.ResetCache(); } _rebuildGraphicsResources() { this.wipeCaches(true); this._rebuildEffects(); this._rebuildComputeEffects?.(); this._rebuildBuffers(); this._rebuildInternalTextures(); this._rebuildTextures(); this._rebuildRenderTargetWrappers(); this.wipeCaches(true); } _flagContextRestored() { Logger.Warn(this.name + " context successfully restored."); this.onContextRestoredObservable.notifyObservers(this); this._contextWasLost = false; } _restoreEngineAfterContextLost(initEngine) { setTimeout(() => { this._clearEmptyResources(); const depthTest = this._depthCullingState.depthTest; const depthFunc = this._depthCullingState.depthFunc; const depthMask = this._depthCullingState.depthMask; const stencilTest = this._stencilState.stencilTest; initEngine(); this._rebuildGraphicsResources(); this._depthCullingState.depthTest = depthTest; this._depthCullingState.depthFunc = depthFunc; this._depthCullingState.depthMask = depthMask; this._stencilState.stencilTest = stencilTest; this._flagContextRestored(); }, 0); } /** Gets a boolean indicating if the engine was disposed */ get isDisposed() { return this._isDisposed; } /** * Enables or disables the snapshot rendering mode * Note that the WebGL engine does not support snapshot rendering so setting the value won't have any effect for this engine */ get snapshotRendering() { return false; } set snapshotRendering(activate) { } /** * Gets or sets the snapshot rendering mode */ get snapshotRenderingMode() { return 0; } set snapshotRenderingMode(mode) { } /** * Returns the string "AbstractEngine" * @returns "AbstractEngine" */ getClassName() { return "AbstractEngine"; } /** * Gets the default empty texture */ get emptyTexture() { if (!this._emptyTexture) { this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, 5, false, false, 1); } return this._emptyTexture; } /** * Gets the default empty 3D texture */ get emptyTexture3D() { if (!this._emptyTexture3D) { this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, 5, false, false, 1); } return this._emptyTexture3D; } /** * Gets the default empty 2D array texture */ get emptyTexture2DArray() { if (!this._emptyTexture2DArray) { this._emptyTexture2DArray = this.createRawTexture2DArray(new Uint8Array(4), 1, 1, 1, 5, false, false, 1); } return this._emptyTexture2DArray; } /** * Gets the default empty cube texture */ get emptyCubeTexture() { if (!this._emptyCubeTexture) { const faceData = new Uint8Array(4); const cubeData = [faceData, faceData, faceData, faceData, faceData, faceData]; this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, 5, 0, false, false, 1); } return this._emptyCubeTexture; } /** * Gets the list of current active render loop functions * @returns a read only array with the current render loop functions */ get activeRenderLoops() { return this._activeRenderLoops; } /** * 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. */ stopRenderLoop(renderFunction) { if (!renderFunction) { this._activeRenderLoops.length = 0; this._cancelFrame(); return; } const index = this._activeRenderLoops.indexOf(renderFunction); if (index >= 0) { this._activeRenderLoops.splice(index, 1); if (this._activeRenderLoops.length == 0) { this._cancelFrame(); } } } _cancelFrame() { if (this._frameHandler !== 0) { const handlerToCancel = this._frameHandler; this._frameHandler = 0; if (!IsWindowObjectExist()) { if (typeof cancelAnimationFrame === "function") { return cancelAnimationFrame(handlerToCancel); } } else { const { cancelAnimationFrame: cancelAnimationFrame2 } = this.getHostWindow() || window; if (typeof cancelAnimationFrame2 === "function") { return cancelAnimationFrame2(handlerToCancel); } } return clearTimeout(handlerToCancel); } } /** * Begin a new frame */ beginFrame() { this.onBeginFrameObservable.notifyObservers(this); } /** * End the current frame */ endFrame() { this._frameId++; this.onEndFrameObservable.notifyObservers(this); } /** Gets or sets max frame per second allowed. Will return undefined if not capped */ get maxFPS() { return this._maxFPS; } set maxFPS(value) { this._maxFPS = value; if (value === void 0) { return; } if (value <= 0) { this._minFrameTime = Number.MAX_VALUE; return; } this._minFrameTime = 1e3 / value; } _isOverFrameTime(timestamp) { if (!timestamp || this._maxFPS === void 0) { return false; } const elapsedTime = timestamp - this._lastFrameTime; this._lastFrameTime = timestamp; this._renderAccumulator += elapsedTime; if (this._renderAccumulator < this._minFrameTime) { return true; } this._renderAccumulator -= this._minFrameTime; if (this._renderAccumulator > this._minFrameTime) { this._renderAccumulator = this._minFrameTime; } return false; } _processFrame(timestamp) { this._frameHandler = 0; if (!this._contextWasLost && !this._isOverFrameTime(timestamp)) { let shouldRender = true; if (this.isDisposed || !this.renderEvenInBackground && this._windowIsBackground) { shouldRender = false; } if (shouldRender) { this.beginFrame(); if (!this.skipFrameRender && !this._renderViews()) { this._renderFrame(); } this.endFrame(); } } } /** @internal */ _renderLoop(timestamp) { this._processFrame(timestamp); if (this._activeRenderLoops.length > 0 && this._frameHandler === 0) { this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow()); } } /** @internal */ _renderFrame() { for (let index = 0; index < this._activeRenderLoops.length; index++) { const renderFunction = this._activeRenderLoops[index]; renderFunction(); } } /** @internal */ _renderViews() { return false; } /** * Can be used to override the current requestAnimationFrame requester. * @internal */ _queueNewFrame(bindedRenderFunction, requester) { return 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 */ runRenderLoop(renderFunction) { if (this._activeRenderLoops.indexOf(renderFunction) !== -1) { return; } this._activeRenderLoops.push(renderFunction); if (this._activeRenderLoops.length === 1 && this._frameHandler === 0) { this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow()); } } /** * Gets a boolean indicating if depth testing is enabled * @returns the current state */ getDepthBuffer() { return this._depthCullingState.depthTest; } /** * Enable or disable depth buffering * @param enable defines the state to set */ setDepthBuffer(enable) { this._depthCullingState.depthTest = enable; } /** * Set the z offset Factor to apply to current rendering * @param value defines the offset to apply */ setZOffset(value) { this._depthCullingState.zOffset = this.useReverseDepthBuffer ? -value : value; } /** * Gets the current value of the zOffset Factor * @returns the current zOffset Factor state */ getZOffset() { const zOffset = this._depthCullingState.zOffset; return this.useReverseDepthBuffer ? -zOffset : zOffset; } /** * Set the z offset Units to apply to current rendering * @param value defines the offset to apply */ setZOffsetUnits(value) { this._depthCullingState.zOffsetUnits = this.useReverseDepthBuffer ? -value : value; } /** * Gets the current value of the zOffset Units * @returns the current zOffset Units state */ getZOffsetUnits() { const zOffsetUnits = this._depthCullingState.zOffsetUnits; return this.useReverseDepthBuffer ? -zOffsetUnits : zOffsetUnits; } /** * Gets host window * @returns the host window object */ getHostWindow() { if (!IsWindowObjectExist()) { return null; } if (this._renderingCanvas && this._renderingCanvas.ownerDocument && this._renderingCanvas.ownerDocument.defaultView) { return this._renderingCanvas.ownerDocument.defaultView; } return window; } /** * (WebGPU only) True (default) to be in compatibility mode, meaning rendering all existing scenes without artifacts (same rendering than WebGL). * Setting the property to false will improve performances but may not work in some scenes if some precautions are not taken. * See https://doc.babylonjs.com/setup/support/webGPU/webGPUOptimization/webGPUNonCompatibilityMode for more details */ get compatibilityMode() { return this._compatibilityMode; } set compatibilityMode(mode) { this._compatibilityMode = true; } _rebuildTextures() { for (const scene of this.scenes) { scene._rebuildTextures(); } for (const scene of this._virtualScenes) { scene._rebuildTextures(); } } /** * @internal */ _releaseRenderTargetWrapper(rtWrapper) { const index = this._renderTargetWrapperCache.indexOf(rtWrapper); if (index !== -1) { this._renderTargetWrapperCache.splice(index, 1); } } /** * Gets the current viewport */ get currentViewport() { return this._cachedViewport; } /** * 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 */ setViewport(viewport, requiredWidth, requiredHeight) { const width = requiredWidth || this.getRenderWidth(); const height = requiredHeight || this.getRenderHeight(); const x = viewport.x || 0; const y = viewport.y || 0; this._cachedViewport = viewport; this._viewport(x * width, y * height, width * viewport.width, height * viewport.height); } /** * Create an image to use with canvas * @returns IImage interface */ createCanvasImage() { return document.createElement("img"); } /** * Create a 2D path to use with canvas * @returns IPath2D interface * @param d SVG path string */ createCanvasPath2D(d) { return new Path2D(d); } /** * Returns a string describing the current engine */ get description() { let description = this.name + this.version; if (this._caps.parallelShaderCompile) { description += " - Parallel shader compilation"; } return description; } _createTextureBase(url, noMipmap, invertY, scene, samplingMode = 3, onLoad = null, onError = null, prepareTexture, prepareTextureProcess, buffer = null, fallback = null, format = null, forcedExtension = null, mimeType, loaderOptions, useSRGBBuffer) { url = url || ""; const fromData = url.substring(0, 5) === "data:"; const fromBlob = url.substring(0, 5) === "blob:"; const isBase64 = fromData && url.indexOf(";base64,") !== -1; const texture = fallback ? fallback : new InternalTexture( this, 1 /* InternalTextureSource.Url */ ); if (texture !== fallback) { texture.label = url.substring(0, 60); } const originalUrl = url; if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) { url = this._transformTextureUrl(url); } if (originalUrl !== url) { texture._originalUrl = originalUrl; } const lastDot = url.lastIndexOf("."); let extension = forcedExtension ? forcedExtension : lastDot > -1 ? url.substring(lastDot).toLowerCase() : ""; const queryStringIndex = extension.indexOf("?"); if (queryStringIndex > -1) { extension = extension.split("?")[0]; } const loaderPromise = _GetCompatibleTextureLoader(extension, mimeType); if (scene) { scene.addPendingData(texture); } texture.url = url; texture.generateMipMaps = !noMipmap; texture.samplingMode = samplingMode; texture.invertY = invertY; texture._useSRGBBuffer = this._getUseSRGBBuffer(!!useSRGBBuffer, noMipmap); if (!this._doNotHandleContextLost) { texture._buffer = buffer; } let onLoadObserver = null; if (onLoad && !fallback) { onLoadObserver = texture.onLoadedObservable.add(onLoad); } if (!fallback) { this._internalTexturesCache.push(texture); } const onInternalError = /* @__PURE__ */ __name((message, exception) => { if (scene) { scene.removePendingData(texture); } if (url === originalUrl) { if (onLoadObserver) { texture.onLoadedObservable.remove(onLoadObserver); } if (EngineStore.UseFallbackTexture && url !== EngineStore.FallbackTexture) { this._createTextureBase(EngineStore.FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, prepareTexture, prepareTextureProcess, buffer, texture); } message = (message || "Unknown error") + (EngineStore.UseFallbackTexture ? " - Fallback texture was used" : ""); texture.onErrorObservable.notifyObservers({ message, exception }); if (onError) { onError(message, exception); } } else { Logger.Warn(`Failed to load ${url}, falling back to ${originalUrl}`); this._createTextureBase(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, prepareTexture, prepareTextureProcess, buffer, texture, format, forcedExtension, mimeType, loaderOptions, useSRGBBuffer); } }, "onInternalError"); if (loaderPromise) { const callbackAsync = /* @__PURE__ */ __name(async (data) => { const loader = await loaderPromise; loader.loadData(data, texture, (width, height, loadMipmap, isCompressed, done, loadFailed) => { if (loadFailed) { onInternalError("TextureLoader failed to load data"); } else { prepareTexture(texture, extension, scene, { width, height }, texture.invertY, !loadMipmap, isCompressed, () => { done(); return false; }, samplingMode); } }, loaderOptions); }, "callbackAsync"); if (!buffer) { this._loadFile(url, (data) => { callbackAsync(new Uint8Array(data)); }, void 0, scene ? scene.offlineProvider : void 0, true, (request, exception) => { onInternalError("Unable to load " + (request ? request.responseURL : url, exception)); }); } else { if (buffer instanceof ArrayBuffer) { callbackAsync(new Uint8Array(buffer)); } else if (ArrayBuffer.isView(buffer)) { callbackAsync(buffer); } else { if (onError) { onError("Unable to load: only ArrayBuffer or ArrayBufferView is supported", null); } } } } else { const onload = /* @__PURE__ */ __name((img) => { if (fromBlob && !this._doNotHandleContextLost) { texture._buffer = img; } prepareTexture(texture, extension, scene, img, texture.invertY, noMipmap, false, prepareTextureProcess, samplingMode); }, "onload"); if (!fromData || isBase64) { if (buffer && (typeof buffer.decoding === "string" || buffer.close)) { onload(buffer); } else { _AbstractEngine._FileToolsLoadImage(url || "", onload, onInternalError, scene ? scene.offlineProvider : null, mimeType, texture.invertY && this._features.needsInvertingBitmap ? { imageOrientation: "flipY" } : void 0, this); } } else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer) || buffer instanceof Blob) { _AbstractEngine._FileToolsLoadImage(buffer, onload, onInternalError, scene ? scene.offlineProvider : null, mimeType, texture.invertY && this._features.needsInvertingBitmap ? { imageOrientation: "flipY" } : void 0, this); } else if (buffer) { onload(buffer); } } return texture; } _rebuildBuffers() { for (const uniformBuffer of this._uniformBuffers) { uniformBuffer._rebuildAfterContextLost(); } } /** @internal */ get _shouldUseHighPrecisionShader() { return !!(this._caps.highPrecisionShaderSupported && this._highPrecisionShadersAllowed); } /** * Gets host document * @returns the host document object */ getHostDocument() { if (this._renderingCanvas && this._renderingCanvas.ownerDocument) { return this._renderingCanvas.ownerDocument; } return IsDocumentAvailable() ? document : null; } /** * Gets the list of loaded textures * @returns an array containing all loaded textures */ getLoadedTexturesCache() { return this._internalTexturesCache; } /** * Clears the list of texture accessible through engine. * This can help preventing texture load conflict due to name collision. */ clearInternalTexturesCache() { this._internalTexturesCache.length = 0; } /** * Gets the object containing all engine capabilities * @returns the EngineCapabilities object */ getCaps() { return this._caps; } /** * Reset the texture cache to empty state */ resetTextureCache() { for (const key in this._boundTexturesCache) { if (!Object.prototype.hasOwnProperty.call(this._boundTexturesCache, key)) { continue; } this._boundTexturesCache[key] = null; } this._currentTextureChannel = -1; } /** * Gets or sets the name of the engine */ get name() { return this._name; } set name(value) { this._name = value; } /** * Returns the current npm package of the sdk */ // Not mixed with Version for tooling purpose. static get NpmPackage() { return "babylonjs@8.33.2"; } /** * Returns the current version of the framework */ static get Version() { return "8.33.2"; } /** * Gets the HTML canvas attached with the current webGL context * @returns a HTML canvas */ getRenderingCanvas() { return this._renderingCanvas; } /** * Gets the audio context specified in engine initialization options * @deprecated please use AudioEngineV2 instead * @returns an Audio Context */ getAudioContext() { return this._audioContext; } /** * Gets the audio destination specified in engine initialization options * @deprecated please use AudioEngineV2 instead * @returns an audio destination node */ getAudioDestination() { return this._audioDestination; } /** * 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 */ setHardwareScalingLevel(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 */ getHardwareScalingLevel() { return this._hardwareScalingLevel; } /** * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/optimize_your_scene#handling-webgl-context-lost */ get doNotHandleContextLost() { return this._doNotHandleContextLost; } set doNotHandleContextLost(value) { this._doNotHandleContextLost = value; } /** * Returns true if the stencil buffer has been enabled through the creation option of the context. */ get isStencilEnable() { return this._isStencilEnable; } /** * Gets the options used for engine creation * NOTE that modifying the object after engine creation will have no effect * @returns EngineOptions object */ getCreationOptions() { return this._creationOptions; } /** * Creates a new engine * @param antialias defines whether anti-aliasing should be enabled. If undefined, it means that the underlying engine is free to enable it or not * @param options defines further options to be sent to the creation context * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false) */ constructor(antialias, options, adaptToDeviceRatio) { this._colorWrite = true; this._colorWriteChanged = true; this._depthCullingState = new DepthCullingState(); this._stencilStateComposer = new StencilStateComposer(); this._stencilState = new StencilState(); this._alphaState = new AlphaState(false); this._alphaMode = Array(8).fill(-1); this._alphaEquation = Array(8).fill(-1); this._activeRequests = []; this._badOS = false; this._badDesktopOS = false; this._compatibilityMode = true; this._internalTexturesCache = new Array(); this._currentRenderTarget = null; this._boundTexturesCache = {}; this._activeChannel = 0; this._currentTextureChannel = -1; this._viewportCached = { x: 0, y: 0, z: 0, w: 0 }; this._isWebGPU = false; this.onCanvasBlurObservable = new Observable(); this.onCanvasFocusObservable = new Observable(); this.onNewSceneAddedObservable = new Observable(); this.onResizeObservable = new Observable(); this.onCanvasPointerOutObservable = new Observable(); this.onEffectErrorObservable = new Observable(); this.disablePerformanceMonitorInBackground = false; this.disableVertexArrayObjects = false; this._frameId = 0; this.hostInformation = { isMobile: false }; this.isFullscreen = false; this.enableOfflineSupport = false; this.disableManifestCheck = false; this.disableContextMenu = true; this.currentRenderPassId = 0; this.isPointerLock = false; this.postProcesses = []; this.canvasTabIndex = 1; this._contextWasLost = false; this._useReverseDepthBuffer = false; this.isNDCHalfZRange = false; this.hasOriginBottomLeft = true; this._renderTargetWrapperCache = new Array(); this._compiledEffects = {}; this._isDisposed = false; this.scenes = []; this._virtualScenes = new Array(); this.onBeforeTextureInitObservable = new Observable(); this.renderEvenInBackground = true; this.preventCacheWipeBetweenFrames = false; this._frameHandler = 0; this._activeRenderLoops = new Array(); this._windowIsBackground = false; this._boundRenderFunction = (timestamp) => this._renderLoop(timestamp); this._lastFrameTime = 0; this._renderAccumulator = 0; this.skipFrameRender = false; this.onBeforeShaderCompilationObservable = new Observable(); this.onAfterShaderCompilationObservable = new Observable(); this.onBeginFrameObservable = new Observable(); this.onEndFrameObservable = new Observable(); this._transformTextureUrl = null; this._uniformBuffers = new Array(); this._storageBuffers = new Array(); this._highPrecisionShadersAllowed = true; this.onContextLostObservable = new Observable(); this.onContextRestoredObservable = new Observable(); this._name = ""; this.premultipliedAlpha = true; this.adaptToDeviceRatio = false; this._lastDevicePixelRatio = 1; this._doNotHandleContextLost = false; this.cullBackFaces = null; this._renderPassNames = ["main"]; this._fps = 60; this._deltaTime = 0; this._deterministicLockstep = false; this._lockstepMaxSteps = 4; this._timeStep = 1 / 60; this.onDisposeObservable = new Observable(); this.onReleaseEffectsObservable = new Observable(); EngineStore.Instances.push(this); this.startTime = PrecisionDate.Now; this._stencilStateComposer.stencilGlobal = this._stencilState; PerformanceConfigurator.SetMatrixPrecision(!!options.useLargeWorldRendering || !!options.useHighPrecisionMatrix); if (IsNavigatorAvailable() && navigator.userAgent) { this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent); this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); } this.adaptToDeviceRatio = adaptToDeviceRatio ?? false; options.antialias = antialias ?? options.antialias; options.deterministicLockstep = options.deterministicLockstep ?? false; options.lockstepMaxSteps = options.lockstepMaxSteps ?? 4; options.timeStep = options.timeStep ?? 1 / 60; options.stencil = options.stencil ?? true; this._audioContext = options.audioEngineOptions?.audioContext ?? null; this._audioDestination = options.audioEngineOptions?.audioDestination ?? null; this.premultipliedAlpha = options.premultipliedAlpha ?? true; this._doNotHandleContextLost = !!options.doNotHandleContextLost; this._isStencilEnable = options.stencil ? true : false; this.useExactSrgbConversions = options.useExactSrgbConversions ?? false; const devicePixelRatio = IsWindowObjectExist() ? window.devicePixelRatio || 1 : 1; const limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio; adaptToDeviceRatio = adaptToDeviceRatio || options.adaptToDeviceRatio || false; this._hardwareScalingLevel = adaptToDeviceRatio ? 1 / Math.min(limitDeviceRatio, devicePixelRatio) : 1; this._lastDevicePixelRatio = devicePixelRatio; this._creationOptions = options; } /** * Resize the view according to the canvas' size * @param forceSetSize true to force setting the sizes of the underlying canvas */ resize(forceSetSize = false) { let width; let height; if (this.adaptToDeviceRatio) { const devicePixelRatio = IsWindowObjectExist() ? window.devicePixelRatio || 1 : 1; const changeRatio = this._lastDevicePixelRatio / devicePixelRatio; this._lastDevicePixelRatio = devicePixelRatio; this._hardwareScalingLevel *= changeRatio; } if (IsWindowObjectExist() && IsDocumentAvailable()) { if (this._renderingCanvas) { const boundingRect = this._renderingCanvas.getBoundingClientRect?.(); width = this._renderingCanvas.clientWidth || boundingRect?.width || this._renderingCanvas.width * this._hardwareScalingLevel || 100; height = this._renderingCanvas.clientHeight || boundingRect?.height || this._renderingCanvas.height * this._hardwareScalingLevel || 100; } else { width = window.innerWidth; 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, forceSetSize); } /** * Force a specific size of the canvas * @param width defines the new canvas' width * @param height defines the new canvas' height * @param forceSetSize true to force setting the sizes of the underlying canvas * @returns true if the size was changed */ setSize(width, height, forceSetSize = false) { if (!this._renderingCanvas) { return false; } width = width | 0; height = height | 0; if (!forceSetSize && this._renderingCanvas.width === width && this._renderingCanvas.height === height) { return false; } this._renderingCanvas.width = width; this._renderingCanvas.height = height; if (this.scenes) { for (let index = 0; index < this.scenes.length; index++) { const scene = this.scenes[index]; for (let camIndex = 0; camIndex < scene.cameras.length; camIndex++) { const cam = scene.cameras[camIndex]; cam._currentRenderId = 0; } } if (this.onResizeObservable.hasObservers()) { this.onResizeObservable.notifyObservers(this); } } return true; } // eslint-disable-next-line jsdoc/require-returns-check /** * 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_BYTE by default) * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). * @returns the raw texture inside an InternalTexture */ createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type, creationFlags, useSRGBBuffer) { throw _WarnImport("engine.rawTexture"); } // eslint-disable-next-line jsdoc/require-returns-check /** * 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_BYTE) * @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 */ createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression) { throw _WarnImport("engine.rawTexture"); } // eslint-disable-next-line jsdoc/require-returns-check /** * 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) * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) * @returns a new raw 3D texture (stored in an InternalTexture) */ createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType, creationFlags) { throw _WarnImport("engine.rawTexture"); } // eslint-disable-next-line jsdoc/require-returns-check /** * 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) * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) * @returns a new raw 2D array texture (stored in an InternalTexture) */ createRawTexture2DArray(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType, creationFlags) { throw _WarnImport("engine.rawTexture"); } /** * Shared initialization across engines types. * @param canvas The canvas associated with this instance of the engine. */ _sharedInit(canvas) { this._renderingCanvas = canvas; } _setupMobileChecks() { if (!(navigator && navigator.userAgent)) { return; } this._checkForMobile = () => { const currentUa = navigator.userAgent; this.hostInformation.isMobile = currentUa.indexOf("Mobile") !== -1 || // Needed for iOS 13+ detection on iPad (inspired by solution from https://stackoverflow.com/questions/9038625/detect-if-device-is-ios) currentUa.indexOf("Mac") !== -1 && IsDocumentAvailable() && "ontouchend" in document; }; this._checkForMobile(); if (IsWindowObjectExist()) { window.addEventListener("resize", this._checkForMobile); } } /** * creates and returns a new video element * @param constraints video constraints * @returns video element */ // eslint-disable-next-line @typescript-eslint/no-unused-vars createVideoElement(constraints) { return document.createElement("video"); } /** * @internal */ _reportDrawCall(numDrawCalls = 1) { this._drawCalls?.addCount(numDrawCalls, false); } /** * Gets the current framerate * @returns a number representing the framerate */ getFps() { return this._fps; } /** * Gets the time spent between current and previous frame * @returns a number representing the delta time in ms */ getDeltaTime() { return this._deltaTime; } /** * Gets a boolean indicating that the engine is running in deterministic lock step mode * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep * @returns true if engine is in deterministic lock step mode */ isDeterministicLockStep() { return this._deterministicLockstep; } /** * Gets the max steps when engine is running in deterministic lock step * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#deterministic-lockstep * @returns the max steps */ getLockstepMaxSteps() { return this._lockstepMaxSteps; } /** * Returns the time in ms between steps when using deterministic lock step. * @returns time step in (ms) */ getTimeStep() { return this._timeStep * 1e3; } /** * Engine abstraction for loading and creating an image bitmap from a given source string. * @param imageSource source to load the image from. * @param options An object that sets options for the image's extraction. */ // eslint-disable-next-line @typescript-eslint/promise-function-async _createImageBitmapFromSource(imageSource, options) { throw new Error("createImageBitmapFromSource is not implemented"); } /** * Engine abstraction for createImageBitmap * @param image source for image * @param options An object that sets options for the image's extraction. * @returns ImageBitmap */ // eslint-disable-next-line @typescript-eslint/promise-function-async createImageBitmap(image, options) { return createImageBitmap(image, options); } /** * Resize an image and returns the image data as an uint8array * @param image image to resize * @param bufferWidth destination buffer width * @param bufferHeight destination buffer height */ resizeImageBitmap(image, bufferWidth, bufferHeight) { throw new Error("resizeImageBitmap is not implemented"); } /** * Get Font size information * @param font font name */ getFontOffset(font) { throw new Error("getFontOffset is not implemented"); } static _CreateCanvas(width, height) { if (typeof document === "undefined") { return new OffscreenCanvas(width, height); } const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; return canvas; } /** * Create a canvas. This method is overridden by other engines * @param width width * @param height height * @returns ICanvas interface */ createCanvas(width, height) { return _AbstractEngine._CreateCanvas(width, height); } /** * 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 * @param imageBitmapOptions optional the options to use when creating an ImageBitmap * @param engine the engine instance to use * @returns the HTMLImageElement of the loaded image * @internal */ static _FileToolsLoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions, engine) { throw _WarnImport("FileTools"); } /** * @internal */ _loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) { const request = _LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError); this._activeRequests.push(request); request.onCompleteObservable.add(() => { const index = this._activeRequests.indexOf(request); if (index !== -1) { this._activeRequests.splice(index, 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 * @internal */ static _FileToolsLoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) { if (EngineFunctionContext.loadFile) { return EngineFunctionContext.loadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError); } throw _WarnImport("FileTools"); } /** * Dispose and release all associated resources */ dispose() { this.releaseEffects(); this._isDisposed = true; this.stopRenderLoop(); if (this._emptyTexture) { this._releaseTexture(this._emptyTexture); this._emptyTexture = null; } if (this._emptyCubeTexture) { this._releaseTexture(this._emptyCubeTexture); this._emptyCubeTexture = null; } this._renderingCanvas = null; if (this.onBeforeTextureInitObservable) { this.onBeforeTextureInitObservable.clear(); } while (this.postProcesses.length) { this.postProcesses[0].dispose(); } while (this.scenes.length) { this.scenes[0].dispose(); } while (this._virtualScenes.length) { this._virtualScenes[0].dispose(); } this.releaseComputeEffects?.(); Effect.ResetCache(); for (const request of this._activeRequests) { request.abort(); } this._boundRenderFunction = null; this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); this.onResizeObservable.clear(); this.onCanvasBlurObservable.clear(); this.onCanvasFocusObservable.clear(); this.onCanvasPointerOutObservable.clear(); this.onNewSceneAddedObservable.clear(); this.onEffectErrorObservable.clear(); if (IsWindowObjectExist()) { window.removeEventListener("resize", this._checkForMobile); } const index = EngineStore.Instances.indexOf(this); if (index >= 0) { EngineStore.Instances.splice(index, 1); } if (!EngineStore.Instances.length) { EngineStore.OnEnginesDisposedObservable.notifyObservers(this); EngineStore.OnEnginesDisposedObservable.clear(); } this.onBeginFrameObservable.clear(); this.onEndFrameObservable.clear(); } /** * Method called to create the default loading screen. * This can be overridden in your own app. * @param canvas The rendering canvas element */ // eslint-disable-next-line @typescript-eslint/no-unused-vars static DefaultLoadingScreenFactory(canvas) { throw _WarnImport("LoadingScreen"); } /** * 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 */ static MarkAllMaterialsAsDirty(flag, predicate) { for (let engineIndex = 0; engineIndex < EngineStore.Instances.length; engineIndex++) { const engine = EngineStore.Instances[engineIndex]; for (let sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) { engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate); } } } }; AbstractEngine._RenderPassIdCounter = 0; AbstractEngine._RescalePostProcessFactory = null; AbstractEngine.CollisionsEpsilon = 1e-3; AbstractEngine.QueueNewFrame = QueueNewFrame; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/fileTools.js function DecodeBase64UrlToBinary(uri) { return DecodeBase64ToBinary(uri.split(",")[1]); } var Base64DataUrlRegEx, LoadFileError, RequestFileError, ReadFileError, CleanUrl, FileToolsOptions, SetCorsBehavior, LoadImageConfiguration, LoadImage, ReadFile, LoadFile, RequestFile, GetMimeType, IsFileURL, IsBase64DataUrl, TestBase64DataUrl, DecodeBase64UrlToString, initSideEffects, FileTools, _injectLTSFileTools; var init_fileTools = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/fileTools.js"() { init_webRequest(); init_domManagement(); init_observable(); init_filesInputStore(); init_retryStrategy(); init_error(); init_stringTools(); init_shaderProcessor(); init_engineStore(); init_logger(); init_timingTools(); init_abstractEngine_functions(); init_abstractEngine(); Base64DataUrlRegEx = new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i); LoadFileError = class _LoadFileError extends RuntimeError { static { __name(this, "LoadFileError"); } /** * Creates a new LoadFileError * @param message defines the message of the error * @param object defines the optional web request */ constructor(message, object) { super(message, ErrorCodes.LoadFileError); this.name = "LoadFileError"; BaseError._setPrototypeOf(this, _LoadFileError.prototype); if (object instanceof WebRequest) { this.request = object; } else { this.file = object; } } }; RequestFileError = class _RequestFileError extends RuntimeError { static { __name(this, "RequestFileError"); } /** * Creates a new LoadFileError * @param message defines the message of the error * @param request defines the optional web request */ constructor(message, request) { super(message, ErrorCodes.RequestFileError); this.request = request; this.name = "RequestFileError"; BaseError._setPrototypeOf(this, _RequestFileError.prototype); } }; ReadFileError = class _ReadFileError extends RuntimeError { static { __name(this, "ReadFileError"); } /** * Creates a new ReadFileError * @param message defines the message of the error * @param file defines the optional file */ constructor(message, file) { super(message, ErrorCodes.ReadFileError); this.file = file; this.name = "ReadFileError"; BaseError._setPrototypeOf(this, _ReadFileError.prototype); } }; CleanUrl = /* @__PURE__ */ __name((url) => { url = url.replace(/#/gm, "%23"); return url; }, "CleanUrl"); FileToolsOptions = { /** * Gets or sets the retry strategy to apply when an error happens while loading an asset. * When defining this function, return the wait time before trying again or return -1 to * stop retrying and error out. */ DefaultRetryStrategy: RetryStrategy.ExponentialBackoff(), /** * Gets or sets the base URL to use to load assets */ BaseUrl: "", /** * Default behaviour for cors in the application. * It can be a string if the expected behavior is identical in the entire app. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance) */ CorsBehavior: "anonymous", /** * Gets or sets a function used to pre-process url before using them to load assets * @param url * @returns the processed url */ PreprocessUrl: /* @__PURE__ */ __name((url) => url, "PreprocessUrl"), /** * Gets or sets the base URL to use to load scripts * Used for both JS and WASM */ ScriptBaseUrl: "", /** * Gets or sets a function used to pre-process script url before using them to load. * Used for both JS and WASM * @param url defines the url to process * @returns the processed url */ ScriptPreprocessUrl: /* @__PURE__ */ __name((url) => url, "ScriptPreprocessUrl"), /** * Gets or sets a function used to clean the url before using it to load assets * @param url defines the url to clean * @returns the cleaned url */ CleanUrl }; SetCorsBehavior = /* @__PURE__ */ __name((url, element) => { if (url && url.indexOf("data:") === 0) { return; } if (FileToolsOptions.CorsBehavior) { if (typeof FileToolsOptions.CorsBehavior === "string" || FileToolsOptions.CorsBehavior instanceof String) { element.crossOrigin = FileToolsOptions.CorsBehavior; } else { const result = FileToolsOptions.CorsBehavior(url); if (result) { element.crossOrigin = result; } } } }, "SetCorsBehavior"); LoadImageConfiguration = { getRequiredSize: null }; LoadImage = /* @__PURE__ */ __name((input, onLoad, onError, offlineProvider, mimeType = "", imageBitmapOptions, engine = EngineStore.LastCreatedEngine) => { if (typeof HTMLImageElement === "undefined" && !engine?._features.forceBitmapOverHTMLImageElement) { onError("LoadImage is only supported in web or BabylonNative environments."); return null; } let url; let usingObjectURL = false; if (input instanceof ArrayBuffer || ArrayBuffer.isView(input)) { if (typeof Blob !== "undefined" && typeof URL !== "undefined") { url = URL.createObjectURL(new Blob([input], { type: mimeType })); usingObjectURL = true; } else { url = `data:${mimeType};base64,` + EncodeArrayBufferToBase64(input); } } else if (input instanceof Blob) { url = URL.createObjectURL(input); usingObjectURL = true; } else { url = FileToolsOptions.CleanUrl(input); url = FileToolsOptions.PreprocessUrl(url); } const onErrorHandler = /* @__PURE__ */ __name((exception) => { if (onError) { const inputText = url || input.toString(); onError(`Error while trying to load image: ${inputText.indexOf("http") === 0 || inputText.length <= 128 ? inputText : inputText.slice(0, 128) + "..."}`, exception); } }, "onErrorHandler"); if (engine?._features.forceBitmapOverHTMLImageElement) { LoadFile(url, (data) => { engine.createImageBitmap(new Blob([data], { type: mimeType }), { premultiplyAlpha: "none", ...imageBitmapOptions }).then((imgBmp) => { onLoad(imgBmp); if (usingObjectURL) { URL.revokeObjectURL(url); } }).catch((reason) => { if (onError) { onError("Error while trying to load image: " + input, reason); } }); }, void 0, offlineProvider || void 0, true, (request, exception) => { onErrorHandler(exception); }); return null; } const img = new Image(); if (LoadImageConfiguration.getRequiredSize) { const size = LoadImageConfiguration.getRequiredSize(input); if (size.width) { img.width = size.width; } if (size.height) { img.height = size.height; } } SetCorsBehavior(url, img); const handlersList = []; const loadHandlersList = /* @__PURE__ */ __name(() => { for (const handler of handlersList) { handler.target.addEventListener(handler.name, handler.handler); } }, "loadHandlersList"); const unloadHandlersList = /* @__PURE__ */ __name(() => { for (const handler of handlersList) { handler.target.removeEventListener(handler.name, handler.handler); } handlersList.length = 0; }, "unloadHandlersList"); const loadHandler = /* @__PURE__ */ __name(() => { unloadHandlersList(); onLoad(img); if (usingObjectURL && img.src) { URL.revokeObjectURL(img.src); } }, "loadHandler"); const errorHandler = /* @__PURE__ */ __name((err) => { unloadHandlersList(); onErrorHandler(err); if (usingObjectURL && img.src) { URL.revokeObjectURL(img.src); } }, "errorHandler"); const cspHandler = /* @__PURE__ */ __name((err) => { if (err.blockedURI !== img.src || err.disposition === "report") { return; } unloadHandlersList(); const cspException = new Error(`CSP violation of policy ${err.effectiveDirective} ${err.blockedURI}. Current policy is ${err.originalPolicy}`); EngineStore.UseFallbackTexture = false; onErrorHandler(cspException); if (usingObjectURL && img.src) { URL.revokeObjectURL(img.src); } img.src = ""; }, "cspHandler"); handlersList.push({ target: img, name: "load", handler: loadHandler }); handlersList.push({ target: img, name: "error", handler: errorHandler }); handlersList.push({ target: document, name: "securitypolicyviolation", handler: cspHandler }); loadHandlersList(); const fromBlob = url.substring(0, 5) === "blob:"; const fromData = url.substring(0, 5) === "data:"; const noOfflineSupport = /* @__PURE__ */ __name(() => { if (fromBlob || fromData || !WebRequest.IsCustomRequestAvailable) { img.src = url; } else { LoadFile(url, (data, _, contentType) => { const type = !mimeType && contentType ? contentType : mimeType; const blob = new Blob([data], { type }); const url2 = URL.createObjectURL(blob); usingObjectURL = true; img.src = url2; }, void 0, offlineProvider || void 0, true, (_request, exception) => { onErrorHandler(exception); }); } }, "noOfflineSupport"); const loadFromOfflineSupport = /* @__PURE__ */ __name(() => { if (offlineProvider) { offlineProvider.loadImage(url, img); } }, "loadFromOfflineSupport"); if (!fromBlob && !fromData && offlineProvider && offlineProvider.enableTexturesOffline) { offlineProvider.open(loadFromOfflineSupport, noOfflineSupport); } else { if (url.indexOf("file:") !== -1) { const textureName = decodeURIComponent(url.substring(5).toLowerCase()); if (FilesInputStore.FilesToLoad[textureName] && typeof URL !== "undefined") { try { let blobURL; try { blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]); } catch (ex) { blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]); } img.src = blobURL; usingObjectURL = true; } catch (e) { img.src = ""; } return img; } } noOfflineSupport(); } return img; }, "LoadImage"); ReadFile = /* @__PURE__ */ __name((file, onSuccess, onProgress, useArrayBuffer, onError) => { const reader = new FileReader(); const fileRequest = { onCompleteObservable: new Observable(), abort: /* @__PURE__ */ __name(() => reader.abort(), "abort") }; reader.onloadend = () => fileRequest.onCompleteObservable.notifyObservers(fileRequest); if (onError) { reader.onerror = () => { onError(new ReadFileError(`Unable to read ${file.name}`, file)); }; } reader.onload = (e) => { onSuccess(e.target["result"]); }; if (onProgress) { reader.onprogress = onProgress; } if (!useArrayBuffer) { reader.readAsText(file); } else { reader.readAsArrayBuffer(file); } return fileRequest; }, "ReadFile"); LoadFile = /* @__PURE__ */ __name((fileOrUrl, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, onOpened) => { if (fileOrUrl.name) { return ReadFile(fileOrUrl, onSuccess, onProgress, useArrayBuffer, onError ? (error) => { onError(void 0, error); } : void 0); } const url = fileOrUrl; if (url.indexOf("file:") !== -1) { let fileName = decodeURIComponent(url.substring(5).toLowerCase()); if (fileName.indexOf("./") === 0) { fileName = fileName.substring(2); } const file = FilesInputStore.FilesToLoad[fileName]; if (file) { return ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError ? (error) => onError(void 0, new LoadFileError(error.message, error.file)) : void 0); } } const { match, type } = TestBase64DataUrl(url); if (match) { const fileRequest = { onCompleteObservable: new Observable(), abort: /* @__PURE__ */ __name(() => () => { }, "abort") }; try { const data = useArrayBuffer ? DecodeBase64UrlToBinary(url) : DecodeBase64UrlToString(url); onSuccess(data, void 0, type); } catch (error) { if (onError) { onError(void 0, error); } else { Logger.Error(error.message || "Failed to parse the Data URL"); } } TimingTools.SetImmediate(() => { fileRequest.onCompleteObservable.notifyObservers(fileRequest); }); return fileRequest; } return RequestFile(url, (data, request) => { onSuccess(data, request?.responseURL, request?.getResponseHeader("content-type")); }, onProgress, offlineProvider, useArrayBuffer, onError ? (error) => { onError(error.request, new LoadFileError(error.message, error.request)); } : void 0, onOpened); }, "LoadFile"); RequestFile = /* @__PURE__ */ __name((url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError, onOpened) => { if (offlineProvider !== null) { offlineProvider ?? (offlineProvider = EngineStore.LastCreatedScene?.offlineProvider); } url = FileToolsOptions.CleanUrl(url); url = FileToolsOptions.PreprocessUrl(url); const loadUrl = FileToolsOptions.BaseUrl + url; let aborted = false; const fileRequest = { onCompleteObservable: new Observable(), abort: /* @__PURE__ */ __name(() => aborted = true, "abort") }; const requestFile = /* @__PURE__ */ __name(() => { let request = new WebRequest(); let retryHandle = null; let onReadyStateChange; const unbindEvents = /* @__PURE__ */ __name(() => { if (!request) { return; } if (onProgress) { request.removeEventListener("progress", onProgress); } if (onReadyStateChange) { request.removeEventListener("readystatechange", onReadyStateChange); } request.removeEventListener("loadend", onLoadEnd); }, "unbindEvents"); let onLoadEnd = /* @__PURE__ */ __name(() => { unbindEvents(); fileRequest.onCompleteObservable.notifyObservers(fileRequest); fileRequest.onCompleteObservable.clear(); onProgress = void 0; onReadyStateChange = null; onLoadEnd = null; onError = void 0; onOpened = void 0; onSuccess = void 0; }, "onLoadEnd"); fileRequest.abort = () => { aborted = true; if (onLoadEnd) { onLoadEnd(); } if (request && request.readyState !== (XMLHttpRequest.DONE || 4)) { request.abort(); } if (retryHandle !== null) { clearTimeout(retryHandle); retryHandle = null; } request = null; }; const handleError = /* @__PURE__ */ __name((error) => { const message = error.message || "Unknown error"; if (onError && request) { onError(new RequestFileError(message, request)); } else { Logger.Error(message); } }, "handleError"); const retryLoop = /* @__PURE__ */ __name((retryIndex) => { if (!request) { return; } request.open("GET", loadUrl); if (onOpened) { try { onOpened(request); } catch (e) { handleError(e); return; } } if (useArrayBuffer) { request.responseType = "arraybuffer"; } if (onProgress) { request.addEventListener("progress", onProgress); } if (onLoadEnd) { request.addEventListener("loadend", onLoadEnd); } onReadyStateChange = /* @__PURE__ */ __name(() => { if (aborted || !request) { return; } if (request.readyState === (XMLHttpRequest.DONE || 4)) { if (onReadyStateChange) { request.removeEventListener("readystatechange", onReadyStateChange); } if (request.status >= 200 && request.status < 300 || request.status === 0 && (!IsWindowObjectExist() || IsFileURL())) { const data = useArrayBuffer ? request.response : request.responseText; if (data !== null) { try { if (onSuccess) { onSuccess(data, request); } } catch (e) { handleError(e); } return; } } const retryStrategy = FileToolsOptions.DefaultRetryStrategy; if (retryStrategy) { const waitTime = retryStrategy(loadUrl, request, retryIndex); if (waitTime !== -1) { unbindEvents(); request = new WebRequest(); retryHandle = setTimeout(() => retryLoop(retryIndex + 1), waitTime); return; } } const error = new RequestFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request); if (onError) { onError(error); } } }, "onReadyStateChange"); request.addEventListener("readystatechange", onReadyStateChange); request.send(); }, "retryLoop"); retryLoop(0); }, "requestFile"); if (offlineProvider && offlineProvider.enableSceneOffline && !url.startsWith("blob:")) { const noOfflineSupport = /* @__PURE__ */ __name((request) => { if (request && request.status > 400) { if (onError) { onError(request); } } else { requestFile(); } }, "noOfflineSupport"); const loadFromOfflineSupport = /* @__PURE__ */ __name(() => { if (offlineProvider) { offlineProvider.loadFile(FileToolsOptions.BaseUrl + url, (data) => { if (!aborted && onSuccess) { onSuccess(data); } fileRequest.onCompleteObservable.notifyObservers(fileRequest); }, onProgress ? (event) => { if (!aborted && onProgress) { onProgress(event); } } : void 0, noOfflineSupport, useArrayBuffer); } }, "loadFromOfflineSupport"); offlineProvider.open(loadFromOfflineSupport, noOfflineSupport); } else { requestFile(); } return fileRequest; }, "RequestFile"); GetMimeType = /* @__PURE__ */ __name((url) => { const { match, type } = TestBase64DataUrl(url); if (match) { return type || void 0; } const lastDot = url.lastIndexOf("."); const extension = url.substring(lastDot + 1).toLowerCase(); switch (extension) { case "glb": return "model/gltf-binary"; case "bin": return "application/octet-stream"; case "gltf": return "model/gltf+json"; case "jpg": case "jpeg": return "image/jpeg"; case "png": return "image/png"; case "webp": return "image/webp"; case "ktx": return "image/ktx"; case "ktx2": return "image/ktx2"; case "avif": return "image/avif"; default: return void 0; } }, "GetMimeType"); IsFileURL = /* @__PURE__ */ __name(() => { return typeof location !== "undefined" && location.protocol === "file:"; }, "IsFileURL"); IsBase64DataUrl = /* @__PURE__ */ __name((uri) => { return Base64DataUrlRegEx.test(uri); }, "IsBase64DataUrl"); TestBase64DataUrl = /* @__PURE__ */ __name((uri) => { const results = Base64DataUrlRegEx.exec(uri); if (results === null || results.length === 0) { return { match: false, type: "" }; } else { const type = results[0].replace("data:", "").replace(";base64,", ""); return { match: true, type }; } }, "TestBase64DataUrl"); __name(DecodeBase64UrlToBinary, "DecodeBase64UrlToBinary"); DecodeBase64UrlToString = /* @__PURE__ */ __name((uri) => { return DecodeBase64ToString(uri.split(",")[1]); }, "DecodeBase64UrlToString"); initSideEffects = /* @__PURE__ */ __name(() => { AbstractEngine._FileToolsLoadImage = LoadImage; EngineFunctionContext.loadFile = LoadFile; _FunctionContainer.loadFile = LoadFile; }, "initSideEffects"); initSideEffects(); _injectLTSFileTools = /* @__PURE__ */ __name((DecodeBase64UrlToBinary2, DecodeBase64UrlToString2, FileToolsOptions2, IsBase64DataUrl2, IsFileURL2, LoadFile2, LoadImage2, ReadFile2, RequestFile2, SetCorsBehavior2) => { FileTools = { DecodeBase64UrlToBinary: DecodeBase64UrlToBinary2, DecodeBase64UrlToString: DecodeBase64UrlToString2, DefaultRetryStrategy: FileToolsOptions2.DefaultRetryStrategy, BaseUrl: FileToolsOptions2.BaseUrl, CorsBehavior: FileToolsOptions2.CorsBehavior, PreprocessUrl: FileToolsOptions2.PreprocessUrl, IsBase64DataUrl: IsBase64DataUrl2, IsFileURL: IsFileURL2, LoadFile: LoadFile2, LoadImage: LoadImage2, ReadFile: ReadFile2, RequestFile: RequestFile2, SetCorsBehavior: SetCorsBehavior2 }; Object.defineProperty(FileTools, "DefaultRetryStrategy", { get: /* @__PURE__ */ __name(function() { return FileToolsOptions2.DefaultRetryStrategy; }, "get"), set: /* @__PURE__ */ __name(function(value) { FileToolsOptions2.DefaultRetryStrategy = value; }, "set") }); Object.defineProperty(FileTools, "BaseUrl", { get: /* @__PURE__ */ __name(function() { return FileToolsOptions2.BaseUrl; }, "get"), set: /* @__PURE__ */ __name(function(value) { FileToolsOptions2.BaseUrl = value; }, "set") }); Object.defineProperty(FileTools, "PreprocessUrl", { get: /* @__PURE__ */ __name(function() { return FileToolsOptions2.PreprocessUrl; }, "get"), set: /* @__PURE__ */ __name(function(value) { FileToolsOptions2.PreprocessUrl = value; }, "set") }); Object.defineProperty(FileTools, "CorsBehavior", { get: /* @__PURE__ */ __name(function() { return FileToolsOptions2.CorsBehavior; }, "get"), set: /* @__PURE__ */ __name(function(value) { FileToolsOptions2.CorsBehavior = value; }, "set") }); }, "_injectLTSFileTools"); _injectLTSFileTools(DecodeBase64UrlToBinary, DecodeBase64UrlToString, FileToolsOptions, IsBase64DataUrl, IsFileURL, LoadFile, LoadImage, ReadFile, RequestFile, SetCorsBehavior); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tools.js function className(name260, module2) { return (target) => { target["__bjsclassName__"] = name260; target["__bjsmoduleName__"] = module2 != null ? module2 : null; }; } var Tools, AsyncLoop; var init_tools = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/tools.js"() { init_observable(); init_domManagement(); init_logger(); init_deepCopier(); init_precisionDate(); init_devTools(); init_webRequest(); init_engineStore(); init_fileTools(); init_timingTools(); init_instantiationTools(); init_guid(); init_tools_functions(); Tools = class _Tools { static { __name(this, "Tools"); } /** * Gets or sets the base URL to use to load assets */ static get BaseUrl() { return FileToolsOptions.BaseUrl; } static set BaseUrl(value) { FileToolsOptions.BaseUrl = value; } /** * Gets or sets the clean URL function to use to load assets */ static get CleanUrl() { return FileToolsOptions.CleanUrl; } static set CleanUrl(value) { FileToolsOptions.CleanUrl = value; } /** * This function checks whether a URL is absolute or not. * It will also detect data and blob URLs * @param url the url to check * @returns is the url absolute or relative */ static IsAbsoluteUrl(url) { if (url.indexOf("//") === 0) { return true; } if (url.indexOf("://") === -1) { return false; } if (url.indexOf(".") === -1) { return false; } if (url.indexOf("/") === -1) { return false; } if (url.indexOf(":") > url.indexOf("/")) { return false; } if (url.indexOf("://") < url.indexOf(".")) { return true; } if (url.indexOf("data:") === 0 || url.indexOf("blob:") === 0) { return true; } return false; } /** * Sets the base URL to use to load scripts */ static set ScriptBaseUrl(value) { FileToolsOptions.ScriptBaseUrl = value; } static get ScriptBaseUrl() { return FileToolsOptions.ScriptBaseUrl; } /** * Sets both the script base URL and the assets base URL to the same value. * Setter only! */ // eslint-disable-next-line @typescript-eslint/naming-convention static set CDNBaseUrl(value) { _Tools.ScriptBaseUrl = value; _Tools.AssetBaseUrl = value; } /** * Sets a preprocessing function to run on a source URL before importing it * Note that this function will execute AFTER the base URL is appended to the URL */ static set ScriptPreprocessUrl(func) { FileToolsOptions.ScriptPreprocessUrl = func; } static get ScriptPreprocessUrl() { return FileToolsOptions.ScriptPreprocessUrl; } /** * Gets or sets the retry strategy to apply when an error happens while loading an asset */ static get DefaultRetryStrategy() { return FileToolsOptions.DefaultRetryStrategy; } static set DefaultRetryStrategy(strategy) { FileToolsOptions.DefaultRetryStrategy = strategy; } /** * Default behavior for cors in the application. * It can be a string if the expected behavior is identical in the entire app. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance) */ static get CorsBehavior() { return FileToolsOptions.CorsBehavior; } static set CorsBehavior(value) { FileToolsOptions.CorsBehavior = value; } /** * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded * @ignorenaming */ static get UseFallbackTexture() { return EngineStore.UseFallbackTexture; } static set UseFallbackTexture(value) { EngineStore.UseFallbackTexture = value; } /** * Use this object to register external classes like custom textures or material * to allow the loaders to instantiate them */ static get RegisteredExternalClasses() { return InstantiationTools.RegisteredExternalClasses; } static set RegisteredExternalClasses(classes) { InstantiationTools.RegisteredExternalClasses = classes; } /** * Texture content used if a texture cannot loaded * @ignorenaming */ // eslint-disable-next-line @typescript-eslint/naming-convention static get fallbackTexture() { return EngineStore.FallbackTexture; } // eslint-disable-next-line @typescript-eslint/naming-convention static set fallbackTexture(value) { EngineStore.FallbackTexture = value; } /** * Read the content of a byte array at a specified coordinates (taking in account wrapping) * @param u defines the coordinate on X axis * @param v defines the coordinate on Y axis * @param width defines the width of the source data * @param height defines the height of the source data * @param pixels defines the source byte array * @param color defines the output color */ static FetchToRef(u, v, width, height, pixels, color) { const wrappedU = Math.abs(u) * width % width | 0; const wrappedV = Math.abs(v) * height % height | 0; const position = (wrappedU + wrappedV * width) * 4; color.r = pixels[position] / 255; color.g = pixels[position + 1] / 255; color.b = pixels[position + 2] / 255; color.a = pixels[position + 3] / 255; } /** * Interpolates between a and b via alpha * @param a The lower value (returned when alpha = 0) * @param b The upper value (returned when alpha = 1) * @param alpha The interpolation-factor * @returns The mixed value */ static Mix(a, b, alpha) { return 0; } /** * Tries to instantiate a new object from a given class name * @param className defines the class name to instantiate * @returns the new object or null if the system was not able to do the instantiation */ static Instantiate(className2) { return InstantiationTools.Instantiate(className2); } /** * Polyfill for setImmediate * @param action defines the action to execute after the current execution block */ static SetImmediate(action) { TimingTools.SetImmediate(action); } /** * Function indicating if a number is an exponent of 2 * @param value defines the value to test * @returns true if the value is an exponent of 2 */ static IsExponentOfTwo(value) { return true; } /** * Returns the nearest 32-bit single precision float representation of a Number * @param value A Number. If the parameter is of a different type, it will get converted * to a number or to NaN if it cannot be converted * @returns number */ static FloatRound(value) { return Math.fround(value); } /** * Extracts the filename from a path * @param path defines the path to use * @returns the filename */ static GetFilename(path) { const index = path.lastIndexOf("/"); if (index < 0) { return path; } return path.substring(index + 1); } /** * Extracts the "folder" part of a path (everything before the filename). * @param uri The URI to extract the info from * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present * @returns The "folder" part of the path */ static GetFolderPath(uri, returnUnchangedIfNoSlash = false) { const index = uri.lastIndexOf("/"); if (index < 0) { if (returnUnchangedIfNoSlash) { return uri; } return ""; } return uri.substring(0, index + 1); } /** * Convert an angle in radians to degrees * @param angle defines the angle to convert * @returns the angle in degrees */ static ToDegrees(angle) { return angle * 180 / Math.PI; } /** * Convert an angle in degrees to radians * @param angle defines the angle to convert * @returns the angle in radians */ static ToRadians(angle) { return angle * Math.PI / 180; } /** * Smooth angle changes (kind of low-pass filter), in particular for device orientation "shaking" * Use trigonometric functions to avoid discontinuity (0/360, -180/180) * @param previousAngle defines last angle value, in degrees * @param newAngle defines new angle value, in degrees * @param smoothFactor defines smoothing sensitivity; min 0: no smoothing, max 1: new data ignored * @returns the angle in degrees */ static SmoothAngleChange(previousAngle, newAngle, smoothFactor = 0.9) { const previousAngleRad = this.ToRadians(previousAngle); const newAngleRad = this.ToRadians(newAngle); return this.ToDegrees(Math.atan2((1 - smoothFactor) * Math.sin(newAngleRad) + smoothFactor * Math.sin(previousAngleRad), (1 - smoothFactor) * Math.cos(newAngleRad) + smoothFactor * Math.cos(previousAngleRad))); } /** * Returns an array if obj is not an array * @param obj defines the object to evaluate as an array * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined * @returns either obj directly if obj is an array or a new array containing obj */ static MakeArray(obj, allowsNullUndefined) { if (allowsNullUndefined !== true && (obj === void 0 || obj == null)) { return null; } return Array.isArray(obj) ? obj : [obj]; } /** * Gets the pointer prefix to use * @param engine defines the engine we are finding the prefix for * @returns "pointer" if touch is enabled. Else returns "mouse" */ static GetPointerPrefix(engine) { return IsWindowObjectExist() && !window.PointerEvent ? "mouse" : "pointer"; } /** * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element. * @param url define the url we are trying * @param element define the dom element where to configure the cors policy * @param element.crossOrigin */ static SetCorsBehavior(url, element) { SetCorsBehavior(url, element); } /** * Sets the referrerPolicy behavior on a dom element. * @param referrerPolicy define the referrer policy to use * @param element define the dom element where to configure the referrer policy * @param element.referrerPolicy */ static SetReferrerPolicyBehavior(referrerPolicy, element) { element.referrerPolicy = referrerPolicy; } // External files /** * Gets or sets a function used to pre-process url before using them to load assets */ static get PreprocessUrl() { return FileToolsOptions.PreprocessUrl; } static set PreprocessUrl(processor) { FileToolsOptions.PreprocessUrl = processor; } /** * 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 * @param imageBitmapOptions optional the options to use when creating an ImageBitmap * @returns the HTMLImageElement of the loaded image */ static LoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions) { return LoadImage(input, onLoad, onError, offlineProvider, mimeType, imageBitmapOptions); } /** * Loads a file from a url * @param url url string, ArrayBuffer, or Blob 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 */ static LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) { return LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError); } /** * Loads a file from a url * @param url the file url to load * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer * @returns a promise containing an ArrayBuffer corresponding to the loaded file */ static async LoadFileAsync(url, useArrayBuffer = true) { return await new Promise((resolve, reject) => { LoadFile(url, (data) => { resolve(data); }, void 0, void 0, useArrayBuffer, (request, exception) => { reject(exception); }); }); } /** * This function will convert asset URLs if the AssetBaseUrl parameter is set. * Any URL with `assets.babylonjs.com/core` will be replaced with the value of AssetBaseUrl. * @param url the URL to convert * @returns a new URL */ static GetAssetUrl(url) { if (!url) { return ""; } if (_Tools.AssetBaseUrl && url.startsWith(_Tools._DefaultAssetsUrl)) { const baseUrl = _Tools.AssetBaseUrl[_Tools.AssetBaseUrl.length - 1] === "/" ? _Tools.AssetBaseUrl.substring(0, _Tools.AssetBaseUrl.length - 1) : _Tools.AssetBaseUrl; return url.replace(_Tools._DefaultAssetsUrl, baseUrl); } return url; } /** * Get a script URL including preprocessing * @param scriptUrl the script Url to process * @param forceAbsoluteUrl force the script to be an absolute url (adding the current base url if necessary) * @returns a modified URL to use */ static GetBabylonScriptURL(scriptUrl, forceAbsoluteUrl) { if (!scriptUrl) { return ""; } if (_Tools.ScriptBaseUrl && scriptUrl.startsWith(_Tools._DefaultCdnUrl)) { const baseUrl = _Tools.ScriptBaseUrl[_Tools.ScriptBaseUrl.length - 1] === "/" ? _Tools.ScriptBaseUrl.substring(0, _Tools.ScriptBaseUrl.length - 1) : _Tools.ScriptBaseUrl; scriptUrl = scriptUrl.replace(_Tools._DefaultCdnUrl, baseUrl); } scriptUrl = _Tools.ScriptPreprocessUrl(scriptUrl); if (forceAbsoluteUrl && !_Tools.IsAbsoluteUrl(scriptUrl)) { scriptUrl = _Tools.GetAbsoluteUrl(scriptUrl); } return scriptUrl; } /** * This function is used internally by babylon components to load a script (identified by an url). When the url returns, the * content of this file is added into a new script element, attached to the DOM (body element) * @param scriptUrl defines the url of the script to load * @param onSuccess defines the callback called when the script is loaded * @param onError defines the callback to call if an error occurs * @param scriptId defines the id of the script element */ static LoadBabylonScript(scriptUrl, onSuccess, onError, scriptId) { scriptUrl = _Tools.GetBabylonScriptURL(scriptUrl); _Tools.LoadScript(scriptUrl, onSuccess, onError); } /** * Load an asynchronous script (identified by an url). When the url returns, the * content of this file is added into a new script element, attached to the DOM (body element) * @param scriptUrl defines the url of the script to laod * @returns a promise request object */ static async LoadBabylonScriptAsync(scriptUrl) { scriptUrl = _Tools.GetBabylonScriptURL(scriptUrl); return await _Tools.LoadScriptAsync(scriptUrl); } /** * This function is used internally by babylon components to load a script (identified by an url). When the url returns, the * content of this file is added into a new script element, attached to the DOM (body element) * @param scriptUrl defines the url of the script to load * @param onSuccess defines the callback called when the script is loaded * @param onError defines the callback to call if an error occurs * @param scriptId defines the id of the script element * @param useModule defines if we should use the module strategy to load the script */ static LoadScript(scriptUrl, onSuccess, onError, scriptId, useModule = false) { if (typeof importScripts === "function") { try { importScripts(scriptUrl); if (onSuccess) { onSuccess(); } } catch (e) { onError?.(`Unable to load script '${scriptUrl}' in worker`, e); } return; } else if (!IsWindowObjectExist()) { onError?.(`Cannot load script '${scriptUrl}' outside of a window or a worker`); return; } const head = document.getElementsByTagName("head")[0]; const script = document.createElement("script"); if (useModule) { script.setAttribute("type", "module"); script.innerText = scriptUrl; } else { script.setAttribute("type", "text/javascript"); script.setAttribute("src", scriptUrl); } if (scriptId) { script.id = scriptId; } script.onload = () => { if (onSuccess) { onSuccess(); } }; script.onerror = (e) => { if (onError) { onError(`Unable to load script '${scriptUrl}'`, e); } }; head.appendChild(script); } /** * Load an asynchronous script (identified by an url). When the url returns, the * content of this file is added into a new script element, attached to the DOM (body element) * @param scriptUrl defines the url of the script to load * @param scriptId defines the id of the script element * @returns a promise request object */ static async LoadScriptAsync(scriptUrl, scriptId) { return await new Promise((resolve, reject) => { this.LoadScript(scriptUrl, () => { resolve(); }, (message, exception) => { reject(exception || new Error(message)); }, scriptId); }); } /** * Loads a file from a blob * @param fileToLoad defines the blob to use * @param callback defines the callback to call when data is loaded * @param progressCallback defines the callback to call during loading process * @returns a file request object */ static ReadFileAsDataURL(fileToLoad, callback, progressCallback) { const reader = new FileReader(); const request = { onCompleteObservable: new Observable(), abort: /* @__PURE__ */ __name(() => reader.abort(), "abort") }; reader.onloadend = () => { request.onCompleteObservable.notifyObservers(request); }; reader.onload = (e) => { callback(e.target["result"]); }; reader.onprogress = progressCallback; reader.readAsDataURL(fileToLoad); return request; } /** * Reads a file from a File object * @param file defines the file to load * @param onSuccess defines the callback to call when data is loaded * @param onProgress defines the callback to call during loading process * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer * @param onError defines the callback to call when an error occurs * @returns a file request object */ static ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError) { return ReadFile(file, onSuccess, onProgress, useArrayBuffer, onError); } /** * Creates a data url from a given string content * @param content defines the content to convert * @returns the new data url link */ static FileAsURL(content) { const fileBlob = new Blob([content]); const url = window.URL; const link = url.createObjectURL(fileBlob); return link; } /** * Format the given number to a specific decimal format * @param value defines the number to format * @param decimals defines the number of decimals to use * @returns the formatted string */ static Format(value, decimals = 2) { return value.toFixed(decimals); } /** * Tries to copy an object by duplicating every property * @param source defines the source object * @param destination defines the target object * @param doNotCopyList defines a list of properties to avoid * @param mustCopyList defines a list of properties to copy (even if they start with _) */ static DeepCopy(source, destination, doNotCopyList, mustCopyList) { DeepCopier.DeepCopy(source, destination, doNotCopyList, mustCopyList); } /** * Gets a boolean indicating if the given object has no own property * @param obj defines the object to test * @returns true if object has no own property */ static IsEmpty(obj) { for (const i in obj) { if (Object.prototype.hasOwnProperty.call(obj, i)) { return false; } } return true; } /** * Function used to register events at window level * @param windowElement defines the Window object to use * @param events defines the events to register */ static RegisterTopRootEvents(windowElement, events) { for (let index = 0; index < events.length; index++) { const event = events[index]; windowElement.addEventListener(event.name, event.handler, false); try { if (window.parent) { window.parent.addEventListener(event.name, event.handler, false); } } catch (e) { } } } /** * Function used to unregister events from window level * @param windowElement defines the Window object to use * @param events defines the events to unregister */ static UnregisterTopRootEvents(windowElement, events) { for (let index = 0; index < events.length; index++) { const event = events[index]; windowElement.removeEventListener(event.name, event.handler); try { if (windowElement.parent) { windowElement.parent.removeEventListener(event.name, event.handler); } } catch (e) { } } } /** * Dumps the current bound framebuffer * @param width defines the rendering width * @param height defines the rendering height * @param engine defines the hosting engine * @param successCallback defines the callback triggered once the data are available * @param mimeType defines the mime type of the result * @param fileName defines the filename to download. If present, the result will automatically be downloaded * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. * @returns a void promise */ // Should end with Async but this is a breaking change // eslint-disable-next-line no-restricted-syntax, @typescript-eslint/require-await, @typescript-eslint/naming-convention static async DumpFramebuffer(width, height, engine, successCallback, mimeType = "image/png", fileName, quality) { throw _WarnImport("DumpTools"); } /** * Dumps an array buffer * @param width defines the rendering width * @param height defines the rendering height * @param data the data array * @param successCallback defines the callback triggered once the data are available * @param mimeType defines the mime type of the result * @param fileName defines the filename to download. If present, the result will automatically be downloaded * @param invertY true to invert the picture in the Y dimension * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. */ static DumpData(width, height, data, successCallback, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) { throw _WarnImport("DumpTools"); } // eslint-disable-next-line jsdoc/require-returns-check /** * Dumps an array buffer * @param width defines the rendering width * @param height defines the rendering height * @param data the data array * @param mimeType defines the mime type of the result * @param fileName defines the filename to download. If present, the result will automatically be downloaded * @param invertY true to invert the picture in the Y dimension * @param toArrayBuffer true to convert the data to an ArrayBuffer (encoded as `mimeType`) instead of a base64 string * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. * @returns a promise that resolve to the final data */ // eslint-disable-next-line no-restricted-syntax, @typescript-eslint/require-await static async DumpDataAsync(width, height, data, mimeType = "image/png", fileName, invertY = false, toArrayBuffer = false, quality) { throw _WarnImport("DumpTools"); } static _IsOffScreenCanvas(canvas) { return canvas.convertToBlob !== void 0; } /** * Converts the canvas data to blob. * This acts as a polyfill for browsers not supporting the to blob function. * @param canvas Defines the canvas to extract the data from (can be an offscreen canvas) * @param successCallback Defines the callback triggered once the data are available * @param mimeType Defines the mime type of the result * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. */ static ToBlob(canvas, successCallback, mimeType = "image/png", quality) { if (!_Tools._IsOffScreenCanvas(canvas) && !canvas.toBlob) { canvas.toBlob = function(callback, type, quality2) { setTimeout(() => { const binStr = atob(this.toDataURL(type, quality2).split(",")[1]), len = binStr.length, arr = new Uint8Array(len); for (let i = 0; i < len; i++) { arr[i] = binStr.charCodeAt(i); } callback(new Blob([arr])); }); }; } if (_Tools._IsOffScreenCanvas(canvas)) { canvas.convertToBlob({ type: mimeType, quality }).then((blob) => successCallback(blob)); } else { canvas.toBlob(function(blob) { successCallback(blob); }, mimeType, quality); } } /** * Download a Blob object * @param blob the Blob object * @param fileName the file name to download */ static DownloadBlob(blob, fileName) { if ("download" in document.createElement("a")) { if (!fileName) { const date = /* @__PURE__ */ new Date(); const stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ("0" + date.getMinutes()).slice(-2); fileName = "screenshot_" + stringDate + ".png"; } _Tools.Download(blob, fileName); } else { if (blob && typeof URL !== "undefined") { const url = URL.createObjectURL(blob); const newWindow = window.open(""); if (!newWindow) { return; } const img = newWindow.document.createElement("img"); img.onload = function() { URL.revokeObjectURL(url); }; img.src = url; newWindow.document.body.appendChild(img); } } } /** * Encodes the canvas data to base 64, or automatically downloads the result if `fileName` is defined. * @param canvas The canvas to get the data from, which can be an offscreen canvas. * @param successCallback The callback which is triggered once the data is available. If `fileName` is defined, the callback will be invoked after the download occurs, and the `data` argument will be an empty string. * @param mimeType The mime type of the result. * @param fileName The name of the file to download. If defined, the result will automatically be downloaded. If not defined, and `successCallback` is also not defined, the result will automatically be downloaded with an auto-generated file name. * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. */ static EncodeScreenshotCanvasData(canvas, successCallback, mimeType = "image/png", fileName, quality) { if (typeof fileName === "string" || !successCallback) { this.ToBlob(canvas, function(blob) { if (blob) { _Tools.DownloadBlob(blob, fileName); } if (successCallback) { successCallback(""); } }, mimeType, quality); } else if (successCallback) { if (_Tools._IsOffScreenCanvas(canvas)) { canvas.convertToBlob({ type: mimeType, quality }).then((blob) => { const reader = new FileReader(); reader.readAsDataURL(blob); reader.onloadend = () => { const base64data = reader.result; successCallback(base64data); }; }); return; } const base64Image = canvas.toDataURL(mimeType, quality); successCallback(base64Image); } } /** * Downloads a blob in the browser * @param blob defines the blob to download * @param fileName defines the name of the downloaded file */ static Download(blob, fileName) { if (typeof URL === "undefined") { return; } const url = window.URL.createObjectURL(blob); const a = document.createElement("a"); document.body.appendChild(a); a.style.display = "none"; a.href = url; a.download = fileName; a.addEventListener("click", () => { if (a.parentElement) { a.parentElement.removeChild(a); } }); a.click(); window.URL.revokeObjectURL(url); } /** * Will return the right value of the noPreventDefault variable * Needed to keep backwards compatibility to the old API. * * @param args arguments passed to the attachControl function * @returns the correct value for noPreventDefault */ static BackCompatCameraNoPreventDefault(args) { if (typeof args[0] === "boolean") { return args[0]; } else if (typeof args[1] === "boolean") { return args[1]; } return false; } /** * Captures a screenshot of the current rendering * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG * @param engine defines the rendering engine * @param camera defines the source camera * @param size This parameter can be set to a single number or to an object with the * following (optional) properties: precision, width, height. If a single number is passed, * it will be used for both width and height. If an object is passed, the screenshot size * will be derived from the parameters. The precision property is a multiplier allowing * rendering at a higher or lower resolution * @param successCallback defines the callback receives a single parameter which contains the * screenshot as a string of base64-encoded characters. This string can be assigned to the * src parameter of an to display it * @param mimeType defines the MIME type of the screenshot image (default: image/png). * Check your browser for supported MIME types * @param forceDownload force the system to download the image even if a successCallback is provided * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars static CreateScreenshot(engine, camera, size, successCallback, mimeType = "image/png", forceDownload = false, quality) { throw _WarnImport("ScreenshotTools"); } // eslint-disable-next-line jsdoc/require-returns-check /** * Captures a screenshot of the current rendering * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG * @param engine defines the rendering engine * @param camera defines the source camera * @param size This parameter can be set to a single number or to an object with the * following (optional) properties: precision, width, height. If a single number is passed, * it will be used for both width and height. If an object is passed, the screenshot size * will be derived from the parameters. The precision property is a multiplier allowing * rendering at a higher or lower resolution * @param mimeType defines the MIME type of the screenshot image (default: image/png). * Check your browser for supported MIME types * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. * @returns screenshot as a string of base64-encoded characters. This string can be assigned * to the src parameter of an to display it */ // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-restricted-syntax, @typescript-eslint/require-await static async CreateScreenshotAsync(engine, camera, size, mimeType = "image/png", quality) { throw _WarnImport("ScreenshotTools"); } /** * Generates an image screenshot from the specified camera. * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG * @param engine The engine to use for rendering * @param camera The camera to use for rendering * @param size This parameter can be set to a single number or to an object with the * following (optional) properties: precision, width, height. If a single number is passed, * it will be used for both width and height. If an object is passed, the screenshot size * will be derived from the parameters. The precision property is a multiplier allowing * rendering at a higher or lower resolution * @param successCallback The callback receives a single parameter which contains the * screenshot as a string of base64-encoded characters. This string can be assigned to the * src parameter of an to display it * @param mimeType The MIME type of the screenshot image (default: image/png). * Check your browser for supported MIME types * @param samples Texture samples (default: 1) * @param antialiasing Whether antialiasing should be turned on or not (default: false) * @param fileName A name for for the downloaded file. * @param renderSprites Whether the sprites should be rendered or not (default: false) * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false) * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true) * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. * @param customizeTexture An optional callback that can be used to modify the render target texture before taking the screenshot. This can be used, for instance, to enable camera post-processes before taking the screenshot. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars static CreateScreenshotUsingRenderTarget(engine, camera, size, successCallback, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality, customizeTexture) { throw _WarnImport("ScreenshotTools"); } // eslint-disable-next-line jsdoc/require-returns-check /** * Generates an image screenshot from the specified camera. * @see https://doc.babylonjs.com/features/featuresDeepDive/scene/renderToPNG * @param engine The engine to use for rendering * @param camera The camera to use for rendering * @param size This parameter can be set to a single number or to an object with the * following (optional) properties: precision, width, height. If a single number is passed, * it will be used for both width and height. If an object is passed, the screenshot size * will be derived from the parameters. The precision property is a multiplier allowing * rendering at a higher or lower resolution * @param mimeType The MIME type of the screenshot image (default: image/png). * Check your browser for supported MIME types * @param samples Texture samples (default: 1) * @param antialiasing Whether antialiasing should be turned on or not (default: false) * @param fileName A name for for the downloaded file. * @param renderSprites Whether the sprites should be rendered or not (default: false) * @param enableStencilBuffer Whether the stencil buffer should be enabled or not (default: false) * @param useLayerMask if the camera's layer mask should be used to filter what should be rendered (default: true) * @param quality The quality of the image if lossy mimeType is used (e.g. image/jpeg, image/webp). See {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob | HTMLCanvasElement.toBlob()}'s `quality` parameter. * @param customizeTexture An optional callback that can be used to modify the render target texture before taking the screenshot. This can be used, for instance, to enable camera post-processes before taking the screenshot. * @returns screenshot as a string of base64-encoded characters. This string can be assigned * to the src parameter of an to display it */ // eslint-disable-next-line @typescript-eslint/no-unused-vars, no-restricted-syntax, @typescript-eslint/require-await static async CreateScreenshotUsingRenderTargetAsync(engine, camera, size, mimeType = "image/png", samples = 1, antialiasing = false, fileName, renderSprites = false, enableStencilBuffer = false, useLayerMask = true, quality, customizeTexture) { throw _WarnImport("ScreenshotTools"); } /** * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 * Be aware Math.random() could cause collisions, but: * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide" * @returns a pseudo random id */ static RandomId() { return RandomGUID(); } /** * Test if the given uri is a base64 string * @deprecated Please use FileTools.IsBase64DataUrl instead. * @param uri The uri to test * @returns True if the uri is a base64 string or false otherwise */ static IsBase64(uri) { return IsBase64DataUrl(uri); } /** * Decode the given base64 uri. * @deprecated Please use FileTools.DecodeBase64UrlToBinary instead. * @param uri The uri to decode * @returns The decoded base64 data. */ static DecodeBase64(uri) { return DecodeBase64UrlToBinary(uri); } /** * Gets a value indicating the number of loading errors * @ignorenaming */ // eslint-disable-next-line @typescript-eslint/naming-convention static get errorsCount() { return Logger.errorsCount; } /** * Log a message to the console * @param message defines the message to log */ static Log(message) { Logger.Log(message); } /** * Write a warning message to the console * @param message defines the message to log */ static Warn(message) { Logger.Warn(message); } /** * Write an error message to the console * @param message defines the message to log */ static Error(message) { Logger.Error(message); } /** * Gets current log cache (list of logs) */ static get LogCache() { return Logger.LogCache; } /** * Clears the log cache */ static ClearLogCache() { Logger.ClearLogCache(); } /** * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel) */ static set LogLevels(level) { Logger.LogLevels = level; } /** * Sets the current performance log level */ static set PerformanceLogLevel(level) { if ((level & _Tools.PerformanceUserMarkLogLevel) === _Tools.PerformanceUserMarkLogLevel) { _Tools.StartPerformanceCounter = _Tools._StartUserMark; _Tools.EndPerformanceCounter = _Tools._EndUserMark; return; } if ((level & _Tools.PerformanceConsoleLogLevel) === _Tools.PerformanceConsoleLogLevel) { _Tools.StartPerformanceCounter = _Tools._StartPerformanceConsole; _Tools.EndPerformanceCounter = _Tools._EndPerformanceConsole; return; } _Tools.StartPerformanceCounter = _Tools._StartPerformanceCounterDisabled; _Tools.EndPerformanceCounter = _Tools._EndPerformanceCounterDisabled; } // eslint-disable-next-line @typescript-eslint/no-unused-vars static _StartPerformanceCounterDisabled(counterName, condition) { } // eslint-disable-next-line @typescript-eslint/no-unused-vars static _EndPerformanceCounterDisabled(counterName, condition) { } static _StartUserMark(counterName, condition = true) { if (!_Tools._Performance) { if (!IsWindowObjectExist()) { return; } _Tools._Performance = window.performance; } if (!condition || !_Tools._Performance.mark) { return; } _Tools._Performance.mark(counterName + "-Begin"); } static _EndUserMark(counterName, condition = true) { if (!condition || !_Tools._Performance.mark) { return; } _Tools._Performance.mark(counterName + "-End"); _Tools._Performance.measure(counterName, counterName + "-Begin", counterName + "-End"); } static _StartPerformanceConsole(counterName, condition = true) { if (!condition) { return; } _Tools._StartUserMark(counterName, condition); if (console.time) { console.time(counterName); } } static _EndPerformanceConsole(counterName, condition = true) { if (!condition) { return; } _Tools._EndUserMark(counterName, condition); console.timeEnd(counterName); } /** * Gets either window.performance.now() if supported or Date.now() else */ static get Now() { return PrecisionDate.Now; } /** * This method will return the name of the class used to create the instance of the given object. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator. * @param object the object to get the class name from * @param isType defines if the object is actually a type * @returns the name of the class, will be "object" for a custom data type not using the @className decorator */ static GetClassName(object, isType = false) { let name260 = null; if (!isType && object.getClassName) { name260 = object.getClassName(); } else { if (object instanceof Object) { const classObj = isType ? object : Object.getPrototypeOf(object); name260 = classObj.constructor["__bjsclassName__"]; } if (!name260) { name260 = typeof object; } } return name260; } /** * Gets the first element of an array satisfying a given predicate * @param array defines the array to browse * @param predicate defines the predicate to use * @returns null if not found or the element */ static First(array, predicate) { for (const el of array) { if (predicate(el)) { return el; } } return null; } /** * This method will return the name of the full name of the class, including its owning module (if any). * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified). * @param object the object to get the class name from * @param isType defines if the object is actually a type * @returns a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified. * @ignorenaming */ // eslint-disable-next-line @typescript-eslint/naming-convention static getFullClassName(object, isType = false) { let className2 = null; let moduleName = null; if (!isType && object.getClassName) { className2 = object.getClassName(); } else { if (object instanceof Object) { const classObj = isType ? object : Object.getPrototypeOf(object); className2 = classObj.constructor["__bjsclassName__"]; moduleName = classObj.constructor["__bjsmoduleName__"]; } if (!className2) { className2 = typeof object; } } if (!className2) { return null; } return (moduleName != null ? moduleName + "." : "") + className2; } /** * Returns a promise that resolves after the given amount of time. * @param delay Number of milliseconds to delay * @returns Promise that resolves after the given amount of time */ static async DelayAsync(delay) { await new Promise((resolve) => { setTimeout(() => { resolve(); }, delay); }); } /** * Utility function to detect if the current user agent is Safari * @returns whether or not the current user agent is safari */ static IsSafari() { if (!IsNavigatorAvailable()) { return false; } return /^((?!chrome|android).)*safari/i.test(navigator.userAgent); } }; Tools.AssetBaseUrl = ""; Tools.UseCustomRequestHeaders = false; Tools.CustomRequestHeaders = WebRequest.CustomRequestHeaders; Tools.GetDOMTextContent = GetDOMTextContent; Tools._DefaultCdnUrl = "https://cdn.babylonjs.com"; Tools._DefaultAssetsUrl = "https://assets.babylonjs.com/core"; Tools.GetAbsoluteUrl = typeof document === "object" ? (url) => { const a = document.createElement("a"); a.href = url; return a.href; } : typeof URL === "function" && typeof location === "object" ? (url) => new URL(url, location.origin).href : () => { throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context."); }; Tools.NoneLogLevel = Logger.NoneLogLevel; Tools.MessageLogLevel = Logger.MessageLogLevel; Tools.WarningLogLevel = Logger.WarningLogLevel; Tools.ErrorLogLevel = Logger.ErrorLogLevel; Tools.AllLogLevel = Logger.AllLogLevel; Tools.IsWindowObjectExist = IsWindowObjectExist; Tools.PerformanceNoneLogLevel = 0; Tools.PerformanceUserMarkLogLevel = 1; Tools.PerformanceConsoleLogLevel = 2; Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled; Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled; __name(className, "className"); AsyncLoop = class _AsyncLoop { static { __name(this, "AsyncLoop"); } /** * Constructor. * @param iterations the number of iterations. * @param func the function to run each iteration * @param successCallback the callback that will be called upon successful execution * @param offset starting offset. */ constructor(iterations, func, successCallback, offset = 0) { this.iterations = iterations; this.index = offset - 1; this._done = false; this._fn = func; this._successCallback = successCallback; } /** * Execute the next iteration. Must be called after the last iteration was finished. */ executeNext() { if (!this._done) { if (this.index + 1 < this.iterations) { ++this.index; this._fn(this); } else { this.breakLoop(); } } } /** * Break the loop and run the success callback. */ breakLoop() { this._done = true; this._successCallback(); } /** * Create and run an async loop. * @param iterations the number of iterations. * @param fn the function to run each iteration * @param successCallback the callback that will be called upon successful execution * @param offset starting offset. * @returns the created async loop object */ static Run(iterations, fn, successCallback, offset = 0) { const loop = new _AsyncLoop(iterations, fn, successCallback, offset); loop.executeNext(); return loop; } /** * A for-loop that will run a given number of iterations synchronous and the rest async. * @param iterations total number of iterations * @param syncedIterations number of synchronous iterations in each async iteration. * @param fn the function to call each iteration. * @param callback a success call back that will be called when iterating stops. * @param breakFunction a break condition (optional) * @param timeout timeout settings for the setTimeout function. default - 0. * @returns the created async loop object */ static SyncAsyncForLoop(iterations, syncedIterations, fn, callback, breakFunction, timeout = 0) { return _AsyncLoop.Run(Math.ceil(iterations / syncedIterations), (loop) => { if (breakFunction && breakFunction()) { loop.breakLoop(); } else { setTimeout(() => { for (let i = 0; i < syncedIterations; ++i) { const iteration = loop.index * syncedIterations + i; if (iteration >= iterations) { break; } fn(iteration); if (breakFunction && breakFunction()) { loop.breakLoop(); break; } } loop.executeNext(); }, timeout); } }, callback); } }; Tools.Mix = Mix; Tools.IsExponentOfTwo = IsExponentOfTwo; EngineStore.FallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z"; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/bitArray.js function GetByteIndex(bitIndex) { return Math.floor(bitIndex / 8); } function GetBitMask(bitIndex) { return 1 << bitIndex % 8; } var BitArray; var init_bitArray = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/bitArray.js"() { __name(GetByteIndex, "GetByteIndex"); __name(GetBitMask, "GetBitMask"); BitArray = class { static { __name(this, "BitArray"); } /** * Creates a new bit array with a fixed size. * @param size The number of bits to store. */ constructor(size) { this.size = size; this._byteArray = new Uint8Array(Math.ceil(this.size / 8)); } /** * Gets the current value at the specified index. * @param bitIndex The index to get the value from. * @returns The value at the specified index. */ get(bitIndex) { if (bitIndex >= this.size) { throw new RangeError("Bit index out of range"); } const byteIndex = GetByteIndex(bitIndex); const bitMask = GetBitMask(bitIndex); return (this._byteArray[byteIndex] & bitMask) !== 0; } /** * Sets the value at the specified index. * @param bitIndex The index to set the value at. * @param value The value to set. */ set(bitIndex, value) { if (bitIndex >= this.size) { throw new RangeError("Bit index out of range"); } const byteIndex = GetByteIndex(bitIndex); const bitMask = GetBitMask(bitIndex); if (value) { this._byteArray[byteIndex] |= bitMask; } else { this._byteArray[byteIndex] &= ~bitMask; } } }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/mesh.vertexData.functions.js var mesh_vertexData_functions_exports = {}; __export(mesh_vertexData_functions_exports, { OptimizeIndices: () => OptimizeIndices }); function OptimizeIndices(indices) { const faces = []; const faceCount = indices.length / 3; for (let i = 0; i < faceCount; i++) { faces.push([indices[i * 3], indices[i * 3 + 1], indices[i * 3 + 2]]); } const vertexToFaceMap = /* @__PURE__ */ new Map(); for (let faceIndex = 0; faceIndex < faces.length; faceIndex++) { const face = faces[faceIndex]; for (const vertex of face) { let face2 = vertexToFaceMap.get(vertex); if (!face2) { vertexToFaceMap.set(vertex, face2 = []); } face2.push(faceIndex); } } const visited = new BitArray(faceCount); const sortedFaces = []; const deepFirstSearchStack = /* @__PURE__ */ __name((startFaceIndex) => { const stack = [startFaceIndex]; while (stack.length > 0) { const currentFaceIndex = stack.pop(); if (visited.get(currentFaceIndex)) { continue; } visited.set(currentFaceIndex, true); sortedFaces.push(faces[currentFaceIndex]); for (const vertex of faces[currentFaceIndex]) { const neighbors = vertexToFaceMap.get(vertex); if (!neighbors) { return; } for (const neighborFaceIndex of neighbors) { if (!visited.get(neighborFaceIndex)) { stack.push(neighborFaceIndex); } } } } }, "deepFirstSearchStack"); for (let i = 0; i < faceCount; i++) { if (!visited.get(i)) { deepFirstSearchStack(i); } } let index = 0; for (const face of sortedFaces) { indices[index++] = face[0]; indices[index++] = face[1]; indices[index++] = face[2]; } } var init_mesh_vertexData_functions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/mesh.vertexData.functions.js"() { init_bitArray(); __name(OptimizeIndices, "OptimizeIndices"); } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/defaultUboDeclaration.js var name95, shader95, defaultUboDeclarationWGSL; var init_defaultUboDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/defaultUboDeclaration.js"() { init_shaderStore(); init_sceneUboDeclaration(); init_meshUboDeclaration(); name95 = "defaultUboDeclaration"; shader95 = `uniform diffuseLeftColor: vec4f;uniform diffuseRightColor: vec4f;uniform opacityParts: vec4f;uniform reflectionLeftColor: vec4f;uniform reflectionRightColor: vec4f;uniform refractionLeftColor: vec4f;uniform refractionRightColor: vec4f;uniform emissiveLeftColor: vec4f;uniform emissiveRightColor: vec4f;uniform vDiffuseInfos: vec2f;uniform vAmbientInfos: vec2f;uniform vOpacityInfos: vec2f;uniform vEmissiveInfos: vec2f;uniform vLightmapInfos: vec2f;uniform vSpecularInfos: vec2f;uniform vBumpInfos: vec3f;uniform diffuseMatrix: mat4x4f;uniform ambientMatrix: mat4x4f;uniform opacityMatrix: mat4x4f;uniform emissiveMatrix: mat4x4f;uniform lightmapMatrix: mat4x4f;uniform specularMatrix: mat4x4f;uniform bumpMatrix: mat4x4f;uniform vTangentSpaceParams: vec2f;uniform pointSize: f32;uniform alphaCutOff: f32;uniform refractionMatrix: mat4x4f;uniform vRefractionInfos: vec4f;uniform vRefractionPosition: vec3f;uniform vRefractionSize: vec3f;uniform vSpecularColor: vec4f;uniform vEmissiveColor: vec3f;uniform vDiffuseColor: vec4f;uniform vAmbientColor: vec3f;uniform cameraInfo: vec4f;uniform vReflectionInfos: vec2f;uniform reflectionMatrix: mat4x4f;uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f; #define ADDITIONAL_UBO_DECLARATION #include #include `; if (!ShaderStore.IncludesShadersStoreWGSL[name95]) { ShaderStore.IncludesShadersStoreWGSL[name95] = shader95; } defaultUboDeclarationWGSL = { name: name95, shader: shader95 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/uvAttributeDeclaration.js var name96, shader96, uvAttributeDeclarationWGSL; var init_uvAttributeDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/uvAttributeDeclaration.js"() { init_shaderStore(); name96 = "uvAttributeDeclaration"; shader96 = `#ifdef UV{X} attribute uv{X}: vec2f; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name96]) { ShaderStore.IncludesShadersStoreWGSL[name96] = shader96; } uvAttributeDeclarationWGSL = { name: name96, shader: shader96 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassVertexDeclaration.js var name97, shader97, prePassVertexDeclarationWGSL; var init_prePassVertexDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassVertexDeclaration.js"() { init_shaderStore(); name97 = "prePassVertexDeclaration"; shader97 = `#ifdef PREPASS #ifdef PREPASS_LOCAL_POSITION varying vPosition : vec3f; #endif #ifdef PREPASS_DEPTH varying vViewPos: vec3f; #endif #ifdef PREPASS_NORMALIZED_VIEW_DEPTH varying vNormViewDepth: f32; #endif #if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) uniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name97]) { ShaderStore.IncludesShadersStoreWGSL[name97] = shader97; } prePassVertexDeclarationWGSL = { name: name97, shader: shader97 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/mainUVVaryingDeclaration.js var name98, shader98, mainUVVaryingDeclarationWGSL; var init_mainUVVaryingDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/mainUVVaryingDeclaration.js"() { init_shaderStore(); name98 = "mainUVVaryingDeclaration"; shader98 = `#ifdef MAINUV{X} varying vMainUV{X}: vec2f; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name98]) { ShaderStore.IncludesShadersStoreWGSL[name98] = shader98; } mainUVVaryingDeclarationWGSL = { name: name98, shader: shader98 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/samplerVertexDeclaration.js var name99, shader99, samplerVertexDeclarationWGSL; var init_samplerVertexDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/samplerVertexDeclaration.js"() { init_shaderStore(); name99 = "samplerVertexDeclaration"; shader99 = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 varying v_VARYINGNAME_UV: vec2f; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name99]) { ShaderStore.IncludesShadersStoreWGSL[name99] = shader99; } samplerVertexDeclarationWGSL = { name: name99, shader: shader99 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpVertexDeclaration.js var name100, shader100, bumpVertexDeclarationWGSL; var init_bumpVertexDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpVertexDeclaration.js"() { init_shaderStore(); name100 = "bumpVertexDeclaration"; shader100 = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f; #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name100]) { ShaderStore.IncludesShadersStoreWGSL[name100] = shader100; } bumpVertexDeclarationWGSL = { name: name100, shader: shader100 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogVertexDeclaration.js var name101, shader101, fogVertexDeclarationWGSL; var init_fogVertexDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogVertexDeclaration.js"() { init_shaderStore(); name101 = "fogVertexDeclaration"; shader101 = `#ifdef FOG varying vFogDistance: vec3f; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name101]) { ShaderStore.IncludesShadersStoreWGSL[name101] = shader101; } fogVertexDeclarationWGSL = { name: name101, shader: shader101 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightVxFragmentDeclaration.js var name102, shader102, lightVxFragmentDeclarationWGSL; var init_lightVxFragmentDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightVxFragmentDeclaration.js"() { init_shaderStore(); name102 = "lightVxFragmentDeclaration"; shader102 = `#ifdef LIGHT{X} uniform vLightData{X}: vec4f;uniform vLightDiffuse{X}: vec4f; #ifdef SPECULARTERM uniform vLightSpecular{X}: vec4f; #else var vLightSpecular{X}: vec4f= vec4f(0.); #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform lightMatrix{X}: mat4x4f[SHADOWCSMNUM_CASCADES{X}];varying var vPositionFromLight{X}: vec4f[SHADOWCSMNUM_CASCADES{X}];varying var vDepthMetric{X}: f32[SHADOWCSMNUM_CASCADES{X}];varying var vPositionFromCamera{X}: vec4f; #elif defined(SHADOWCUBE{X}) #else varying var vPositionFromLight{X}: vec4f;varying var vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f; #endif uniform shadowsInfo{X}: vec4f;uniform depthValues{X}: vec2f; #endif #ifdef SPOTLIGHT{X} uniform vLightDirection{X}: vec4f;uniform vLightFalloff{X}: vec4f; #elif defined(POINTLIGHT{X}) uniform vLightFalloff{X}: vec4f; #elif defined(HEMILIGHT{X}) uniform vLightGround{X}: vec3f; #endif #if defined(AREALIGHT{X}) uniform vLightWidth{X}: vec4f;uniform vLightHeight{X}: vec4f; #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name102]) { ShaderStore.IncludesShadersStoreWGSL[name102] = shader102; } lightVxFragmentDeclarationWGSL = { name: name102, shader: shader102 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightVxUboDeclaration.js var name103, shader103, lightVxUboDeclarationWGSL; var init_lightVxUboDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightVxUboDeclaration.js"() { init_shaderStore(); name103 = "lightVxUboDeclaration"; shader103 = `#ifdef LIGHT{X} struct Light{X} {vLightData: vec4f, vLightDiffuse: vec4f, vLightSpecular: vec4f, #ifdef SPOTLIGHT{X} vLightDirection: vec4f, vLightFalloff: vec4f, #elif defined(POINTLIGHT{X}) vLightFalloff: vec4f, #elif defined(HEMILIGHT{X}) vLightGround: vec3f, #elif defined(CLUSTLIGHT{X}) vSliceData: vec2f, vSliceRanges: array, #endif #if defined(AREALIGHT{X}) vLightWidth: vec4f, vLightHeight: vec4f, #endif shadowsInfo: vec4f, depthValues: vec2f} ;var light{X} : Light{X}; #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform lightMatrix{X}: array;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f; #elif defined(SHADOWCUBE{X}) #else varying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32;uniform lightMatrix{X}: mat4x4f; #endif #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name103]) { ShaderStore.IncludesShadersStoreWGSL[name103] = shader103; } lightVxUboDeclarationWGSL = { name: name103, shader: shader103 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/logDepthDeclaration.js var name104, shader104, logDepthDeclarationWGSL; var init_logDepthDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/logDepthDeclaration.js"() { init_shaderStore(); name104 = "logDepthDeclaration"; shader104 = `#ifdef LOGARITHMICDEPTH uniform logarithmicDepthConstant: f32;varying vFragmentDepth: f32; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name104]) { ShaderStore.IncludesShadersStoreWGSL[name104] = shader104; } logDepthDeclarationWGSL = { name: name104, shader: shader104 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassVertex.js var name105, shader105, prePassVertexWGSL; var init_prePassVertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassVertex.js"() { init_shaderStore(); name105 = "prePassVertex"; shader105 = `#ifdef PREPASS_DEPTH vertexOutputs.vViewPos=(scene.view*worldPos).rgb; #endif #ifdef PREPASS_NORMALIZED_VIEW_DEPTH vertexOutputs.vNormViewDepth=((scene.view*worldPos).z-uniforms.cameraInfo.x)/(uniforms.cameraInfo.y-uniforms.cameraInfo.x); #endif #ifdef PREPASS_LOCAL_POSITION vertexOutputs.vPosition=positionUpdated.xyz; #endif #if (defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED) vertexOutputs.vCurrentPosition=scene.viewProjection*worldPos; #if NUM_BONE_INFLUENCERS>0 var previousInfluence: mat4x4f;previousInfluence=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3]; #endif vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*previousInfluence* vec4f(positionUpdated,1.0); #else vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0); #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name105]) { ShaderStore.IncludesShadersStoreWGSL[name105] = shader105; } prePassVertexWGSL = { name: name105, shader: shader105 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/uvVariableDeclaration.js var name106, shader106, uvVariableDeclarationWGSL; var init_uvVariableDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/uvVariableDeclaration.js"() { init_shaderStore(); name106 = "uvVariableDeclaration"; shader106 = `#ifdef MAINUV{X} #if !defined(UV{X}) var uv{X}: vec2f=vec2f(0.,0.); #else var uv{X}: vec2f=vertexInputs.uv{X}; #endif vertexOutputs.vMainUV{X}=uv{X}; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name106]) { ShaderStore.IncludesShadersStoreWGSL[name106] = shader106; } uvVariableDeclarationWGSL = { name: name106, shader: shader106 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/samplerVertexImplementation.js var name107, shader107, samplerVertexImplementationWGSL; var init_samplerVertexImplementation = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/samplerVertexImplementation.js"() { init_shaderStore(); name107 = "samplerVertexImplementation"; shader107 = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 if (uniforms.v_INFONAME_==0.) {vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(uvUpdated,1.0,0.0)).xy;} #ifdef UV2 else if (uniforms.v_INFONAME_==1.) {vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(uv2Updated,1.0,0.0)).xy;} #endif #ifdef UV3 else if (uniforms.v_INFONAME_==2.) {vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv3,1.0,0.0)).xy;} #endif #ifdef UV4 else if (uniforms.v_INFONAME_==3.) {vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv4,1.0,0.0)).xy;} #endif #ifdef UV5 else if (uniforms.v_INFONAME_==4.) {vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv5,1.0,0.0)).xy;} #endif #ifdef UV6 else if (uniforms.v_INFONAME_==5.) {vertexOutputs.v_VARYINGNAME_UV= (uniforms._MATRIXNAME_Matrix* vec4f(vertexInputs.uv6,1.0,0.0)).xy;} #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name107]) { ShaderStore.IncludesShadersStoreWGSL[name107] = shader107; } samplerVertexImplementationWGSL = { name: name107, shader: shader107 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpVertex.js var name108, shader108, bumpVertexWGSL; var init_bumpVertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpVertex.js"() { init_shaderStore(); name108 = "bumpVertex"; shader108 = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) var tbnNormal: vec3f=normalize(normalUpdated);var tbnTangent: vec3f=normalize(tangentUpdated.xyz);var tbnBitangent: vec3f=cross(tbnNormal,tbnTangent)*tangentUpdated.w;var matTemp= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz)* mat3x3f(tbnTangent,tbnBitangent,tbnNormal);vertexOutputs.vTBN0=matTemp[0];vertexOutputs.vTBN1=matTemp[1];vertexOutputs.vTBN2=matTemp[2]; #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name108]) { ShaderStore.IncludesShadersStoreWGSL[name108] = shader108; } bumpVertexWGSL = { name: name108, shader: shader108 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogVertex.js var name109, shader109, fogVertexWGSL; var init_fogVertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogVertex.js"() { init_shaderStore(); name109 = "fogVertex"; shader109 = `#ifdef FOG #ifdef SCENE_UBO vertexOutputs.vFogDistance=(scene.view*worldPos).xyz; #else vertexOutputs.vFogDistance=(uniforms.view*worldPos).xyz; #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name109]) { ShaderStore.IncludesShadersStoreWGSL[name109] = shader109; } fogVertexWGSL = { name: name109, shader: shader109 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowsVertex.js var name110, shader110, shadowsVertexWGSL; var init_shadowsVertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/shadowsVertex.js"() { init_shaderStore(); name110 = "shadowsVertex"; shader110 = `#ifdef SHADOWS #if defined(SHADOWCSM{X}) vertexOutputs.vPositionFromCamera{X}=scene.view*worldPos; #if SHADOWCSMNUM_CASCADES{X}>0 vertexOutputs.vPositionFromLight{X}_0=uniforms.lightMatrix{X}[0]*worldPos; #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.vDepthMetric{X}_0=(-vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y; #else vertexOutputs.vDepthMetric{X}_0= (vertexOutputs.vPositionFromLight{X}_0.z+light{X}.depthValues.x)/light{X}.depthValues.y; #endif #endif #if SHADOWCSMNUM_CASCADES{X}>1 vertexOutputs.vPositionFromLight{X}_1=uniforms.lightMatrix{X}[1]*worldPos; #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.vDepthMetric{X}_1=(-vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y; #else vertexOutputs.vDepthMetric{X}_1= (vertexOutputs.vPositionFromLight{X}_1.z+light{X}.depthValues.x)/light{X}.depthValues.y; #endif #endif #if SHADOWCSMNUM_CASCADES{X}>2 vertexOutputs.vPositionFromLight{X}_2=uniforms.lightMatrix{X}[2]*worldPos; #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.vDepthMetric{X}_2=(-vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y; #else vertexOutputs.vDepthMetric{X}_2= (vertexOutputs.vPositionFromLight{X}_2.z+light{X}.depthValues.x)/light{X}.depthValues.y; #endif #endif #if SHADOWCSMNUM_CASCADES{X}>3 vertexOutputs.vPositionFromLight{X}_3=uniforms.lightMatrix{X}[3]*worldPos; #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.vDepthMetric{X}_3=(-vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y; #else vertexOutputs.vDepthMetric{X}_3= (vertexOutputs.vPositionFromLight{X}_3.z+light{X}.depthValues.x)/light{X}.depthValues.y; #endif #endif #elif defined(SHADOW{X}) && !defined(SHADOWCUBE{X}) vertexOutputs.vPositionFromLight{X}=uniforms.lightMatrix{X}*worldPos; #ifdef USE_REVERSE_DEPTHBUFFER vertexOutputs.vDepthMetric{X}=(-vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y; #else vertexOutputs.vDepthMetric{X}=(vertexOutputs.vPositionFromLight{X}.z+light{X}.depthValues.x)/light{X}.depthValues.y; #endif #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name110]) { ShaderStore.IncludesShadersStoreWGSL[name110] = shader110; } shadowsVertexWGSL = { name: name110, shader: shader110 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/vertexColorMixing.js var name111, shader111, vertexColorMixingWGSL; var init_vertexColorMixing = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/vertexColorMixing.js"() { init_shaderStore(); name111 = "vertexColorMixing"; shader111 = `#if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) vertexOutputs.vColor=vec4f(1.0); #ifdef VERTEXCOLOR #ifdef VERTEXALPHA vertexOutputs.vColor*=vertexInputs.color; #else vertexOutputs.vColor=vec4f(vertexOutputs.vColor.rgb*vertexInputs.color.rgb,vertexOutputs.vColor.a); #endif #endif #ifdef INSTANCESCOLOR vertexOutputs.vColor*=vertexInputs.instanceColor; #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name111]) { ShaderStore.IncludesShadersStoreWGSL[name111] = shader111; } vertexColorMixingWGSL = { name: name111, shader: shader111 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/logDepthVertex.js var name112, shader112, logDepthVertexWGSL; var init_logDepthVertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/logDepthVertex.js"() { init_shaderStore(); name112 = "logDepthVertex"; shader112 = `#ifdef LOGARITHMICDEPTH vertexOutputs.vFragmentDepth=1.0+vertexOutputs.position.w;vertexOutputs.position.z=log2(max(0.000001,vertexOutputs.vFragmentDepth))*uniforms.logarithmicDepthConstant; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name112]) { ShaderStore.IncludesShadersStoreWGSL[name112] = shader112; } logDepthVertexWGSL = { name: name112, shader: shader112 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/default.vertex.js var default_vertex_exports = {}; __export(default_vertex_exports, { defaultVertexShaderWGSL: () => defaultVertexShaderWGSL }); var name113, shader113, defaultVertexShaderWGSL; var init_default_vertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/default.vertex.js"() { init_shaderStore(); init_defaultUboDeclaration(); init_uvAttributeDeclaration(); init_helperFunctions(); init_bonesDeclaration(); init_bakedVertexAnimationDeclaration(); init_instancesDeclaration(); init_prePassVertexDeclaration(); init_mainUVVaryingDeclaration(); init_samplerVertexDeclaration(); init_bumpVertexDeclaration(); init_clipPlaneVertexDeclaration(); init_fogVertexDeclaration(); init_lightVxFragmentDeclaration(); init_lightVxUboDeclaration(); init_morphTargetsVertexGlobalDeclaration(); init_morphTargetsVertexDeclaration(); init_logDepthDeclaration(); init_morphTargetsVertexGlobal(); init_morphTargetsVertex(); init_instancesVertex(); init_bonesVertex(); init_bakedVertexAnimation(); init_prePassVertex(); init_uvVariableDeclaration(); init_samplerVertexImplementation(); init_bumpVertex(); init_clipPlaneVertex(); init_fogVertex(); init_shadowsVertex(); init_vertexColorMixing(); init_logDepthVertex(); name113 = "defaultVertexShader"; shader113 = `#include #define CUSTOM_VERTEX_BEGIN attribute position: vec3f; #ifdef NORMAL attribute normal: vec3f; #endif #ifdef TANGENT attribute tangent: vec4f; #endif #ifdef UV1 attribute uv: vec2f; #endif #include[2..7] #ifdef VERTEXCOLOR attribute color: vec4f; #endif #include #include #include #include #include #include[1..7] #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) #endif #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) varying vPositionW: vec3f; #ifdef NORMAL varying vNormalW: vec3f; #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vColor: vec4f; #endif #include #include #include #include<__decl__lightVxFragment>[0..maxSimultaneousLights] #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX varying vPositionUVW: vec3f; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vDirectionW: vec3f; #endif #if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0 varying vViewDepth: f32; #endif #include #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN var positionUpdated: vec3f=vertexInputs.position; #ifdef NORMAL var normalUpdated: vec3f=vertexInputs.normal; #endif #ifdef TANGENT var tangentUpdated: vec4f=vertexInputs.tangent; #endif #ifdef UV1 var uvUpdated: vec2f=vertexInputs.uv; #endif #ifdef UV2 var uv2Updated: vec2f=vertexInputs.uv2; #endif #ifdef VERTEXCOLOR var colorUpdated: vec4f=vertexInputs.color; #endif #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX vertexOutputs.vPositionUVW=positionUpdated; #endif #define CUSTOM_VERTEX_UPDATE_POSITION #define CUSTOM_VERTEX_UPDATE_NORMAL #include #if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED) vertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*vec4f(positionUpdated,1.0); #endif #include #include var worldPos: vec4f=finalWorld*vec4f(positionUpdated,1.0); #ifdef NORMAL var normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz); #if defined(INSTANCES) && defined(THIN_INSTANCES) vertexOutputs.vNormalW=normalUpdated/ vec3f(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vertexOutputs.vNormalW=normalize(normalWorld*vertexOutputs.vNormalW); #else #ifdef NONUNIFORMSCALING normalWorld=transposeMat3(inverseMat3(normalWorld)); #endif vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated); #endif #endif #define CUSTOM_VERTEX_UPDATE_WORLDPOS #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {vertexOutputs.position=scene.viewProjection*worldPos;} else {vertexOutputs.position=scene.viewProjectionR*worldPos;} #else vertexOutputs.position=scene.viewProjection*worldPos; #endif vertexOutputs.vPositionW= worldPos.xyz; #ifdef PREPASS #include #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) vertexOutputs.vDirectionW=normalize((finalWorld* vec4f(positionUpdated,0.0)).xyz); #endif #if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0 vertexOutputs.vViewDepth=(scene.view*worldPos).z; #endif #ifndef UV1 var uvUpdated: vec2f=vec2f(0.,0.); #endif #ifdef MAINUV1 vertexOutputs.vMainUV1=uvUpdated; #endif #ifndef UV2 var uv2Updated: vec2f=vec2f(0.,0.); #endif #ifdef MAINUV2 vertexOutputs.vMainUV2=uv2Updated; #endif #include[3..7] #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) #endif #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) #include #include #include #include[0..maxSimultaneousLights] #include #include #define CUSTOM_VERTEX_MAIN_END } `; if (!ShaderStore.ShadersStoreWGSL[name113]) { ShaderStore.ShadersStoreWGSL[name113] = shader113; } defaultVertexShaderWGSL = { name: name113, shader: shader113 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassDeclaration.js var name114, shader114, prePassDeclarationWGSL; var init_prePassDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/prePassDeclaration.js"() { init_shaderStore(); name114 = "prePassDeclaration"; shader114 = `#ifdef PREPASS #ifdef PREPASS_LOCAL_POSITION varying vPosition : vec3f; #endif #ifdef PREPASS_DEPTH varying vViewPos: vec3f; #endif #ifdef PREPASS_NORMALIZED_VIEW_DEPTH varying vNormViewDepth: f32; #endif #if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name114]) { ShaderStore.IncludesShadersStoreWGSL[name114] = shader114; } prePassDeclarationWGSL = { name: name114, shader: shader114 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/oitDeclaration.js var name115, shader115, oitDeclarationWGSL; var init_oitDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/oitDeclaration.js"() { init_shaderStore(); name115 = "oitDeclaration"; shader115 = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY #define MAX_DEPTH 99999.0 var oitDepthSamplerSampler: sampler;var oitDepthSampler: texture_2d;var oitFrontColorSamplerSampler: sampler;var oitFrontColorSampler: texture_2d; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name115]) { ShaderStore.IncludesShadersStoreWGSL[name115] = shader115; } oitDeclarationWGSL = { name: name115, shader: shader115 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightUboDeclaration.js var name116, shader116, lightUboDeclarationWGSL; var init_lightUboDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightUboDeclaration.js"() { init_shaderStore(); name116 = "lightUboDeclaration"; shader116 = `#ifdef LIGHT{X} struct Light{X} {vLightData: vec4f, vLightDiffuse: vec4f, vLightSpecular: vec4f, #ifdef SPOTLIGHT{X} vLightDirection: vec4f, vLightFalloff: vec4f, #elif defined(POINTLIGHT{X}) vLightFalloff: vec4f, #elif defined(HEMILIGHT{X}) vLightGround: vec3f, #elif defined(CLUSTLIGHT{X}) vSliceData: vec2f, vSliceRanges: array, #endif #if defined(AREALIGHT{X}) vLightWidth: vec4f, vLightHeight: vec4f, #endif shadowsInfo: vec4f, depthValues: vec2f} ;var light{X} : Light{X}; #ifdef IESLIGHTTEXTURE{X} var iesLightTexture{X}Sampler: sampler;var iesLightTexture{X}: texture_2d; #endif #ifdef PROJECTEDLIGHTTEXTURE{X} uniform textureProjectionMatrix{X}: mat4x4f;var projectionLightTexture{X}Sampler: sampler;var projectionLightTexture{X}: texture_2d; #endif #ifdef CLUSTLIGHT{X} var lightDataTexture{X}: texture_2d;var tileMaskBuffer{X}: array; #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform lightMatrix{X}: array;uniform viewFrustumZ{X}: array;uniform frustumLengths{X}: array;uniform cascadeBlendFactor{X}: f32;varying vPositionFromLight{X}_0: vec4f;varying vDepthMetric{X}_0: f32;varying vPositionFromLight{X}_1: vec4f;varying vDepthMetric{X}_1: f32;varying vPositionFromLight{X}_2: vec4f;varying vDepthMetric{X}_2: f32;varying vPositionFromLight{X}_3: vec4f;varying vDepthMetric{X}_3: f32;varying vPositionFromCamera{X}: vec4f;var vPositionFromLight{X}: array;var vDepthMetric{X} : array; #if defined(SHADOWPCSS{X}) var shadowTexture{X}Sampler: sampler_comparison; var shadowTexture{X}: texture_depth_2d_array;var depthTexture{X}Sampler: sampler;var depthTexture{X}: texture_2d_array;uniform lightSizeUVCorrection{X}: array;uniform depthCorrection{X}: array;uniform penumbraDarkness{X}: f32; #elif defined(SHADOWPCF{X}) var shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d_array; #else var shadowTexture{X}Sampler: sampler; var shadowTexture{X}: texture_2d_array; #endif #ifdef SHADOWCSMDEBUG{X} const vCascadeColorsMultiplier{X}: array=array ( vec3f ( 1.5,0.0,0.0 ), vec3f ( 0.0,1.5,0.0 ), vec3f ( 0.0,0.0,5.5 ), vec3f ( 1.5,0.0,5.5 ), vec3f ( 1.5,1.5,0.0 ), vec3f ( 1.0,1.0,1.0 ), vec3f ( 0.0,1.0,5.5 ), vec3f ( 0.5,3.5,0.75 ) ); #endif #elif defined(SHADOWCUBE{X}) var shadowTexture{X}Sampler: sampler;var shadowTexture{X}: texture_cube; #else varying vPositionFromLight{X}: vec4f;varying vDepthMetric{X}: f32; #if defined(SHADOWPCSS{X}) var shadowTexture{X}Sampler: sampler_comparison; var shadowTexture{X}: texture_depth_2d;var depthTexture{X}Sampler: sampler; var depthTexture{X}: texture_2d; #elif defined(SHADOWPCF{X}) var shadowTexture{X}Sampler: sampler_comparison;var shadowTexture{X}: texture_depth_2d; #else var shadowTexture{X}Sampler: sampler; var shadowTexture{X}: texture_2d; #endif uniform lightMatrix{X}: mat4x4f; #endif #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name116]) { ShaderStore.IncludesShadersStoreWGSL[name116] = shader116; } lightUboDeclarationWGSL = { name: name116, shader: shader116 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/ltcHelperFunctions.js var name117, shader117, ltcHelperFunctionsWGSL; var init_ltcHelperFunctions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/ltcHelperFunctions.js"() { init_shaderStore(); name117 = "ltcHelperFunctions"; shader117 = `fn LTCUv(N: vec3f,V: vec3f,roughness: f32)->vec2f {var LUTSIZE: f32=64.0;var LUTSCALE: f32=( LUTSIZE-1.0 )/LUTSIZE;var LUTBIAS:f32=0.5/LUTSIZE;var dotNV:f32=saturate( dot( N,V ) );var uv:vec2f=vec2f( roughness,sqrt( 1.0-dotNV ) );uv=uv*LUTSCALE+LUTBIAS;return uv;} fn LTCClippedSphereFormFactor( f:vec3f )->f32 {var l: f32=length( f );return max( ( l*l+f.z )/( l+1.0 ),0.0 );} fn LTCEdgeVectorFormFactor( v1:vec3f,v2:vec3f )->vec3f {var x:f32=dot( v1,v2 );var y:f32=abs( x );var a:f32=0.8543985+( 0.4965155+0.0145206*y )*y;var b:f32=3.4175940+( 4.1616724+y )*y;var v:f32=a/b;var thetaSintheta:f32=0.0;if( x>0.0 ) {thetaSintheta=v;} else {thetaSintheta=0.5*inverseSqrt( max( 1.0-x*x,0.00000001 ) )-v;} return cross( v1,v2 )*thetaSintheta;} fn LTCEvaluate( N:vec3f,V:vec3f,P:vec3f,mInv: mat3x3,rectCoords0:vec3f,rectCoords1:vec3f,rectCoords2:vec3f,rectCoords3:vec3f )->vec3f {var v1:vec3f=rectCoords1-rectCoords0;var v2:vec3f=rectCoords3-rectCoords0;var lightNormal:vec3f=cross( v1,v2 );if( dot( lightNormal,P-rectCoords0 )<0.0 ){return vec3f( 0.0 );} var T1:vec3f=normalize( V-N*dot( V,N ) );var T2:vec3f=- cross( N,T1 ); var mat: mat3x3=mInv*transposeMat3( mat3x3( T1,T2,N ) );var coords0: vec3f=mat*( rectCoords0-P );var coords1: vec3f=mat*( rectCoords1-P );var coords2: vec3f=mat*( rectCoords2-P );var coords3: vec3f=mat*( rectCoords3-P );coords0=normalize( coords0 );coords1=normalize( coords1 );coords2=normalize( coords2 );coords3=normalize( coords3 );var vectorFormFactor:vec3f=vec3( 0.0 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords0,coords1 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords1,coords2 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords2,coords3 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords3,coords0 );var result:f32=LTCClippedSphereFormFactor( vectorFormFactor );return vec3f( result );} struct areaLightData {Diffuse: vec3f, Specular: vec3f, Fresnel: vec4f};fn computeAreaLightSpecularDiffuseFresnel(ltc1: texture_2d,ltc1Sampler:sampler,ltc2:texture_2d,ltc2Sampler:sampler,viewDir: vec3f,normal:vec3f,position:vec3f,lightPos:vec3f,halfWidth:vec3f, halfHeight:vec3f,roughness:f32)->areaLightData {var result: areaLightData;var rectCoords0:vec3f=lightPos+halfWidth-halfHeight; var rectCoords1:vec3f=lightPos-halfWidth-halfHeight;var rectCoords2:vec3f=lightPos-halfWidth+halfHeight;var rectCoords3:vec3f=lightPos+halfWidth+halfHeight; #ifdef SPECULARTERM var uv:vec2f=LTCUv( normal,viewDir,roughness );var t1:vec4f=textureSample( ltc1,ltc1Sampler,uv );var t2:vec4f=textureSample( ltc2,ltc2Sampler,uv );var mInv:mat3x3=mat3x3( vec3f( t1.x,0,t1.y ), vec3f( 0,1, 0 ), vec3f( t1.z,0,t1.w ) );result.Fresnel=t2;result.Specular=LTCEvaluate( normal,viewDir,position,mInv,rectCoords0,rectCoords1,rectCoords2,rectCoords3 ); #endif var mInvEmpty:mat3x3=mat3x3( vec3f( 1,0,0 ), vec3f( 0,1,0 ), vec3f( 0,0,1 ) );result.Diffuse+=LTCEvaluate( normal,viewDir,position,mInvEmpty,rectCoords0,rectCoords1,rectCoords2,rectCoords3 );return result;}`; if (!ShaderStore.IncludesShadersStoreWGSL[name117]) { ShaderStore.IncludesShadersStoreWGSL[name117] = shader117; } ltcHelperFunctionsWGSL = { name: name117, shader: shader117 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clusteredLightingFunctions.js var name118, shader118, clusteredLightingFunctionsWGSL; var init_clusteredLightingFunctions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/clusteredLightingFunctions.js"() { init_shaderStore(); name118 = "clusteredLightingFunctions"; shader118 = `struct ClusteredLight {vLightData: vec4f, vLightDiffuse: vec4f, vLightSpecular: vec4f, vLightDirection: vec4f, vLightFalloff: vec4f,} fn getClusteredLight(lightDataTexture: texture_2d,index: u32)->ClusteredLight {return ClusteredLight( textureLoad(lightDataTexture,vec2u(0,index),0), textureLoad(lightDataTexture,vec2u(1,index),0), textureLoad(lightDataTexture,vec2u(2,index),0), textureLoad(lightDataTexture,vec2u(3,index),0), textureLoad(lightDataTexture,vec2u(4,index),0) );} fn getClusteredSliceIndex(sliceData: vec2f,viewDepth: f32)->i32 {return i32(log(viewDepth)*sliceData.x+sliceData.y);} `; if (!ShaderStore.IncludesShadersStoreWGSL[name118]) { ShaderStore.IncludesShadersStoreWGSL[name118] = shader118; } clusteredLightingFunctionsWGSL = { name: name118, shader: shader118 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightsFragmentFunctions.js var name119, shader119, lightsFragmentFunctionsWGSL; var init_lightsFragmentFunctions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightsFragmentFunctions.js"() { init_shaderStore(); init_ltcHelperFunctions(); init_clusteredLightingFunctions(); name119 = "lightsFragmentFunctions"; shader119 = `struct lightingInfo {diffuse: vec3f, #ifdef SPECULARTERM specular: vec3f, #endif #ifdef NDOTL ndl: f32, #endif };fn computeLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var result: lightingInfo;var lightVectorW: vec3f;var attenuation: f32=1.0;if (lightData.w==0.) {var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} else {lightVectorW=normalize(-lightData.xyz);} var ndl: f32=max(0.,dot(vNormal,lightVectorW)); #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=ndl*diffuseColor*attenuation; #ifdef SPECULARTERM var angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; #endif return result;} fn getAttenuation(cosAngle: f32,exponent: f32)->f32 {return max(0.,pow(cosAngle,exponent));} fn getIESAttenuation(cosAngle: f32,iesLightTexture: texture_2d,iesLightTextureSampler: sampler)->f32 {var angle=acos(cosAngle)/PI;return textureSampleLevel(iesLightTexture,iesLightTextureSampler,vec2f(angle,0),0.).r;} fn computeBasicSpotLighting(viewDirectionW: vec3f,lightVectorW: vec3f,vNormal: vec3f,attenuation: f32,diffuseColor: vec3f,specularColor: vec3f,glossiness: f32)->lightingInfo {var result: lightingInfo;var ndl: f32=max(0.,dot(vNormal,lightVectorW)); #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=ndl*diffuseColor*attenuation; #ifdef SPECULARTERM var angleW: vec3f=normalize(viewDirectionW+lightVectorW);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; #endif return result;} fn computeIESSpotLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,lightDirection: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32,iesLightTexture: texture_2d,iesLightTextureSampler: sampler)->lightingInfo {var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;var lightVectorW: vec3f=normalize(direction);var attenuation: f32=max(0.,1.0-length(direction)/range);var dotProduct=dot(lightDirection.xyz,-lightVectorW);var cosAngle: f32=max(0.,dotProduct);if (cosAngle>=lightDirection.w) {attenuation*=getIESAttenuation(dotProduct,iesLightTexture,iesLightTextureSampler);return computeBasicSpotLighting(viewDirectionW,lightVectorW,vNormal,attenuation,diffuseColor,specularColor,glossiness);} var result: lightingInfo;result.diffuse=vec3f(0.); #ifdef SPECULARTERM result.specular=vec3f(0.); #endif #ifdef NDOTL result.ndl=0.; #endif return result;} fn computeSpotLighting(viewDirectionW: vec3f,vNormal: vec3f ,lightData: vec4f,lightDirection: vec4f,diffuseColor: vec3f,specularColor: vec3f,range: f32,glossiness: f32)->lightingInfo {var direction: vec3f=lightData.xyz-fragmentInputs.vPositionW;var lightVectorW: vec3f=normalize(direction);var attenuation: f32=max(0.,1.0-length(direction)/range);var cosAngle: f32=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) {attenuation*=getAttenuation(cosAngle,lightData.w);return computeBasicSpotLighting(viewDirectionW,lightVectorW,vNormal,attenuation,diffuseColor,specularColor,glossiness);} var result: lightingInfo;result.diffuse=vec3f(0.); #ifdef SPECULARTERM result.specular=vec3f(0.); #endif #ifdef NDOTL result.ndl=0.; #endif return result;} fn computeHemisphericLighting(viewDirectionW: vec3f,vNormal: vec3f,lightData: vec4f,diffuseColor: vec3f,specularColor: vec3f,groundColor: vec3f,glossiness: f32)->lightingInfo {var result: lightingInfo;var ndl: f32=dot(vNormal,lightData.xyz)*0.5+0.5; #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=mix(groundColor,diffuseColor,ndl); #ifdef SPECULARTERM var angleW: vec3f=normalize(viewDirectionW+lightData.xyz);var specComp: f32=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; #endif return result;} fn computeProjectionTextureDiffuseLighting(projectionLightTexture: texture_2d,projectionLightSampler: sampler,textureProjectionMatrix: mat4x4f,posW: vec3f)->vec3f {var strq: vec4f=textureProjectionMatrix*vec4f(posW,1.0);strq/=strq.w;var textureColor: vec3f=textureSample(projectionLightTexture,projectionLightSampler,strq.xy).rgb;return textureColor;} #if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED) #include var areaLightsLTC1SamplerSampler: sampler;var areaLightsLTC1Sampler: texture_2d;var areaLightsLTC2SamplerSampler: sampler;var areaLightsLTC2Sampler: texture_2d;fn computeAreaLighting(ltc1: texture_2d,ltc1Sampler:sampler,ltc2:texture_2d,ltc2Sampler:sampler,viewDirectionW: vec3f,vNormal:vec3f,vPosition:vec3f,lightPosition:vec3f,halfWidth:vec3f, halfHeight:vec3f,diffuseColor:vec3f,specularColor:vec3f,roughness:f32 )->lightingInfo {var result: lightingInfo;var data: areaLightData=computeAreaLightSpecularDiffuseFresnel(ltc1,ltc1Sampler,ltc2,ltc2Sampler,viewDirectionW,vNormal,vPosition,lightPosition,halfWidth,halfHeight,roughness); #ifdef SPECULARTERM var fresnel:vec3f=( specularColor*data.Fresnel.x+( vec3f( 1.0 )-specularColor )*data.Fresnel.y );result.specular+=specularColor*fresnel*data.Specular; #endif result.diffuse+=diffuseColor*data.Diffuse;return result;} #endif #if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0 #include fn computeClusteredLighting( lightDataTexture: texture_2d, tileMaskBuffer: ptr>, viewDirectionW: vec3f, vNormal: vec3f, lightData: vec4f, sliceRange: vec2u, glossiness: f32 )->lightingInfo {var result: lightingInfo;let tilePosition=vec2u(fragmentInputs.position.xy*lightData.xy);let maskResolution=vec2u(lightData.zw);var tileIndex=(tilePosition.x*maskResolution.x+tilePosition.y)*maskResolution.y;let batchRange=sliceRange/CLUSTLIGHT_BATCH;var batchOffset=batchRange.x*CLUSTLIGHT_BATCH;tileIndex+=batchRange.x;for (var i=batchRange.x; i<=batchRange.y; i+=1) {var mask=tileMaskBuffer[tileIndex];tileIndex+=1;let maskOffset=max(sliceRange.x,batchOffset)-batchOffset; let maskWidth=min(sliceRange.y-batchOffset+1,CLUSTLIGHT_BATCH);mask=extractBits(mask,maskOffset,maskWidth);while mask != 0 {let trailing=firstTrailingBit(mask);mask ^= 1u<f32 {const bit_shift: vec4f= vec4f(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} #endif fn computeFallOff(value: f32,clipSpace: vec2f,frustumEdgeFalloff: f32)->f32 {var mask: f32=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} fn computeShadowCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthValues: vec2f)->f32 {var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; #ifndef SHADOWFLOAT var shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight)); #else var shadow: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x; #endif return select(1.0,darkness,depth>shadow);} fn computeShadowWithPoissonSamplingCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,mapSize: f32,darkness: f32,depthValues: vec2f)->f32 {var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec3f(-1.0,1.0,-1.0);poissonDisk[1]= vec3f(1.0,-1.0,-1.0);poissonDisk[2]= vec3f(-1.0,-1.0,-1.0);poissonDisk[3]= vec3f(1.0,-1.0,1.0); #ifndef SHADOWFLOAT if (unpack(textureSample(shadowTexture,shadowSampler,directionToLight+poissonDisk[0]*mapSize)),shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32 {var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; #ifndef SHADOWFLOAT var shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight)); #else var shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x; #endif var esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return esm;} fn computeShadowWithCloseESMCube(worldPos: vec3f,lightPosition: vec3f,shadowTexture: texture_cube,shadowSampler: sampler,darkness: f32,depthScale: f32,depthValues: vec2f)->f32 {var directionToLight: vec3f=worldPos-lightPosition;var depth: f32=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);var shadowPixelDepth: f32=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; #ifndef SHADOWFLOAT var shadowMapSample: f32=unpack(textureSample(shadowTexture,shadowSampler,directionToLight)); #else var shadowMapSample: f32=textureSample(shadowTexture,shadowSampler,directionToLight).x; #endif var esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return esm;} fn computeShadowCSM(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d_array,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT var shadow: f32=unpack(textureSample(shadowTexture,shadowSampler,uv,layer)); #else var shadow: f32=textureSample(shadowTexture,shadowSampler,uv,layer).x; #endif return select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );} fn computeShadow(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT var shadow: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.)); #else var shadow: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x; #endif return select(1.,computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff),shadowPixelDepth>shadow );}} fn computeShadowWithPoissonSampling(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,mapSize: f32,darkness: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0);var visibility: f32=1.;var poissonDisk: array;poissonDisk[0]= vec2f(-0.94201624,-0.39906216);poissonDisk[1]= vec2f(0.94558609,-0.76890725);poissonDisk[2]= vec2f(-0.094184101,-0.92938870);poissonDisk[3]= vec2f(0.34495938,0.29387760); #ifndef SHADOWFLOAT if (unpack(textureSampleLevel(shadowTexture,shadowSampler,uv+poissonDisk[0]*mapSize,0.)),shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT var shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.)); #else var shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x; #endif var esm: f32=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} fn computeShadowWithCloseESM(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_2d,shadowSampler: sampler,darkness: f32,depthScale: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uv: vec2f=0.5*clipSpace.xy+ vec2f(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {var shadowPixelDepth: f32=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT var shadowMapSample: f32=unpack(textureSampleLevel(shadowTexture,shadowSampler,uv,0.)); #else var shadowMapSample: f32=textureSampleLevel(shadowTexture,shadowSampler,uv,0.).x; #endif var esm: f32=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} fn getZInClip(clipSpace: vec3f,uvDepth: vec3f)->f32 { #ifdef IS_NDC_HALF_ZRANGE return clipSpace.z; #else return uvDepth.z; #endif } const GREATEST_LESS_THAN_ONE: f32=0.99999994; #define DISABLE_UNIFORMITY_ANALYSIS fn computeShadowWithCSMPCF1(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var shadow: f32=textureSampleCompare(shadowTexture,shadowSampler,uvDepth.xy,layer,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} fn computeShadowWithCSMPCF3(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; var st: vec2f=fract(uv); var base_uv: vec2f=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; var uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} fn computeShadowWithCSMPCF5(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; var st: vec2f=fract(uv); var base_uv: vec2f=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; var uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),layer,uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),layer,uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),layer,uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),layer,uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),layer,uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),layer,uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),layer,uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),layer,uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompare(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),layer,uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} fn computeShadowWithPCF1(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,darkness: f32,frustumEdgeFalloff: f32)->f32 {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var shadow: f32=textureSampleCompareLevel(shadowTexture,shadowSampler,uvDepth.xy,uvDepth.z);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} fn computeShadowWithPCF3(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32 {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; var st: vec2f=fract(uv); var base_uv: vec2f=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; var uvw0: vec2f=3.-2.*st;var uvw1: vec2f=1.+2.*st;var u: vec2f= vec2f((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;var v: vec2f= vec2f((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} fn computeShadowWithPCF5(vPositionFromLight: vec4f,depthMetric: f32,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeAndInverse: vec2f,darkness: f32,frustumEdgeFalloff: f32)->f32 {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var uv: vec2f=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; var st: vec2f=fract(uv); var base_uv: vec2f=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; var uvw0: vec2f=4.-3.*st;var uvw1: vec2f= vec2f(7.);var uvw2: vec2f=1.+3.*st;var u: vec3f= vec3f((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;var v: vec3f= vec3f((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;var shadow: f32=0.;shadow+=uvw0.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[0]),uvDepth.z);shadow+=uvw1.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[0]),uvDepth.z);shadow+=uvw2.x*uvw0.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[0]),uvDepth.z);shadow+=uvw0.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[1]),uvDepth.z);shadow+=uvw1.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[1]),uvDepth.z);shadow+=uvw2.x*uvw1.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[1]),uvDepth.z);shadow+=uvw0.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[0],v[2]),uvDepth.z);shadow+=uvw1.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[1],v[2]),uvDepth.z);shadow+=uvw2.x*uvw2.y*textureSampleCompareLevel(shadowTexture,shadowSampler, base_uv.xy+ vec2f(u[2],v[2]),uvDepth.z);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} const PoissonSamplers32: array=array ( vec3f(0.06407013,0.05409927,0.), vec3f(0.7366577,0.5789394,0.), vec3f(-0.6270542,-0.5320278,0.), vec3f(-0.4096107,0.8411095,0.), vec3f(0.6849564,-0.4990818,0.), vec3f(-0.874181,-0.04579735,0.), vec3f(0.9989998,0.0009880066,0.), vec3f(-0.004920578,-0.9151649,0.), vec3f(0.1805763,0.9747483,0.), vec3f(-0.2138451,0.2635818,0.), vec3f(0.109845,0.3884785,0.), vec3f(0.06876755,-0.3581074,0.), vec3f(0.374073,-0.7661266,0.), vec3f(0.3079132,-0.1216763,0.), vec3f(-0.3794335,-0.8271583,0.), vec3f(-0.203878,-0.07715034,0.), vec3f(0.5912697,0.1469799,0.), vec3f(-0.88069,0.3031784,0.), vec3f(0.5040108,0.8283722,0.), vec3f(-0.5844124,0.5494877,0.), vec3f(0.6017799,-0.1726654,0.), vec3f(-0.5554981,0.1559997,0.), vec3f(-0.3016369,-0.3900928,0.), vec3f(-0.5550632,-0.1723762,0.), vec3f(0.925029,0.2995041,0.), vec3f(-0.2473137,0.5538505,0.), vec3f(0.9183037,-0.2862392,0.), vec3f(0.2469421,0.6718712,0.), vec3f(0.3916397,-0.4328209,0.), vec3f(-0.03576927,-0.6220032,0.), vec3f(-0.04661255,0.7995201,0.), vec3f(0.4402924,0.3640312,0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.), vec3f(0.) );const PoissonSamplers64: array=array ( vec3f(-0.613392,0.617481,0.), vec3f(0.170019,-0.040254,0.), vec3f(-0.299417,0.791925,0.), vec3f(0.645680,0.493210,0.), vec3f(-0.651784,0.717887,0.), vec3f(0.421003,0.027070,0.), vec3f(-0.817194,-0.271096,0.), vec3f(-0.705374,-0.668203,0.), vec3f(0.977050,-0.108615,0.), vec3f(0.063326,0.142369,0.), vec3f(0.203528,0.214331,0.), vec3f(-0.667531,0.326090,0.), vec3f(-0.098422,-0.295755,0.), vec3f(-0.885922,0.215369,0.), vec3f(0.566637,0.605213,0.), vec3f(0.039766,-0.396100,0.), vec3f(0.751946,0.453352,0.), vec3f(0.078707,-0.715323,0.), vec3f(-0.075838,-0.529344,0.), vec3f(0.724479,-0.580798,0.), vec3f(0.222999,-0.215125,0.), vec3f(-0.467574,-0.405438,0.), vec3f(-0.248268,-0.814753,0.), vec3f(0.354411,-0.887570,0.), vec3f(0.175817,0.382366,0.), vec3f(0.487472,-0.063082,0.), vec3f(-0.084078,0.898312,0.), vec3f(0.488876,-0.783441,0.), vec3f(0.470016,0.217933,0.), vec3f(-0.696890,-0.549791,0.), vec3f(-0.149693,0.605762,0.), vec3f(0.034211,0.979980,0.), vec3f(0.503098,-0.308878,0.), vec3f(-0.016205,-0.872921,0.), vec3f(0.385784,-0.393902,0.), vec3f(-0.146886,-0.859249,0.), vec3f(0.643361,0.164098,0.), vec3f(0.634388,-0.049471,0.), vec3f(-0.688894,0.007843,0.), vec3f(0.464034,-0.188818,0.), vec3f(-0.440840,0.137486,0.), vec3f(0.364483,0.511704,0.), vec3f(0.034028,0.325968,0.), vec3f(0.099094,-0.308023,0.), vec3f(0.693960,-0.366253,0.), vec3f(0.678884,-0.204688,0.), vec3f(0.001801,0.780328,0.), vec3f(0.145177,-0.898984,0.), vec3f(0.062655,-0.611866,0.), vec3f(0.315226,-0.604297,0.), vec3f(-0.780145,0.486251,0.), vec3f(-0.371868,0.882138,0.), vec3f(0.200476,0.494430,0.), vec3f(-0.494552,-0.711051,0.), vec3f(0.612476,0.705252,0.), vec3f(-0.578845,-0.768792,0.), vec3f(-0.772454,-0.090976,0.), vec3f(0.504440,0.372295,0.), vec3f(0.155736,0.065157,0.), vec3f(0.391522,0.849605,0.), vec3f(-0.620106,-0.328104,0.), vec3f(0.789239,-0.419965,0.), vec3f(-0.545396,0.538133,0.), vec3f(-0.178564,-0.596057,0.) );fn computeShadowWithCSMPCSS(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=clamp(getZInClip(clipSpace,uvDepth),0.,GREATEST_LESS_THAN_ONE);var uvDepthLayer: vec4f= vec4f(uvDepth.x,uvDepth.y,f32(layer),uvDepth.z);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,searchTapCount: i32,pcfTapCount: i32,poissonSamplers: array)->f32 {var clipSpace: vec3f=vPositionFromLight.xyz/vPositionFromLight.w;var uvDepth: vec3f= vec3f(0.5*clipSpace.xyz+ vec3f(0.5));uvDepth.z=getZInClip(clipSpace,uvDepth);var blockerDepth: f32=0.0;var sumBlockerDepth: f32=0.0;var numBlocker: f32=0.0;var exitCondition: bool=depthMetric>1.0 || depthMetric<0.0;for (var i: i32=0; i,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32 {return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);} fn computeShadowWithPCSS32(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32 {return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);} fn computeShadowWithPCSS64(vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d,depthSampler: sampler,shadowTexture: texture_depth_2d,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32)->f32 {return computeShadowWithPCSS(vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);} fn computeShadowWithCSMPCSS16(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32 {return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} fn computeShadowWithCSMPCSS32(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32 {return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} fn computeShadowWithCSMPCSS64(layer: i32,vPositionFromLight: vec4f,depthMetric: f32,depthTexture: texture_2d_array,depthSampler: sampler,shadowTexture: texture_depth_2d_array,shadowSampler: sampler_comparison,shadowMapSizeInverse: f32,lightSizeUV: f32,darkness: f32,frustumEdgeFalloff: f32,lightSizeUVCorrection: vec2f,depthCorrection: f32,penumbraDarkness: f32)->f32 {return computeShadowWithCSMPCSS(layer,vPositionFromLight,depthMetric,depthTexture,depthSampler,shadowTexture,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64,lightSizeUVCorrection,depthCorrection,penumbraDarkness);} #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name120]) { ShaderStore.IncludesShadersStoreWGSL[name120] = shader120; } shadowsFragmentFunctionsWGSL = { name: name120, shader: shader120 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/samplerFragmentDeclaration.js var name121, shader121, samplerFragmentDeclarationWGSL; var init_samplerFragmentDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/samplerFragmentDeclaration.js"() { init_shaderStore(); name121 = "samplerFragmentDeclaration"; shader121 = `#ifdef _DEFINENAME_ #if _DEFINENAME_DIRECTUV==1 #define v_VARYINGNAME_UV vMainUV1 #elif _DEFINENAME_DIRECTUV==2 #define v_VARYINGNAME_UV vMainUV2 #elif _DEFINENAME_DIRECTUV==3 #define v_VARYINGNAME_UV vMainUV3 #elif _DEFINENAME_DIRECTUV==4 #define v_VARYINGNAME_UV vMainUV4 #elif _DEFINENAME_DIRECTUV==5 #define v_VARYINGNAME_UV vMainUV5 #elif _DEFINENAME_DIRECTUV==6 #define v_VARYINGNAME_UV vMainUV6 #else varying v_VARYINGNAME_UV: vec2f; #endif var _SAMPLERNAME_SamplerSampler: sampler;var _SAMPLERNAME_Sampler: texture_2d; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name121]) { ShaderStore.IncludesShadersStoreWGSL[name121] = shader121; } samplerFragmentDeclarationWGSL = { name: name121, shader: shader121 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fresnelFunction.js var name122, shader122, fresnelFunctionWGSL; var init_fresnelFunction = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fresnelFunction.js"() { init_shaderStore(); name122 = "fresnelFunction"; shader122 = `#ifdef FRESNEL fn computeFresnelTerm(viewDirection: vec3f,worldNormal: vec3f,bias: f32,power: f32)->f32 {let fresnelTerm: f32=pow(bias+abs(dot(viewDirection,worldNormal)),power);return clamp(fresnelTerm,0.,1.);} #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name122]) { ShaderStore.IncludesShadersStoreWGSL[name122] = shader122; } fresnelFunctionWGSL = { name: name122, shader: shader122 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/reflectionFunction.js var name123, shader123, reflectionFunctionWGSL; var init_reflectionFunction = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/reflectionFunction.js"() { init_shaderStore(); name123 = "reflectionFunction"; shader123 = `fn computeFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f {var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0); } fn computeMirroredFixedEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,direction: vec3f)->vec3f {var lon: f32=atan2(direction.z,direction.x);var lat: f32=acos(direction.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(1.0-s,t,0); } fn computeEquirectangularCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f {var cameraToVertex: vec3f=normalize(worldPos.xyz-eyePosition);var r: vec3f=normalize(reflect(cameraToVertex,worldNormal));r= (reflectionMatrix* vec4f(r,0)).xyz;var lon: f32=atan2(r.z,r.x);var lat: f32=acos(r.y);var sphereCoords: vec2f= vec2f(lon,lat)*RECIPROCAL_PI2*2.0;var s: f32=sphereCoords.x*0.5+0.5;var t: f32=sphereCoords.y;return vec3f(s,t,0);} fn computeSphericalCoords(worldPos: vec4f,worldNormal: vec3f,view: mat4x4f,reflectionMatrix: mat4x4f)->vec3f {var viewDir: vec3f=normalize((view*worldPos).xyz);var viewNormal: vec3f=normalize((view* vec4f(worldNormal,0.0)).xyz);var r: vec3f=reflect(viewDir,viewNormal);r= (reflectionMatrix* vec4f(r,0)).xyz;r.z=r.z-1.0;var m: f32=2.0*length(r);return vec3f(r.x/m+0.5,1.0-r.y/m-0.5,0);} fn computePlanarCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f {var viewDir: vec3f=worldPos.xyz-eyePosition;var coords: vec3f=normalize(reflect(viewDir,worldNormal));return (reflectionMatrix* vec4f(coords,1)).xyz;} fn computeCubicCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f)->vec3f {var viewDir: vec3f=normalize(worldPos.xyz-eyePosition);var coords: vec3f=reflect(viewDir,worldNormal);coords= (reflectionMatrix* vec4f(coords,0)).xyz; #ifdef INVERTCUBICMAP coords.y*=-1.0; #endif return coords;} fn computeCubicLocalCoords(worldPos: vec4f,worldNormal: vec3f,eyePosition: vec3f,reflectionMatrix: mat4x4f,reflectionSize: vec3f,reflectionPosition: vec3f)->vec3f {var viewDir: vec3f=normalize(worldPos.xyz-eyePosition);var coords: vec3f=reflect(viewDir,worldNormal);coords=parallaxCorrectNormal(worldPos.xyz,coords,reflectionSize,reflectionPosition);coords=(reflectionMatrix* vec4f(coords,0)).xyz; #ifdef INVERTCUBICMAP coords.y*=-1.0; #endif return coords;} fn computeProjectionCoords(worldPos: vec4f,view: mat4x4f,reflectionMatrix: mat4x4f)->vec3f {return (reflectionMatrix*(view*worldPos)).xyz;} fn computeSkyBoxCoords(positionW: vec3f,reflectionMatrix: mat4x4f)->vec3f {return (reflectionMatrix* vec4f(positionW,1.)).xyz;} #ifdef REFLECTION fn computeReflectionCoords(worldPos: vec4f,worldNormal: vec3f)->vec3f { #ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED var direction: vec3f=normalize(fragmentInputs.vDirectionW);return computeMirroredFixedEquirectangularCoords(worldPos,worldNormal,direction); #endif #ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED var direction: vec3f=normalize(fragmentInputs.vDirectionW);return computeFixedEquirectangularCoords(worldPos,worldNormal,direction); #endif #ifdef REFLECTIONMAP_EQUIRECTANGULAR return computeEquirectangularCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix); #endif #ifdef REFLECTIONMAP_SPHERICAL return computeSphericalCoords(worldPos,worldNormal,scene.view,uniforms.reflectionMatrix); #endif #ifdef REFLECTIONMAP_PLANAR return computePlanarCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix); #endif #ifdef REFLECTIONMAP_CUBIC #ifdef USE_LOCAL_REFLECTIONMAP_CUBIC return computeCubicLocalCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix,uniforms.vReflectionSize,uniforms.vReflectionPosition); #else return computeCubicCoords(worldPos,worldNormal,scene.vEyePosition.xyz,uniforms.reflectionMatrix); #endif #endif #ifdef REFLECTIONMAP_PROJECTION return computeProjectionCoords(worldPos,scene.view,uniforms.reflectionMatrix); #endif #ifndef REFLECTIONMAP_CUBIC #ifdef REFLECTIONMAP_SKYBOX return computeSkyBoxCoords(fragmentInputs.vPositionUVW,uniforms.reflectionMatrix); #endif #endif #ifdef REFLECTIONMAP_EXPLICIT return vec3f(0,0,0); #endif } #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name123]) { ShaderStore.IncludesShadersStoreWGSL[name123] = shader123; } reflectionFunctionWGSL = { name: name123, shader: shader123 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/imageProcessingDeclaration.js var name124, shader124, imageProcessingDeclarationWGSL; var init_imageProcessingDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/imageProcessingDeclaration.js"() { init_shaderStore(); name124 = "imageProcessingDeclaration"; shader124 = `#ifdef EXPOSURE uniform exposureLinear: f32; #endif #ifdef CONTRAST uniform contrast: f32; #endif #if defined(VIGNETTE) || defined(DITHER) uniform vInverseScreenSize: vec2f; #endif #ifdef VIGNETTE uniform vignetteSettings1: vec4f;uniform vignetteSettings2: vec4f; #endif #ifdef COLORCURVES uniform vCameraColorCurveNegative: vec4f;uniform vCameraColorCurveNeutral: vec4f;uniform vCameraColorCurvePositive: vec4f; #endif #ifdef COLORGRADING #ifdef COLORGRADING3D var txColorTransformSampler: sampler;var txColorTransform: texture_3d; #else var txColorTransformSampler: sampler;var txColorTransform: texture_2d; #endif uniform colorTransformSettings: vec4f; #endif #ifdef DITHER uniform ditherIntensity: f32; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name124]) { ShaderStore.IncludesShadersStoreWGSL[name124] = shader124; } imageProcessingDeclarationWGSL = { name: name124, shader: shader124 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/imageProcessingFunctions.js var name125, shader125, imageProcessingFunctionsWGSL; var init_imageProcessingFunctions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/imageProcessingFunctions.js"() { init_shaderStore(); name125 = "imageProcessingFunctions"; shader125 = `#if TONEMAPPING==3 const PBRNeutralStartCompression: f32=0.8-0.04;const PBRNeutralDesaturation: f32=0.15;fn PBRNeutralToneMapping( color: vec3f )->vec3f {var x: f32=min(color.r,min(color.g,color.b));var offset: f32=select(0.04,x-6.25*x*x,x<0.08);var result=color;result-=offset;var peak: f32=max(result.r,max(result.g,result.b));if (peakvec3f {var a: vec3f=v*(v+0.0245786)-0.000090537;var b: vec3f=v*(0.983729*v+0.4329510)+0.238081;return a/b;} fn ACESFitted(color: vec3f)->vec3f {var output=ACESInputMat*color;output=RRTAndODTFit(output);output=ACESOutputMat*output;output=saturateVec3(output);return output;} #endif #define CUSTOM_IMAGEPROCESSINGFUNCTIONS_DEFINITIONS fn applyImageProcessing(result: vec4f)->vec4f { #define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATSTART var rgb=result.rgb;; #ifdef EXPOSURE rgb*=uniforms.exposureLinear; #endif #ifdef VIGNETTE var viewportXY: vec2f=fragmentInputs.position.xy*uniforms.vInverseScreenSize;viewportXY=viewportXY*2.0-1.0;var vignetteXY1: vec3f= vec3f(viewportXY*uniforms.vignetteSettings1.xy+uniforms.vignetteSettings1.zw,1.0);var vignetteTerm: f32=dot(vignetteXY1,vignetteXY1);var vignette: f32=pow(vignetteTerm,uniforms.vignetteSettings2.w);var vignetteColor: vec3f=uniforms.vignetteSettings2.rgb; #ifdef VIGNETTEBLENDMODEMULTIPLY var vignetteColorMultiplier: vec3f=mix(vignetteColor, vec3f(1,1,1),vignette);rgb*=vignetteColorMultiplier; #endif #ifdef VIGNETTEBLENDMODEOPAQUE rgb=mix(vignetteColor,rgb,vignette); #endif #endif #if TONEMAPPING==3 rgb=PBRNeutralToneMapping(rgb); #elif TONEMAPPING==2 rgb=ACESFitted(rgb); #elif TONEMAPPING==1 const tonemappingCalibration: f32=1.590579;rgb=1.0-exp2(-tonemappingCalibration*rgb); #endif rgb=toGammaSpaceVec3(rgb);rgb=saturateVec3(rgb); #ifdef CONTRAST var resultHighContrast: vec3f=rgb*rgb*(3.0-2.0*rgb);if (uniforms.contrast<1.0) {rgb=mix( vec3f(0.5,0.5,0.5),rgb,uniforms.contrast);} else {rgb=mix(rgb,resultHighContrast,uniforms.contrast-1.0);} rgb=max(rgb,vec3f(0.)); #endif #ifdef COLORGRADING var colorTransformInput: vec3f=rgb*uniforms.colorTransformSettings.xxx+uniforms.colorTransformSettings.yyy; #ifdef COLORGRADING3D var colorTransformOutput: vec3f=textureSample(txColorTransform,txColorTransformSampler,colorTransformInput).rgb; #else var colorTransformOutput: vec3f=textureSample(txColorTransform,txColorTransformSampler,colorTransformInput,uniforms.colorTransformSettings.yz).rgb; #endif rgb=mix(rgb,colorTransformOutput,uniforms.colorTransformSettings.www); #endif #ifdef COLORCURVES var luma: f32=getLuminance(rgb);var curveMix: vec2f=clamp( vec2f(luma*3.0-1.5,luma*-3.0+1.5), vec2f(0.0), vec2f(1.0));var colorCurve: vec4f=uniforms.vCameraColorCurveNeutral+curveMix.x*uniforms.vCameraColorCurvePositive-curveMix.y*uniforms.vCameraColorCurveNegative;rgb*=colorCurve.rgb;rgb=mix( vec3f(luma),rgb,colorCurve.a); #endif #ifdef DITHER var rand: f32=getRand(fragmentInputs.position.xy*uniforms.vInverseScreenSize);var dither: f32=mix(-uniforms.ditherIntensity,uniforms.ditherIntensity,rand);rgb=saturateVec3(rgb+ vec3f(dither)); #endif #define CUSTOM_IMAGEPROCESSINGFUNCTIONS_UPDATERESULT_ATEND return vec4f(rgb,result.a);}`; if (!ShaderStore.IncludesShadersStoreWGSL[name125]) { ShaderStore.IncludesShadersStoreWGSL[name125] = shader125; } imageProcessingFunctionsWGSL = { name: name125, shader: shader125 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpFragmentMainFunctions.js var name126, shader126, bumpFragmentMainFunctionsWGSL; var init_bumpFragmentMainFunctions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpFragmentMainFunctions.js"() { init_shaderStore(); name126 = "bumpFragmentMainFunctions"; shader126 = `#if defined(BUMP) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) || defined(DETAIL) #if defined(TANGENT) && defined(NORMAL) varying vTBN0: vec3f;varying vTBN1: vec3f;varying vTBN2: vec3f; #endif #ifdef OBJECTSPACE_NORMALMAP uniform normalMatrix: mat4x4f;fn toNormalMatrix(m: mat4x4f)->mat4x4f {var a00=m[0][0];var a01=m[0][1];var a02=m[0][2];var a03=m[0][3];var a10=m[1][0];var a11=m[1][1];var a12=m[1][2];var a13=m[1][3];var a20=m[2][0]; var a21=m[2][1];var a22=m[2][2];var a23=m[2][3];var a30=m[3][0]; var a31=m[3][1];var a32=m[3][2];var a33=m[3][3];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;var det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;var mi=mat4x4( (a11*b11-a12*b10+a13*b09)/det, (a02*b10-a01*b11-a03*b09)/det, (a31*b05-a32*b04+a33*b03)/det, (a22*b04-a21*b05-a23*b03)/det, (a12*b08-a10*b11-a13*b07)/det, (a00*b11-a02*b08+a03*b07)/det, (a32*b02-a30*b05-a33*b01)/det, (a20*b05-a22*b02+a23*b01)/det, (a10*b10-a11*b08+a13*b06)/det, (a01*b08-a00*b10-a03*b06)/det, (a30*b04-a31*b02+a33*b00)/det, (a21*b02-a20*b04-a23*b00)/det, (a11*b07-a10*b09-a12*b06)/det, (a00*b09-a01*b07+a02*b06)/det, (a31*b01-a30*b03-a32*b00)/det, (a20*b03-a21*b01+a22*b00)/det);return mat4x4(mi[0][0],mi[1][0],mi[2][0],mi[3][0], mi[0][1],mi[1][1],mi[2][1],mi[3][1], mi[0][2],mi[1][2],mi[2][2],mi[3][2], mi[0][3],mi[1][3],mi[2][3],mi[3][3]);} #endif fn perturbNormalBase(cotangentFrame: mat3x3f,normal: vec3f,scale: f32)->vec3f {var output=normal; #ifdef NORMALXYSCALE output=normalize(output* vec3f(scale,scale,1.0)); #endif return normalize(cotangentFrame*output);} fn perturbNormal(cotangentFrame: mat3x3f,textureSample: vec3f,scale: f32)->vec3f {return perturbNormalBase(cotangentFrame,textureSample*2.0-1.0,scale);} fn cotangent_frame(normal: vec3f,p: vec3f,uv: vec2f,tangentSpaceParams: vec2f)->mat3x3f {var dp1: vec3f=dpdx(p);var dp2: vec3f=dpdy(p);var duv1: vec2f=dpdx(uv);var duv2: vec2f=dpdy(uv);var dp2perp: vec3f=cross(dp2,normal);var dp1perp: vec3f=cross(normal,dp1);var tangent: vec3f=dp2perp*duv1.x+dp1perp*duv2.x;var bitangent: vec3f=dp2perp*duv1.y+dp1perp*duv2.y;tangent*=tangentSpaceParams.x;bitangent*=tangentSpaceParams.y;var det: f32=max(dot(tangent,tangent),dot(bitangent,bitangent));var invmax: f32=select(inverseSqrt(det),0.0,det==0.0);return mat3x3f(tangent*invmax,bitangent*invmax,normal);} #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name126]) { ShaderStore.IncludesShadersStoreWGSL[name126] = shader126; } bumpFragmentMainFunctionsWGSL = { name: name126, shader: shader126 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpFragmentFunctions.js var name127, shader127, bumpFragmentFunctionsWGSL; var init_bumpFragmentFunctions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpFragmentFunctions.js"() { init_shaderStore(); init_samplerFragmentDeclaration(); name127 = "bumpFragmentFunctions"; shader127 = `#if defined(BUMP) #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) #endif #if defined(DETAIL) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) #endif #if defined(BUMP) && defined(PARALLAX) const minSamples: f32=4.;const maxSamples: f32=15.;const iMaxSamples: i32=15;fn parallaxOcclusion(vViewDirCoT: vec3f,vNormalCoT: vec3f,texCoord: vec2f,parallaxScale: f32)->vec2f {var parallaxLimit: f32=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;var vOffsetDir: vec2f=normalize(vViewDirCoT.xy);var vMaxOffset: vec2f=vOffsetDir*parallaxLimit;var numSamples: f32=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));var stepSize: f32=1.0/numSamples;var currRayHeight: f32=1.0;var vCurrOffset: vec2f= vec2f(0,0);var vLastOffset: vec2f= vec2f(0,0);var lastSampledHeight: f32=1.0;var currSampledHeight: f32=1.0;var keepWorking: bool=true;for (var i: i32=0; icurrRayHeight) {var delta1: f32=currSampledHeight-currRayHeight;var delta2: f32=(currRayHeight+stepSize)-lastSampledHeight;var ratio: f32=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} else {currRayHeight-=stepSize;vLastOffset=vCurrOffset; #ifdef PARALLAX_RHS vCurrOffset-=stepSize*vMaxOffset; #else vCurrOffset+=stepSize*vMaxOffset; #endif lastSampledHeight=currSampledHeight;}} return vCurrOffset;} fn parallaxOffset(viewDir: vec3f,heightScale: f32)->vec2f {var height: f32=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).w;var texCoordOffset: vec2f=heightScale*viewDir.xy*height; #ifdef PARALLAX_RHS return texCoordOffset; #else return -texCoordOffset; #endif } #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name127]) { ShaderStore.IncludesShadersStoreWGSL[name127] = shader127; } bumpFragmentFunctionsWGSL = { name: name127, shader: shader127 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogFragmentDeclaration.js var name128, shader128, fogFragmentDeclarationWGSL; var init_fogFragmentDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogFragmentDeclaration.js"() { init_shaderStore(); name128 = "fogFragmentDeclaration"; shader128 = `#ifdef FOG #define FOGMODE_NONE 0. #define FOGMODE_EXP 1. #define FOGMODE_EXP2 2. #define FOGMODE_LINEAR 3. const E=2.71828;uniform vFogInfos: vec4f;uniform vFogColor: vec3f;varying vFogDistance: vec3f;fn CalcFogFactor()->f32 {var fogCoeff: f32=1.0;var fogStart: f32=uniforms.vFogInfos.y;var fogEnd: f32=uniforms.vFogInfos.z;var fogDensity: f32=uniforms.vFogInfos.w;var fogDistance: f32=length(fragmentInputs.vFogDistance);if (FOGMODE_LINEAR==uniforms.vFogInfos.x) {fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);} else if (FOGMODE_EXP==uniforms.vFogInfos.x) {fogCoeff=1.0/pow(E,fogDistance*fogDensity);} else if (FOGMODE_EXP2==uniforms.vFogInfos.x) {fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} return clamp(fogCoeff,0.0,1.0);} #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name128]) { ShaderStore.IncludesShadersStoreWGSL[name128] = shader128; } fogFragmentDeclarationWGSL = { name: name128, shader: shader128 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpFragment.js var name129, shader129, bumpFragmentWGSL; var init_bumpFragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/bumpFragment.js"() { init_shaderStore(); name129 = "bumpFragment"; shader129 = `var uvOffset: vec2f= vec2f(0.0,0.0); #if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) #ifdef NORMALXYSCALE var normalScale: f32=1.0; #elif defined(BUMP) var normalScale: f32=uniforms.vBumpInfos.y; #else var normalScale: f32=1.0; #endif #if defined(TANGENT) && defined(NORMAL) var TBN: mat3x3f=mat3x3(input.vTBN0,input.vTBN1,input.vTBN2); #elif defined(BUMP) var TBNUV: vec2f=select(-fragmentInputs.vBumpUV,fragmentInputs.vBumpUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV,uniforms.vTangentSpaceParams); #else var TBNUV: vec2f=select(-fragmentInputs.vDetailUV,fragmentInputs.vDetailUV,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW*normalScale,input.vPositionW,TBNUV, vec2f(1.,1.)); #endif #elif defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) var TBN: mat3x3f=mat3x3(input.vTBN0,input.vTBN1,input.vTBN2); #else var TBNUV: vec2f=select( -fragmentInputs.vMainUV1,fragmentInputs.vMainUV1,fragmentInputs.frontFacing);var TBN: mat3x3f=cotangent_frame(normalW,input.vPositionW,TBNUV, vec2f(1.,1.)); #endif #endif #ifdef PARALLAX var invTBN: mat3x3f=transposeMat3(TBN); #ifdef PARALLAXOCCLUSION uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,fragmentInputs.vBumpUV,uniforms.vBumpInfos.z); #else uvOffset=parallaxOffset(invTBN*viewDirectionW,uniforms.vBumpInfos.z); #endif #endif #ifdef DETAIL var detailColor: vec4f=textureSample(detailSampler,detailSamplerSampler,fragmentInputs.vDetailUV+uvOffset);var detailNormalRG: vec2f=detailColor.wy*2.0-1.0;var detailNormalB: f32=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));var detailNormal: vec3f= vec3f(detailNormalRG,detailNormalB); #endif #ifdef BUMP #ifdef OBJECTSPACE_NORMALMAP #define CUSTOM_FRAGMENT_BUMP_FRAGMENT normalW=normalize(textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3x3f(uniforms.normalMatrix[0].xyz,uniforms.normalMatrix[1].xyz,uniforms.normalMatrix[2].xyz)*normalW); #elif !defined(DETAIL) normalW=perturbNormal(TBN,textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV+uvOffset).xyz,uniforms.vBumpInfos.y); #else var bumpNormal: vec3f=textureSample(bumpSampler,bumpSamplerSampler,fragmentInputs.vBumpUV+uvOffset).xyz*2.0-1.0; #if DETAIL_NORMALBLENDMETHOD==0 detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);var blendedNormal: vec3f=normalize( vec3f(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); #elif DETAIL_NORMALBLENDMETHOD==1 detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);bumpNormal+= vec3f(0.0,0.0,1.0);detailNormal*= vec3f(-1.0,-1.0,1.0);var blendedNormal: vec3f=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; #endif normalW=perturbNormalBase(TBN,blendedNormal,uniforms.vBumpInfos.y); #endif #elif defined(DETAIL) detailNormal=vec3f(detailNormal.xy*uniforms.vDetailInfos.z,detailNormal.z);normalW=perturbNormalBase(TBN,detailNormal,uniforms.vDetailInfos.z); #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name129]) { ShaderStore.IncludesShadersStoreWGSL[name129] = shader129; } bumpFragmentWGSL = { name: name129, shader: shader129 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/decalFragment.js var name130, shader130, decalFragmentWGSL; var init_decalFragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/decalFragment.js"() { init_shaderStore(); name130 = "decalFragment"; shader130 = `#ifdef DECAL var decalTempColor=decalColor.rgb;var decalTempAlpha=decalColor.a; #ifdef GAMMADECAL decalTempColor=toLinearSpaceVec3(decalColor.rgb); #endif #ifdef DECAL_SMOOTHALPHA decalTempAlpha=decalColor.a*decalColor.a; #endif surfaceAlbedo=mix(surfaceAlbedo.rgb,decalTempColor,decalTempAlpha); #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name130]) { ShaderStore.IncludesShadersStoreWGSL[name130] = shader130; } decalFragmentWGSL = { name: name130, shader: shader130 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/depthPrePass.js var name131, shader131, depthPrePassWGSL; var init_depthPrePass = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/depthPrePass.js"() { init_shaderStore(); name131 = "depthPrePass"; shader131 = `#ifdef DEPTHPREPASS fragmentOutputs.color= vec4f(0.,0.,0.,1.0);return fragmentOutputs; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name131]) { ShaderStore.IncludesShadersStoreWGSL[name131] = shader131; } depthPrePassWGSL = { name: name131, shader: shader131 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightFragment.js var name132, shader132, lightFragmentWGSL; var init_lightFragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/lightFragment.js"() { init_shaderStore(); name132 = "lightFragment"; shader132 = `#ifdef LIGHT{X} #if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) #else var diffuse{X}: vec4f=light{X}.vLightDiffuse; #define CUSTOM_LIGHT{X}_COLOR #if defined(PBR) && defined(CLUSTLIGHT{X}) {let sliceIndex=min(getClusteredSliceIndex(light{X}.vSliceData,fragmentInputs.vViewDepth),CLUSTLIGHT_SLICES-1);info=computeClusteredLighting( lightDataTexture{X}, &tileMaskBuffer{X}, light{X}.vLightData, vec2u(light{X}.vSliceRanges[sliceIndex].xy), viewDirectionW, normalW, fragmentInputs.vPositionW, surfaceAlbedo, reflectivityOut, #ifdef IRIDESCENCE iridescenceIntensity, #endif #ifdef SS_TRANSLUCENCY subSurfaceOut, #endif #ifdef SPECULARTERM AARoughnessFactors.x, #endif #ifdef ANISOTROPIC anisotropicOut, #endif #ifdef SHEEN sheenOut, #endif #ifdef CLEARCOAT clearcoatOut, #endif );} #elif defined(PBR) #ifdef SPOTLIGHT{X} preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,fragmentInputs.vPositionW); #elif defined(POINTLIGHT{X}) preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,fragmentInputs.vPositionW); #elif defined(HEMILIGHT{X}) preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); #elif defined(DIRLIGHT{X}) preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); #elif defined(AREALIGHT{X}) && defined(AREALIGHTSUPPORTED) preInfo=computeAreaPreLightingInfo(areaLightsLTC1Sampler,areaLightsLTC1SamplerSampler,areaLightsLTC2Sampler,areaLightsLTC2SamplerSampler,viewDirectionW,normalW,fragmentInputs.vPositionW,light{X}.vLightData.xyz,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,roughness); #endif preInfo.NdotV=NdotV; #ifdef SPOTLIGHT{X} #ifdef LIGHT_FALLOFF_GLTF{X} preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); #ifdef IESLIGHTTEXTURE{X} preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X},iesLightTexture{X}Sampler); #else preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); #endif #elif defined(LIGHT_FALLOFF_PHYSICAL{X}) preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); #ifdef IESLIGHTTEXTURE{X} preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X},iesLightTexture{X}Sampler); #else preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w); #endif #elif defined(LIGHT_FALLOFF_STANDARD{X}) preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); #ifdef IESLIGHTTEXTURE{X} preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X},iesLightTexture{X}Sampler); #else preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w); #endif #else preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); #ifdef IESLIGHTTEXTURE{X} preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X},iesLightTexture{X}Sampler); #else preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); #endif #endif #elif defined(POINTLIGHT{X}) #ifdef LIGHT_FALLOFF_GLTF{X} preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); #elif defined(LIGHT_FALLOFF_PHYSICAL{X}) preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); #elif defined(LIGHT_FALLOFF_STANDARD{X}) preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); #else preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); #endif #else preInfo.attenuation=1.0; #endif #if defined(HEMILIGHT{X}) || defined(AREALIGHT{X}) preInfo.roughness=roughness; #else preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance); #endif preInfo.diffuseRoughness=diffuseRoughness;preInfo.surfaceAlbedo=surfaceAlbedo; #ifdef IRIDESCENCE preInfo.iridescenceIntensity=iridescenceIntensity; #endif #ifdef SS_TRANSLUCENCY info.diffuseTransmission=vec3f(0.0); #endif #ifdef HEMILIGHT{X} info.diffuse=computeHemisphericDiffuseLighting(preInfo,diffuse{X}.rgb,light{X}.vLightGround); #elif defined(AREALIGHT{X}) info.diffuse=computeAreaDiffuseLighting(preInfo,diffuse{X}.rgb); #elif defined(SS_TRANSLUCENCY) #ifndef SS_TRANSLUCENCY_LEGACY info.diffuse=computeDiffuseLighting(preInfo,diffuse{X}.rgb)*(1.0-subSurfaceOut.translucencyIntensity);info.diffuseTransmission=computeDiffuseTransmittedLighting(preInfo,diffuse{X}.rgb,subSurfaceOut.transmittance); #else info.diffuse=computeDiffuseTransmittedLighting(preInfo,diffuse{X}.rgb,subSurfaceOut.transmittance); #endif #else info.diffuse=computeDiffuseLighting(preInfo,diffuse{X}.rgb); #endif #ifdef SPECULARTERM #if AREALIGHT{X} info.specular=computeAreaSpecularLighting(preInfo,light{X}.vLightSpecular.rgb,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90); #else #if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR) {let metalFresnel: vec3f=vec3f(reflectivityOut.specularWeight)*getF82Specular(preInfo.VdotH,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90,reflectivityOut.roughness);let dielectricFresnel: vec3f=fresnelSchlickGGXVec3(preInfo.VdotH,reflectivityOut.dielectricColorF0,reflectivityOut.colorReflectanceF90);coloredFresnel=mix(dielectricFresnel,metalFresnel,reflectivityOut.metallic);} #else coloredFresnel=fresnelSchlickGGXVec3(preInfo.VdotH,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90); #endif #ifndef LEGACY_SPECULAR_ENERGY_CONSERVATION {let NdotH: f32=dot(normalW,preInfo.H);let fresnel: vec3f=fresnelSchlickGGXVec3(NdotH,vec3f(reflectanceF0),specularEnvironmentR90);info.diffuse*=(vec3f(1.0)-fresnel);} #endif #ifdef ANISOTROPIC info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb); #else info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,coloredFresnel,AARoughnessFactors.x,diffuse{X}.rgb); #endif #endif #endif #ifndef AREALIGHT{X} #ifdef SHEEN #ifdef SHEEN_LINKWITHALBEDO preInfo.roughness=sheenOut.sheenIntensity; #else #ifdef HEMILIGHT{X} preInfo.roughness=sheenOut.sheenRoughness; #else preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); #endif #endif info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb); #endif #ifdef CLEARCOAT #ifdef HEMILIGHT{X} preInfo.roughness=clearcoatOut.clearCoatRoughness; #else preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); #endif info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,diffuse{X}.rgb); #ifdef CLEARCOAT_TINT absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption; #ifdef SS_TRANSLUCENCY info.diffuseTransmission*=absorption; #endif #ifdef SPECULARTERM info.specular*=absorption; #endif #endif info.diffuse*=info.clearCoat.w; #ifdef SS_TRANSLUCENCY info.diffuseTransmission*=info.clearCoat.w; #endif #ifdef SPECULARTERM info.specular*=info.clearCoat.w; #endif #ifdef SHEEN info.sheen*=info.clearCoat.w; #endif #endif #endif #else #ifdef SPOTLIGHT{X} #ifdef IESLIGHTTEXTURE{X} info=computeIESSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness,iesLightTexture{X},iesLightTexture{X}Sampler); #else info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness); #endif #elif defined(HEMILIGHT{X}) info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness); #elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X}) info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness); #elif define(AREALIGHT{X}) && defined(AREALIGHTSUPPORTED) info=computeAreaLighting(areaLightsLTC1Sampler,areaLightsLTC1SamplerSampler,areaLightsLTC2Sampler,areaLightsLTC2SamplerSampler,viewDirectionW,normalW,fragmentInputs.vPositionW,light{X}.vLightData.xyz,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,diffuse{X}.rgb,light{X}.vLightSpecular.rgb, #ifdef AREALIGHTNOROUGHTNESS 0.5 #else uniforms.vReflectionInfos.y #endif ); #elif defined(CLUSTLIGHT{X}) {let sliceIndex=min(getClusteredSliceIndex(light{X}.vSliceData,fragmentInputs.vViewDepth),CLUSTLIGHT_SLICES-1);info=computeClusteredLighting(lightDataTexture{X},&tileMaskBuffer{X},viewDirectionW,normalW,light{X}.vLightData,vec2u(light{X}.vSliceRanges[sliceIndex].xy),glossiness);} #endif #endif #ifdef PROJECTEDLIGHTTEXTURE{X} info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},projectionLightTexture{X}Sampler,uniforms.textureProjectionMatrix{X},fragmentInputs.vPositionW); #endif #endif #ifdef SHADOW{X} #ifdef SHADOWCSMDEBUG{X} var shadowDebug{X}: vec3f; #endif #ifdef SHADOWCSM{X} #ifdef SHADOWCSMUSESHADOWMAXZ{X} var index{X}: i32=-1; #else var index{X}: i32=SHADOWCSMNUM_CASCADES{X}-1; #endif var diff{X}: f32=0.;vPositionFromLight{X}[0]=fragmentInputs.vPositionFromLight{X}_0;vPositionFromLight{X}[1]=fragmentInputs.vPositionFromLight{X}_1;vPositionFromLight{X}[2]=fragmentInputs.vPositionFromLight{X}_2;vPositionFromLight{X}[3]=fragmentInputs.vPositionFromLight{X}_3;vDepthMetric{X}[0]=fragmentInputs.vDepthMetric{X}_0;vDepthMetric{X}[1]=fragmentInputs.vDepthMetric{X}_1;vDepthMetric{X}[2]=fragmentInputs.vDepthMetric{X}_2;vDepthMetric{X}[3]=fragmentInputs.vDepthMetric{X}_3;for (var i:i32=0; i=0.) {index{X}=i;break;}} #ifdef SHADOWCSMUSESHADOWMAXZ{X} if (index{X}>=0) #endif { #if defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); #else shadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); #endif #else shadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #ifdef SHADOWCSMDEBUG{X} shadowDebug{X}=vec3f(shadow)*vCascadeColorsMultiplier{X}[index{X}]; #endif #ifndef SHADOWCSMNOBLEND{X} var frustumLength:f32=uniforms.frustumLengths{X}[index{X}];var diffRatio:f32=clamp(diff{X}/frustumLength,0.,1.)*uniforms.cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) {index{X}+=1;var nextShadow: f32=0.; #if defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) nextShadow=computeShadowWithCSMPCF1(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],,shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) nextShadow=computeShadowWithCSMPCF3(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else nextShadow=computeShadowWithCSMPCF5(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) nextShadow=computeShadowWithCSMPCSS16(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); #elif defined(SHADOWMEDIUMQUALITY{X}) nextShadow=computeShadowWithCSMPCSS32(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); #else nextShadow=computeShadowWithCSMPCSS64(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,uniforms.lightSizeUVCorrection{X}[index{X}],uniforms.depthCorrection{X}[index{X}],uniforms.penumbraDarkness{X}); #endif #else nextShadow=computeShadowCSM(index{X},vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif shadow=mix(nextShadow,shadow,diffRatio); #ifdef SHADOWCSMDEBUG{X} shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); #endif } #endif } #elif defined(SHADOWCLOSEESM{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithCloseESMCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); #else shadow=computeShadowWithCloseESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWESM{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithESMCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); #else shadow=computeShadowWithESM(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPOISSON{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithPoissonSamplingCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); #else shadow=computeShadowWithPoissonSampling(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithPCF1(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithPCF3(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithPCF5(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithPCSS16(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithPCSS32(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithPCSS64(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},depthTexture{X},depthTexture{X}Sampler,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #else #if defined(SHADOWCUBE{X}) shadow=computeShadowCube(fragmentInputs.vPositionW,light{X}.vLightData.xyz,shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.depthValues); #else shadow=computeShadow(fragmentInputs.vPositionFromLight{X},fragmentInputs.vDepthMetric{X},shadowTexture{X},shadowTexture{X}Sampler,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #endif #ifdef SHADOWONLY #ifndef SHADOWINUSE #define SHADOWINUSE #endif globalShadow+=shadow;shadowLightCount+=1.0; #endif #else shadow=1.; #endif aggShadow+=shadow;numLights+=1.0; #ifndef SHADOWONLY #ifdef CUSTOMUSERLIGHTING diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); #ifdef SPECULARTERM specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); #endif #elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) diffuseBase+=lightmapColor.rgb*shadow; #ifdef SPECULARTERM #ifndef LIGHTMAPNOSPECULAR{X} specularBase+=info.specular*shadow*lightmapColor.rgb; #endif #endif #ifdef CLEARCOAT #ifndef LIGHTMAPNOSPECULAR{X} clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; #endif #endif #ifdef SHEEN #ifndef LIGHTMAPNOSPECULAR{X} sheenBase+=info.sheen.rgb*shadow; #endif #endif #else #ifdef SHADOWCSMDEBUG{X} diffuseBase+=info.diffuse*shadowDebug{X}; #else diffuseBase+=info.diffuse*shadow; #endif #ifdef SS_TRANSLUCENCY diffuseTransmissionBase+=info.diffuseTransmission*shadow; #endif #ifdef SPECULARTERM specularBase+=info.specular*shadow; #endif #ifdef CLEARCOAT clearCoatBase+=info.clearCoat.rgb*shadow; #endif #ifdef SHEEN sheenBase+=info.sheen.rgb*shadow; #endif #endif #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name132]) { ShaderStore.IncludesShadersStoreWGSL[name132] = shader132; } lightFragmentWGSL = { name: name132, shader: shader132 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/logDepthFragment.js var name133, shader133, logDepthFragmentWGSL; var init_logDepthFragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/logDepthFragment.js"() { init_shaderStore(); name133 = "logDepthFragment"; shader133 = `#ifdef LOGARITHMICDEPTH fragmentOutputs.fragDepth=log2(fragmentInputs.vFragmentDepth)*uniforms.logarithmicDepthConstant*0.5; #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name133]) { ShaderStore.IncludesShadersStoreWGSL[name133] = shader133; } logDepthFragmentWGSL = { name: name133, shader: shader133 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogFragment.js var name134, shader134, fogFragmentWGSL; var init_fogFragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/fogFragment.js"() { init_shaderStore(); name134 = "fogFragment"; shader134 = `#ifdef FOG var fog: f32=CalcFogFactor(); #ifdef PBR fog=toLinearSpace(fog); #endif color= vec4f(mix(uniforms.vFogColor,color.rgb,fog),color.a); #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name134]) { ShaderStore.IncludesShadersStoreWGSL[name134] = shader134; } fogFragmentWGSL = { name: name134, shader: shader134 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/oitFragment.js var name135, shader135, oitFragmentWGSL; var init_oitFragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/oitFragment.js"() { init_shaderStore(); name135 = "oitFragment"; shader135 = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY var fragDepth: f32=fragmentInputs.position.z; #ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS var halfFloat: u32=pack2x16float( vec2f(fragDepth));var full: vec2f=unpack2x16float(halfFloat);fragDepth=full.x; #endif var fragCoord: vec2i=vec2i(fragmentInputs.position.xy);var lastDepth: vec2f=textureLoad(oitDepthSampler,fragCoord,0).rg;var lastFrontColor: vec4f=textureLoad(oitFrontColorSampler,fragCoord,0);fragmentOutputs.depth=vec2f(-MAX_DEPTH);fragmentOutputs.frontColor=lastFrontColor;fragmentOutputs.backColor= vec4f(0.0); #ifdef USE_REVERSE_DEPTHBUFFER var furthestDepth: f32=-lastDepth.x;var nearestDepth: f32=lastDepth.y; #else var nearestDepth: f32=-lastDepth.x;var furthestDepth: f32=lastDepth.y; #endif var alphaMultiplier: f32=1.0-lastFrontColor.a; #ifdef USE_REVERSE_DEPTHBUFFER if (fragDepth>nearestDepth || fragDepthfurthestDepth) { #endif return fragmentOutputs;} #ifdef USE_REVERSE_DEPTHBUFFER if (fragDepthfurthestDepth) { #else if (fragDepth>nearestDepth && fragDepth defaultPixelShaderWGSL }); var name136, shader136, defaultPixelShaderWGSL; var init_default_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/default.fragment.js"() { init_shaderStore(); init_defaultUboDeclaration(); init_prePassDeclaration(); init_oitDeclaration(); init_mainUVVaryingDeclaration(); init_helperFunctions(); init_lightUboDeclaration(); init_lightsFragmentFunctions(); init_shadowsFragmentFunctions(); init_samplerFragmentDeclaration(); init_fresnelFunction(); init_reflectionFunction(); init_imageProcessingDeclaration(); init_imageProcessingFunctions(); init_bumpFragmentMainFunctions(); init_bumpFragmentFunctions(); init_clipPlaneFragmentDeclaration(); init_logDepthDeclaration(); init_fogFragmentDeclaration(); init_clipPlaneFragment(); init_bumpFragment(); init_decalFragment(); init_depthPrePass(); init_lightFragment(); init_logDepthFragment(); init_fogFragment(); init_oitFragment(); name136 = "defaultPixelShader"; shader136 = `#include #include[SCENE_MRT_COUNT] #include #define CUSTOM_FRAGMENT_BEGIN varying vPositionW: vec3f; #ifdef NORMAL varying vNormalW: vec3f; #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vColor: vec4f; #endif #if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0 varying vViewDepth: f32; #endif #include[1..7] #include #include[0..maxSimultaneousLights] #include #include #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) #ifdef REFRACTION #ifdef REFRACTIONMAP_3D var refractionCubeSamplerSampler: sampler;var refractionCubeSampler: texture_cube; #else var refraction2DSamplerSampler: sampler;var refraction2DSampler: texture_2d; #endif #endif #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) #endif #include #ifdef REFLECTION #ifdef REFLECTIONMAP_3D var reflectionCubeSamplerSampler: sampler;var reflectionCubeSampler: texture_cube; #else var reflection2DSamplerSampler: sampler;var reflection2DSampler: texture_2d; #endif #ifdef REFLECTIONMAP_SKYBOX varying vPositionUVW: vec3f; #else #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vDirectionW: vec3f; #endif #endif #include #endif #include #include #include #include #include #include #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include var viewDirectionW: vec3f=normalize(scene.vEyePosition.xyz-fragmentInputs.vPositionW);var baseColor: vec4f= vec4f(1.,1.,1.,1.);var diffuseColor: vec3f=uniforms.vDiffuseColor.rgb;var alpha: f32=uniforms.vDiffuseColor.a; #ifdef NORMAL var normalW: vec3f=normalize(fragmentInputs.vNormalW); #else var normalW: vec3f=normalize(-cross(dpdx(fragmentInputs.vPositionW),dpdy(fragmentInputs.vPositionW))); #endif #include #ifdef TWOSIDEDLIGHTING normalW=select(-normalW,normalW,fragmentInputs.frontFacing); #endif #ifdef DIFFUSE baseColor=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vDiffuseUV+uvOffset); #if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) if (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) #endif #include #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) baseColor=vec4f(baseColor.rgb*fragmentInputs.vColor.rgb,baseColor.a); #endif #ifdef DETAIL baseColor=vec4f(baseColor.rgb*2.0*mix(0.5,detailColor.r,uniforms.vDetailInfos.y),baseColor.a); #endif #if defined(DECAL) && defined(DECAL_AFTER_DETAIL) var decalColor: vec4f=textureSample(decalSampler,decalSamplerSampler,fragmentInputs.vDecalUV+uvOffset); #include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) #endif #define CUSTOM_FRAGMENT_UPDATE_DIFFUSE var baseAmbientColor: vec3f= vec3f(1.,1.,1.); #ifdef AMBIENT baseAmbientColor=textureSample(ambientSampler,ambientSamplerSampler,fragmentInputs.vAmbientUV+uvOffset).rgb*uniforms.vAmbientInfos.y; #endif #define CUSTOM_FRAGMENT_BEFORE_LIGHTS var glossiness: f32=uniforms.vSpecularColor.a;var specularColor: vec3f=uniforms.vSpecularColor.rgb; #ifdef SPECULARTERM #ifdef SPECULAR var specularMapColor: vec4f=textureSample(specularSampler,specularSamplerSampler,fragmentInputs.vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; #ifdef GLOSSINESS glossiness=glossiness*specularMapColor.a; #endif #endif #endif var diffuseBase: vec3f= vec3f(0.,0.,0.);var info: lightingInfo; #ifdef SPECULARTERM var specularBase: vec3f= vec3f(0.,0.,0.); #endif var shadow: f32=1.;var aggShadow: f32=0.;var numLights: f32=0.; #ifdef LIGHTMAP var lightmapColor: vec4f=textureSample(lightmapSampler,lightmapSamplerSampler,fragmentInputs.vLightmapUV+uvOffset); #ifdef RGBDLIGHTMAP lightmapColor=vec4f(fromRGBD(lightmapColor),lightmapColor.a); #endif lightmapColor=vec4f(lightmapColor.rgb*uniforms.vLightmapInfos.y,lightmapColor.a); #endif #include[0..maxSimultaneousLights] aggShadow=aggShadow/numLights;var refractionColor: vec4f= vec4f(0.,0.,0.,1.); #ifdef REFRACTION var refractionVector: vec3f=normalize(refract(-viewDirectionW,normalW,uniforms.vRefractionInfos.y)); #ifdef REFRACTIONMAP_3D #ifdef USE_LOCAL_REFRACTIONMAP_CUBIC refractionVector=parallaxCorrectNormal(fragmentInputs.vPositionW,refractionVector,uniforms.vRefractionSize,uniforms.vRefractionPosition); #endif refractionVector.y=refractionVector.y*uniforms.vRefractionInfos.w;var refractionLookup: vec4f=textureSample(refractionCubeSampler,refractionCubeSamplerSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} #else var vRefractionUVW: vec3f= (uniforms.refractionMatrix*(scene.view* vec4f(fragmentInputs.vPositionW+refractionVector*uniforms.vRefractionInfos.z,1.0))).xyz;var refractionCoords: vec2f=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=textureSample(refraction2DSampler,refraction2DSamplerSampler,refractionCoords); #endif #ifdef RGBDREFRACTION refractionColor=vec4f(fromRGBD(refractionColor),refractionColor.a); #endif #ifdef IS_REFRACTION_LINEAR refractionColor=vec4f(toGammaSpaceVec3(refractionColor.rgb),refractionColor.a); #endif refractionColor=vec4f(refractionColor.rgb*uniforms.vRefractionInfos.x,refractionColor.a); #endif var reflectionColor: vec4f= vec4f(0.,0.,0.,1.); #ifdef REFLECTION var vReflectionUVW: vec3f=computeReflectionCoords( vec4f(fragmentInputs.vPositionW,1.0),normalW); #ifdef REFLECTIONMAP_OPPOSITEZ vReflectionUVW=vec3f(vReflectionUVW.x,vReflectionUVW.y,vReflectionUVW.z*-1.0); #endif #ifdef REFLECTIONMAP_3D #ifdef ROUGHNESS var bias: f32=uniforms.vReflectionInfos.y; #ifdef SPECULARTERM #ifdef SPECULAR #ifdef GLOSSINESS bias*=(1.0-specularMapColor.a); #endif #endif #endif reflectionColor=textureSampleLevel(reflectionCubeSampler,reflectionCubeSamplerSampler,vReflectionUVW,bias); #else reflectionColor=textureSample(reflectionCubeSampler,reflectionCubeSamplerSampler,vReflectionUVW); #endif #else var coords: vec2f=vReflectionUVW.xy; #ifdef REFLECTIONMAP_PROJECTION coords/=vReflectionUVW.z; #endif coords.y=1.0-coords.y;reflectionColor=textureSample(reflection2DSampler,reflection2DSamplerSampler,coords); #endif #ifdef RGBDREFLECTION reflectionColor=vec4f(fromRGBD(reflectionColor),reflectionColor.a); #endif #ifdef IS_REFLECTION_LINEAR reflectionColor=vec4f(toGammaSpaceVec3(reflectionColor.rgb),reflectionColor.a); #endif reflectionColor=vec4f(reflectionColor.rgb*uniforms.vReflectionInfos.x,reflectionColor.a); #ifdef REFLECTIONFRESNEL var reflectionFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.reflectionRightColor.a,uniforms.reflectionLeftColor.a); #ifdef REFLECTIONFRESNELFROMSPECULAR #ifdef SPECULARTERM reflectionColor=vec4f(reflectionColor.rgb*specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a); #else reflectionColor=vec4f(reflectionColor.rgb*uniforms.reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a); #endif #else reflectionColor=vec4f(reflectionColor.rgb*uniforms.reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*uniforms.reflectionRightColor.rgb,reflectionColor.a); #endif #endif #endif #ifdef REFRACTIONFRESNEL var refractionFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.refractionRightColor.a,uniforms.refractionLeftColor.a);refractionColor=vec4f(refractionColor.rgb*uniforms.refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*uniforms.refractionRightColor.rgb,refractionColor.a); #endif #ifdef OPACITY var opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vOpacityUV+uvOffset); #ifdef OPACITYRGB opacityMap=vec4f(opacityMap.rgb* vec3f(0.3,0.59,0.11),opacityMap.a);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* uniforms.vOpacityInfos.y; #else alpha*=opacityMap.a*uniforms.vOpacityInfos.y; #endif #endif #if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) alpha*=fragmentInputs.vColor.a; #endif #ifdef OPACITYFRESNEL var opacityFresnelTerm: f32=computeFresnelTerm(viewDirectionW,normalW,uniforms.opacityParts.z,uniforms.opacityParts.w);alpha+=uniforms.opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*uniforms.opacityParts.y; #endif #ifdef ALPHATEST #ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS if (alpha #include #ifdef IMAGEPROCESSINGPOSTPROCESS color=vec4f(toLinearSpaceVec3(color.rgb),color.a); #else #ifdef IMAGEPROCESSING color=vec4f(toLinearSpaceVec3(color.rgb),color.a);color=applyImageProcessing(color); #endif #endif color=vec4f(color.rgb,color.a*mesh.visibility); #ifdef PREMULTIPLYALPHA color=vec4f(color.rgb*color.a, color.a); #endif #define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR #ifdef PREPASS #if SCENE_MRT_COUNT>0 var writeGeometryInfo: f32=select(0.0,1.0,color.a>0.4);var fragData: array,SCENE_MRT_COUNT>; #ifdef PREPASS_COLOR fragData[PREPASS_COLOR_INDEX]=color; #endif #ifdef PREPASS_POSITION fragData[PREPASS_POSITION_INDEX]=vec4f(fragmentInputs.vPositionW,writeGeometryInfo); #endif #ifdef PREPASS_LOCAL_POSITION fragData[PREPASS_LOCAL_POSITION_INDEX]=vec4f(fragmentInputs.vPosition,writeGeometryInfo); #endif #ifdef PREPASS_VELOCITY var a: vec2f=(fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[PREPASS_VELOCITY_INDEX]= vec4f(velocity,0.0,writeGeometryInfo); #elif defined(PREPASS_VELOCITY_LINEAR) var velocity : vec2f=vec2f(0.5)*((fragmentInputs.vPreviousPosition.xy/fragmentInputs.vPreviousPosition.w) - (fragmentInputs.vCurrentPosition.xy/fragmentInputs.vCurrentPosition.w));fragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,writeGeometryInfo); #endif #ifdef PREPASS_IRRADIANCE fragData[PREPASS_IRRADIANCE_INDEX]=vec4f(0.0,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_DEPTH fragData[PREPASS_DEPTH_INDEX]=vec4f(fragmentInputs.vViewPos.z,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_SCREENSPACE_DEPTH fragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_NORMALIZED_VIEW_DEPTH fragData[PREPASS_NORMALIZED_VIEW_DEPTH_INDEX]=vec4f(fragmentInputs.vNormViewDepth,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_NORMAL #ifdef PREPASS_NORMAL_WORLDSPACE fragData[PREPASS_NORMAL_INDEX]=vec4f(normalW,writeGeometryInfo); #else fragData[PREPASS_NORMAL_INDEX]=vec4f(normalize((scene.view*vec4f(normalW,0.0)).rgb),writeGeometryInfo); #endif #endif #ifdef PREPASS_WORLD_NORMAL fragData[PREPASS_WORLD_NORMAL_INDEX]=vec4f(normalW*0.5+0.5,writeGeometryInfo); #endif #ifdef PREPASS_ALBEDO fragData[PREPASS_ALBEDO_INDEX]=vec4f(baseColor.rgb,writeGeometryInfo); #endif #ifdef PREPASS_ALBEDO_SQRT fragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4f(sqrt(baseColor.rgb),writeGeometryInfo); #endif #ifdef PREPASS_REFLECTIVITY #if defined(SPECULAR) fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(toLinearSpaceVec4(specularMapColor))*writeGeometryInfo; #else fragData[PREPASS_REFLECTIVITY_INDEX]=vec4f(toLinearSpaceVec3(specularColor),1.0)*writeGeometryInfo; #endif #endif #if SCENE_MRT_COUNT>0 fragmentOutputs.fragData0=fragData[0]; #endif #if SCENE_MRT_COUNT>1 fragmentOutputs.fragData1=fragData[1]; #endif #if SCENE_MRT_COUNT>2 fragmentOutputs.fragData2=fragData[2]; #endif #if SCENE_MRT_COUNT>3 fragmentOutputs.fragData3=fragData[3]; #endif #if SCENE_MRT_COUNT>4 fragmentOutputs.fragData4=fragData[4]; #endif #if SCENE_MRT_COUNT>5 fragmentOutputs.fragData5=fragData[5]; #endif #if SCENE_MRT_COUNT>6 fragmentOutputs.fragData6=fragData[6]; #endif #if SCENE_MRT_COUNT>7 fragmentOutputs.fragData7=fragData[7]; #endif #endif #endif #if !defined(PREPASS) && !defined(ORDER_INDEPENDENT_TRANSPARENCY) fragmentOutputs.color=color; #endif #include #if ORDER_INDEPENDENT_TRANSPARENCY if (fragDepth==nearestDepth) {fragmentOutputs.frontColor=vec4f(fragmentOutputs.frontColor.rgb+color.rgb*color.a*alphaMultiplier,1.0-alphaMultiplier*(1.0-color.a));} else {fragmentOutputs.backColor+=color;} #endif #define CUSTOM_FRAGMENT_MAIN_END } `; if (!ShaderStore.ShadersStoreWGSL[name136]) { ShaderStore.ShadersStoreWGSL[name136] = shader136; } defaultPixelShaderWGSL = { name: name136, shader: shader136 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/decalVertexDeclaration.js var name137, shader137, decalVertexDeclaration; var init_decalVertexDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/decalVertexDeclaration.js"() { init_shaderStore(); name137 = "decalVertexDeclaration"; shader137 = `#ifdef DECAL uniform vec4 vDecalInfos;uniform mat4 decalMatrix; #endif `; if (!ShaderStore.IncludesShadersStore[name137]) { ShaderStore.IncludesShadersStore[name137] = shader137; } decalVertexDeclaration = { name: name137, shader: shader137 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultVertexDeclaration.js var name138, shader138, defaultVertexDeclaration; var init_defaultVertexDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultVertexDeclaration.js"() { init_shaderStore(); init_decalVertexDeclaration(); name138 = "defaultVertexDeclaration"; shader138 = `uniform mat4 viewProjection; #ifdef MULTIVIEW mat4 viewProjectionR; #endif uniform mat4 view; #ifdef DIFFUSE uniform mat4 diffuseMatrix;uniform vec2 vDiffuseInfos; #endif #ifdef AMBIENT uniform mat4 ambientMatrix;uniform vec2 vAmbientInfos; #endif #ifdef OPACITY uniform mat4 opacityMatrix;uniform vec2 vOpacityInfos; #endif #ifdef EMISSIVE uniform vec2 vEmissiveInfos;uniform mat4 emissiveMatrix; #endif #ifdef LIGHTMAP uniform vec2 vLightmapInfos;uniform mat4 lightmapMatrix; #endif #if defined(SPECULAR) && defined(SPECULARTERM) uniform vec2 vSpecularInfos;uniform mat4 specularMatrix; #endif #ifdef BUMP uniform vec3 vBumpInfos;uniform mat4 bumpMatrix; #endif #ifdef REFLECTION uniform mat4 reflectionMatrix; #endif #ifdef POINTSIZE uniform float pointSize; #endif #ifdef DETAIL uniform vec4 vDetailInfos;uniform mat4 detailMatrix; #endif uniform vec4 cameraInfo; #include #define ADDITIONAL_VERTEX_DECLARATION `; if (!ShaderStore.IncludesShadersStore[name138]) { ShaderStore.IncludesShadersStore[name138] = shader138; } defaultVertexDeclaration = { name: name138, shader: shader138 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultUboDeclaration.js var name139, shader139, defaultUboDeclaration; var init_defaultUboDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultUboDeclaration.js"() { init_shaderStore(); init_sceneUboDeclaration2(); init_meshUboDeclaration2(); name139 = "defaultUboDeclaration"; shader139 = `layout(std140,column_major) uniform;uniform Material {vec4 diffuseLeftColor;vec4 diffuseRightColor;vec4 opacityParts;vec4 reflectionLeftColor;vec4 reflectionRightColor;vec4 refractionLeftColor;vec4 refractionRightColor;vec4 emissiveLeftColor;vec4 emissiveRightColor;vec2 vDiffuseInfos;vec2 vAmbientInfos;vec2 vOpacityInfos;vec2 vEmissiveInfos;vec2 vLightmapInfos;vec2 vSpecularInfos;vec3 vBumpInfos;mat4 diffuseMatrix;mat4 ambientMatrix;mat4 opacityMatrix;mat4 emissiveMatrix;mat4 lightmapMatrix;mat4 specularMatrix;mat4 bumpMatrix;vec2 vTangentSpaceParams;float pointSize;float alphaCutOff;mat4 refractionMatrix;vec4 vRefractionInfos;vec3 vRefractionPosition;vec3 vRefractionSize;vec4 vSpecularColor;vec3 vEmissiveColor;vec4 vDiffuseColor;vec3 vAmbientColor;vec4 cameraInfo;vec2 vReflectionInfos;mat4 reflectionMatrix;vec3 vReflectionPosition;vec3 vReflectionSize; #define ADDITIONAL_UBO_DECLARATION }; #include #include `; if (!ShaderStore.IncludesShadersStore[name139]) { ShaderStore.IncludesShadersStore[name139] = shader139; } defaultUboDeclaration = { name: name139, shader: shader139 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/uvAttributeDeclaration.js var name140, shader140, uvAttributeDeclaration; var init_uvAttributeDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/uvAttributeDeclaration.js"() { init_shaderStore(); name140 = "uvAttributeDeclaration"; shader140 = `#ifdef UV{X} attribute vec2 uv{X}; #endif `; if (!ShaderStore.IncludesShadersStore[name140]) { ShaderStore.IncludesShadersStore[name140] = shader140; } uvAttributeDeclaration = { name: name140, shader: shader140 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassVertexDeclaration.js var name141, shader141, prePassVertexDeclaration; var init_prePassVertexDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassVertexDeclaration.js"() { init_shaderStore(); name141 = "prePassVertexDeclaration"; shader141 = `#ifdef PREPASS #ifdef PREPASS_LOCAL_POSITION varying vec3 vPosition; #endif #ifdef PREPASS_DEPTH varying vec3 vViewPos; #endif #ifdef PREPASS_NORMALIZED_VIEW_DEPTH varying float vNormViewDepth; #endif #if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; #endif #endif `; if (!ShaderStore.IncludesShadersStore[name141]) { ShaderStore.IncludesShadersStore[name141] = shader141; } prePassVertexDeclaration = { name: name141, shader: shader141 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/mainUVVaryingDeclaration.js var name142, shader142, mainUVVaryingDeclaration; var init_mainUVVaryingDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/mainUVVaryingDeclaration.js"() { init_shaderStore(); name142 = "mainUVVaryingDeclaration"; shader142 = `#ifdef MAINUV{X} varying vec2 vMainUV{X}; #endif `; if (!ShaderStore.IncludesShadersStore[name142]) { ShaderStore.IncludesShadersStore[name142] = shader142; } mainUVVaryingDeclaration = { name: name142, shader: shader142 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/samplerVertexDeclaration.js var name143, shader143, samplerVertexDeclaration; var init_samplerVertexDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/samplerVertexDeclaration.js"() { init_shaderStore(); name143 = "samplerVertexDeclaration"; shader143 = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 varying vec2 v_VARYINGNAME_UV; #endif `; if (!ShaderStore.IncludesShadersStore[name143]) { ShaderStore.IncludesShadersStore[name143] = shader143; } samplerVertexDeclaration = { name: name143, shader: shader143 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpVertexDeclaration.js var name144, shader144, bumpVertexDeclaration; var init_bumpVertexDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpVertexDeclaration.js"() { init_shaderStore(); name144 = "bumpVertexDeclaration"; shader144 = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) varying mat3 vTBN; #endif #endif `; if (!ShaderStore.IncludesShadersStore[name144]) { ShaderStore.IncludesShadersStore[name144] = shader144; } bumpVertexDeclaration = { name: name144, shader: shader144 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/fogVertexDeclaration.js var name145, shader145, fogVertexDeclaration; var init_fogVertexDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/fogVertexDeclaration.js"() { init_shaderStore(); name145 = "fogVertexDeclaration"; shader145 = `#ifdef FOG varying vec3 vFogDistance; #endif `; if (!ShaderStore.IncludesShadersStore[name145]) { ShaderStore.IncludesShadersStore[name145] = shader145; } fogVertexDeclaration = { name: name145, shader: shader145 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/lightVxFragmentDeclaration.js var name146, shader146, lightVxFragmentDeclaration; var init_lightVxFragmentDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/lightVxFragmentDeclaration.js"() { init_shaderStore(); name146 = "lightVxFragmentDeclaration"; shader146 = `#ifdef LIGHT{X} uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; #ifdef SPECULARTERM uniform vec4 vLightSpecular{X}; #else vec4 vLightSpecular{X}=vec4(0.); #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; #elif defined(SHADOWCUBE{X}) #else varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; #endif uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; #endif #ifdef SPOTLIGHT{X} uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; #elif defined(POINTLIGHT{X}) uniform vec4 vLightFalloff{X}; #elif defined(HEMILIGHT{X}) uniform vec3 vLightGround{X}; #endif #if defined(AREALIGHT{X}) uniform vec4 vLightWidth{X};uniform vec4 vLightHeight{X}; #endif #endif `; if (!ShaderStore.IncludesShadersStore[name146]) { ShaderStore.IncludesShadersStore[name146] = shader146; } lightVxFragmentDeclaration = { name: name146, shader: shader146 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/lightVxUboDeclaration.js var name147, shader147, lightVxUboDeclaration; var init_lightVxUboDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/lightVxUboDeclaration.js"() { init_shaderStore(); name147 = "lightVxUboDeclaration"; shader147 = `#ifdef LIGHT{X} uniform Light{X} {vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; #ifdef SPOTLIGHT{X} vec4 vLightDirection;vec4 vLightFalloff; #elif defined(POINTLIGHT{X}) vec4 vLightFalloff; #elif defined(HEMILIGHT{X}) vec3 vLightGround; #elif defined(CLUSTLIGHT{X}) vec2 vSliceData;vec2 vSliceRanges[CLUSTLIGHT_SLICES]; #endif #if defined(AREALIGHT{X}) vec4 vLightWidth;vec4 vLightHeight; #endif vec4 shadowsInfo;vec2 depthValues;} light{X}; #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; #elif defined(SHADOWCUBE{X}) #else varying vec4 vPositionFromLight{X};varying float vDepthMetric{X};uniform mat4 lightMatrix{X}; #endif #endif #endif `; if (!ShaderStore.IncludesShadersStore[name147]) { ShaderStore.IncludesShadersStore[name147] = shader147; } lightVxUboDeclaration = { name: name147, shader: shader147 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/logDepthDeclaration.js var name148, shader148, logDepthDeclaration; var init_logDepthDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/logDepthDeclaration.js"() { init_shaderStore(); name148 = "logDepthDeclaration"; shader148 = `#ifdef LOGARITHMICDEPTH uniform float logarithmicDepthConstant;varying float vFragmentDepth; #endif `; if (!ShaderStore.IncludesShadersStore[name148]) { ShaderStore.IncludesShadersStore[name148] = shader148; } logDepthDeclaration = { name: name148, shader: shader148 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassVertex.js var name149, shader149, prePassVertex; var init_prePassVertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassVertex.js"() { init_shaderStore(); name149 = "prePassVertex"; shader149 = `#ifdef PREPASS_DEPTH vViewPos=(view*worldPos).rgb; #endif #ifdef PREPASS_NORMALIZED_VIEW_DEPTH vNormViewDepth=((view*worldPos).z-cameraInfo.x)/(cameraInfo.y-cameraInfo.x); #endif #ifdef PREPASS_LOCAL_POSITION vPosition=positionUpdated.xyz; #endif #if (defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED) vCurrentPosition=viewProjection*worldPos; #if NUM_BONE_INFLUENCERS>0 mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; #endif vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); #else vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #endif `; if (!ShaderStore.IncludesShadersStore[name149]) { ShaderStore.IncludesShadersStore[name149] = shader149; } prePassVertex = { name: name149, shader: shader149 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/uvVariableDeclaration.js var name150, shader150, uvVariableDeclaration; var init_uvVariableDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/uvVariableDeclaration.js"() { init_shaderStore(); name150 = "uvVariableDeclaration"; shader150 = `#if !defined(UV{X}) && defined(MAINUV{X}) vec2 uv{X}=vec2(0.,0.); #endif #ifdef MAINUV{X} vMainUV{X}=uv{X}; #endif `; if (!ShaderStore.IncludesShadersStore[name150]) { ShaderStore.IncludesShadersStore[name150] = shader150; } uvVariableDeclaration = { name: name150, shader: shader150 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/samplerVertexImplementation.js var name151, shader151, samplerVertexImplementation; var init_samplerVertexImplementation2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/samplerVertexImplementation.js"() { init_shaderStore(); name151 = "samplerVertexImplementation"; shader151 = `#if defined(_DEFINENAME_) && _DEFINENAME_DIRECTUV==0 if (v_INFONAME_==0.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uvUpdated,1.0,0.0));} #ifdef UV2 else if (v_INFONAME_==1.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv2Updated,1.0,0.0));} #endif #ifdef UV3 else if (v_INFONAME_==2.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv3,1.0,0.0));} #endif #ifdef UV4 else if (v_INFONAME_==3.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv4,1.0,0.0));} #endif #ifdef UV5 else if (v_INFONAME_==4.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv5,1.0,0.0));} #endif #ifdef UV6 else if (v_INFONAME_==5.) {v_VARYINGNAME_UV=vec2(_MATRIXNAME_Matrix*vec4(uv6,1.0,0.0));} #endif #endif `; if (!ShaderStore.IncludesShadersStore[name151]) { ShaderStore.IncludesShadersStore[name151] = shader151; } samplerVertexImplementation = { name: name151, shader: shader151 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpVertex.js var name152, shader152, bumpVertex; var init_bumpVertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpVertex.js"() { init_shaderStore(); name152 = "bumpVertex"; shader152 = `#if defined(BUMP) || defined(PARALLAX) || defined(CLEARCOAT_BUMP) || defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) vec3 tbnNormal=normalize(normalUpdated);vec3 tbnTangent=normalize(tangentUpdated.xyz);vec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;vTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal); #endif #endif `; if (!ShaderStore.IncludesShadersStore[name152]) { ShaderStore.IncludesShadersStore[name152] = shader152; } bumpVertex = { name: name152, shader: shader152 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/fogVertex.js var name153, shader153, fogVertex; var init_fogVertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/fogVertex.js"() { init_shaderStore(); name153 = "fogVertex"; shader153 = `#ifdef FOG vFogDistance=(view*worldPos).xyz; #endif `; if (!ShaderStore.IncludesShadersStore[name153]) { ShaderStore.IncludesShadersStore[name153] = shader153; } fogVertex = { name: name153, shader: shader153 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowsVertex.js var name154, shader154, shadowsVertex; var init_shadowsVertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowsVertex.js"() { init_shaderStore(); name154 = "shadowsVertex"; shader154 = `#ifdef SHADOWS #if defined(SHADOWCSM{X}) vPositionFromCamera{X}=view*worldPos;for (int i=0; i defaultVertexShader }); var name157, shader157, defaultVertexShader; var init_default_vertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/default.vertex.js"() { init_shaderStore(); init_defaultVertexDeclaration(); init_defaultUboDeclaration2(); init_uvAttributeDeclaration2(); init_helperFunctions2(); init_bonesDeclaration2(); init_bakedVertexAnimationDeclaration2(); init_instancesDeclaration2(); init_prePassVertexDeclaration2(); init_mainUVVaryingDeclaration2(); init_samplerVertexDeclaration2(); init_bumpVertexDeclaration2(); init_clipPlaneVertexDeclaration2(); init_fogVertexDeclaration2(); init_lightVxFragmentDeclaration2(); init_lightVxUboDeclaration2(); init_morphTargetsVertexGlobalDeclaration2(); init_morphTargetsVertexDeclaration2(); init_logDepthDeclaration2(); init_morphTargetsVertexGlobal2(); init_morphTargetsVertex2(); init_instancesVertex2(); init_bonesVertex2(); init_bakedVertexAnimation2(); init_prePassVertex2(); init_uvVariableDeclaration2(); init_samplerVertexImplementation2(); init_bumpVertex2(); init_clipPlaneVertex2(); init_fogVertex2(); init_shadowsVertex2(); init_vertexColorMixing2(); init_pointCloudVertex(); init_logDepthVertex2(); name157 = "defaultVertexShader"; shader157 = `#define CUSTOM_VERTEX_EXTENSION #include<__decl__defaultVertex> #define CUSTOM_VERTEX_BEGIN attribute vec3 position; #ifdef NORMAL attribute vec3 normal; #endif #ifdef TANGENT attribute vec4 tangent; #endif #ifdef UV1 attribute vec2 uv; #endif #include[2..7] #ifdef VERTEXCOLOR attribute vec4 color; #endif #include #include #include #include #include #include[1..7] #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap) #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular) #endif #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal) varying vec3 vPositionW; #ifdef NORMAL varying vec3 vNormalW; #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vec4 vColor; #endif #include #include #include #include<__decl__lightVxFragment>[0..maxSimultaneousLights] #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0 varying float vViewDepth; #endif #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec3 positionUpdated=position; #ifdef NORMAL vec3 normalUpdated=normal; #endif #ifdef TANGENT vec4 tangentUpdated=tangent; #endif #ifdef UV1 vec2 uvUpdated=uv; #endif #ifdef UV2 vec2 uv2Updated=uv2; #endif #ifdef VERTEXCOLOR vec4 colorUpdated=color; #endif #include #include[0..maxSimultaneousMorphTargets] #ifdef REFLECTIONMAP_SKYBOX vPositionUVW=positionUpdated; #endif #define CUSTOM_VERTEX_UPDATE_POSITION #define CUSTOM_VERTEX_UPDATE_NORMAL #include #if defined(PREPASS) && ((defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED) vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); #ifdef NORMAL mat3 normalWorld=mat3(finalWorld); #if defined(INSTANCES) && defined(THIN_INSTANCES) vNormalW=normalUpdated/vec3(dot(normalWorld[0],normalWorld[0]),dot(normalWorld[1],normalWorld[1]),dot(normalWorld[2],normalWorld[2]));vNormalW=normalize(normalWorld*vNormalW); #else #ifdef NONUNIFORMSCALING normalWorld=transposeMat3(inverseMat3(normalWorld)); #endif vNormalW=normalize(normalWorld*normalUpdated); #endif #endif #define CUSTOM_VERTEX_UPDATE_WORLDPOS #ifdef MULTIVIEW if (gl_ViewID_OVR==0u) {gl_Position=viewProjection*worldPos;} else {gl_Position=viewProjectionR*worldPos;} #else gl_Position=viewProjection*worldPos; #endif vPositionW=vec3(worldPos); #ifdef PREPASS #include #endif #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) vDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0))); #endif #if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0 vViewDepth=(view*worldPos).z; #endif #ifndef UV1 vec2 uvUpdated=vec2(0.,0.); #endif #ifndef UV2 vec2 uv2Updated=vec2(0.,0.); #endif #ifdef MAINUV1 vMainUV1=uvUpdated; #endif #ifdef MAINUV2 vMainUV2=uv2Updated; #endif #include[3..7] #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_MATRIXNAME_,diffuse,_INFONAME_,DiffuseInfos.x) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_MATRIXNAME_,detail,_INFONAME_,DetailInfos.x) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_MATRIXNAME_,ambient,_INFONAME_,AmbientInfos.x) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_MATRIXNAME_,opacity,_INFONAME_,OpacityInfos.x) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_MATRIXNAME_,emissive,_INFONAME_,EmissiveInfos.x) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_MATRIXNAME_,lightmap,_INFONAME_,LightmapInfos.x) #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_MATRIXNAME_,specular,_INFONAME_,SpecularInfos.x) #endif #include(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_MATRIXNAME_,bump,_INFONAME_,BumpInfos.x) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_MATRIXNAME_,decal,_INFONAME_,DecalInfos.x) #include #include #include #include[0..maxSimultaneousLights] #include #include #include #define CUSTOM_VERTEX_MAIN_END } `; if (!ShaderStore.ShadersStore[name157]) { ShaderStore.ShadersStore[name157] = shader157; } defaultVertexShader = { name: name157, shader: shader157 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/decalFragmentDeclaration.js var name158, shader158, decalFragmentDeclaration; var init_decalFragmentDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/decalFragmentDeclaration.js"() { init_shaderStore(); name158 = "decalFragmentDeclaration"; shader158 = `#ifdef DECAL uniform vec4 vDecalInfos; #endif `; if (!ShaderStore.IncludesShadersStore[name158]) { ShaderStore.IncludesShadersStore[name158] = shader158; } decalFragmentDeclaration = { name: name158, shader: shader158 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultFragmentDeclaration.js var name159, shader159, defaultFragmentDeclaration; var init_defaultFragmentDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/defaultFragmentDeclaration.js"() { init_shaderStore(); init_decalFragmentDeclaration(); name159 = "defaultFragmentDeclaration"; shader159 = `uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;uniform vec4 vSpecularColor;uniform vec3 vEmissiveColor;uniform vec3 vAmbientColor;uniform float visibility; #ifdef DIFFUSE uniform vec2 vDiffuseInfos; #endif #ifdef AMBIENT uniform vec2 vAmbientInfos; #endif #ifdef OPACITY uniform vec2 vOpacityInfos; #endif #ifdef EMISSIVE uniform vec2 vEmissiveInfos; #endif #ifdef LIGHTMAP uniform vec2 vLightmapInfos; #endif #ifdef BUMP uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; #endif #ifdef ALPHATEST uniform float alphaCutOff; #endif #if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION) || defined(PREPASS) uniform mat4 view; #endif #ifdef REFRACTION uniform vec4 vRefractionInfos; #ifndef REFRACTIONMAP_3D uniform mat4 refractionMatrix; #endif #ifdef REFRACTIONFRESNEL uniform vec4 refractionLeftColor;uniform vec4 refractionRightColor; #endif #if defined(USE_LOCAL_REFRACTIONMAP_CUBIC) && defined(REFRACTIONMAP_3D) uniform vec3 vRefractionPosition;uniform vec3 vRefractionSize; #endif #endif #if defined(SPECULAR) && defined(SPECULARTERM) uniform vec2 vSpecularInfos; #endif #ifdef DIFFUSEFRESNEL uniform vec4 diffuseLeftColor;uniform vec4 diffuseRightColor; #endif #ifdef OPACITYFRESNEL uniform vec4 opacityParts; #endif #ifdef EMISSIVEFRESNEL uniform vec4 emissiveLeftColor;uniform vec4 emissiveRightColor; #endif #if defined(REFLECTION) || (defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED)) uniform vec2 vReflectionInfos; #if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION) || defined(REFLECTIONMAP_EQUIRECTANGULAR) || defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_SKYBOX) uniform mat4 reflectionMatrix; #endif #ifndef REFLECTIONMAP_SKYBOX #if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC) uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; #endif #endif #ifdef REFLECTIONFRESNEL uniform vec4 reflectionLeftColor;uniform vec4 reflectionRightColor; #endif #endif #ifdef DETAIL uniform vec4 vDetailInfos; #endif #include #define ADDITIONAL_FRAGMENT_DECLARATION `; if (!ShaderStore.IncludesShadersStore[name159]) { ShaderStore.IncludesShadersStore[name159] = shader159; } defaultFragmentDeclaration = { name: name159, shader: shader159 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassDeclaration.js var name160, shader160, prePassDeclaration; var init_prePassDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/prePassDeclaration.js"() { init_shaderStore(); name160 = "prePassDeclaration"; shader160 = `#ifdef PREPASS #extension GL_EXT_draw_buffers : require layout(location=0) out highp vec4 glFragData[{X}];highp vec4 gl_FragColor; #ifdef PREPASS_LOCAL_POSITION varying highp vec3 vPosition; #endif #ifdef PREPASS_DEPTH varying highp vec3 vViewPos; #endif #ifdef PREPASS_NORMALIZED_VIEW_DEPTH varying highp float vNormViewDepth; #endif #if defined(PREPASS_VELOCITY) || defined(PREPASS_VELOCITY_LINEAR) varying highp vec4 vCurrentPosition;varying highp vec4 vPreviousPosition; #endif #endif `; if (!ShaderStore.IncludesShadersStore[name160]) { ShaderStore.IncludesShadersStore[name160] = shader160; } prePassDeclaration = { name: name160, shader: shader160 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/oitDeclaration.js var name161, shader161, oitDeclaration; var init_oitDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/oitDeclaration.js"() { init_shaderStore(); name161 = "oitDeclaration"; shader161 = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY #extension GL_EXT_draw_buffers : require layout(location=0) out vec2 depth; layout(location=1) out vec4 frontColor;layout(location=2) out vec4 backColor; #define MAX_DEPTH 99999.0 highp vec4 gl_FragColor;uniform sampler2D oitDepthSampler;uniform sampler2D oitFrontColorSampler; #endif `; if (!ShaderStore.IncludesShadersStore[name161]) { ShaderStore.IncludesShadersStore[name161] = shader161; } oitDeclaration = { name: name161, shader: shader161 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/lightFragmentDeclaration.js var name162, shader162, lightFragmentDeclaration; var init_lightFragmentDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/lightFragmentDeclaration.js"() { init_shaderStore(); name162 = "lightFragmentDeclaration"; shader162 = `#ifdef LIGHT{X} uniform vec4 vLightData{X};uniform vec4 vLightDiffuse{X}; #ifdef SPECULARTERM uniform vec4 vLightSpecular{X}; #else vec4 vLightSpecular{X}=vec4(0.); #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; #if defined(SHADOWPCSS{X}) uniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; #elif defined(SHADOWPCF{X}) uniform highp sampler2DArrayShadow shadowTexture{X}; #else uniform highp sampler2DArray shadowTexture{X}; #endif #ifdef SHADOWCSMDEBUG{X} const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] ( vec3 ( 1.5,0.0,0.0 ), vec3 ( 0.0,1.5,0.0 ), vec3 ( 0.0,0.0,5.5 ), vec3 ( 1.5,0.0,5.5 ), vec3 ( 1.5,1.5,0.0 ), vec3 ( 1.0,1.0,1.0 ), vec3 ( 0.0,1.0,5.5 ), vec3 ( 0.5,3.5,0.75 ) );vec3 shadowDebug{X}; #endif #ifdef SHADOWCSMUSESHADOWMAXZ{X} int index{X}=-1; #else int index{X}=SHADOWCSMNUM_CASCADES{X}-1; #endif float diff{X}=0.; #elif defined(SHADOWCUBE{X}) uniform samplerCube shadowTexture{X}; #else varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; #if defined(SHADOWPCSS{X}) uniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X}; #elif defined(SHADOWPCF{X}) uniform highp sampler2DShadow shadowTexture{X}; #else uniform sampler2D shadowTexture{X}; #endif uniform mat4 lightMatrix{X}; #endif uniform vec4 shadowsInfo{X};uniform vec2 depthValues{X}; #endif #ifdef SPOTLIGHT{X} uniform vec4 vLightDirection{X};uniform vec4 vLightFalloff{X}; #elif defined(POINTLIGHT{X}) uniform vec4 vLightFalloff{X}; #elif defined(HEMILIGHT{X}) uniform vec3 vLightGround{X}; #endif #ifdef AREALIGHT{X} uniform vec4 vLightWidth{X};uniform vec4 vLightHeight{X}; #endif #ifdef IESLIGHTTEXTURE{X} uniform sampler2D iesLightTexture{X}; #endif #ifdef PROJECTEDLIGHTTEXTURE{X} uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X}; #endif #ifdef CLUSTLIGHT{X} uniform vec2 vSliceData{X};uniform vec2 vSliceRanges{X}[CLUSTLIGHT_SLICES];uniform sampler2D lightDataTexture{X};uniform highp sampler2D tileMaskTexture{X}; #endif #endif `; if (!ShaderStore.IncludesShadersStore[name162]) { ShaderStore.IncludesShadersStore[name162] = shader162; } lightFragmentDeclaration = { name: name162, shader: shader162 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/lightUboDeclaration.js var name163, shader163, lightUboDeclaration; var init_lightUboDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/lightUboDeclaration.js"() { init_shaderStore(); name163 = "lightUboDeclaration"; shader163 = `#ifdef LIGHT{X} uniform Light{X} {vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular; #ifdef SPOTLIGHT{X} vec4 vLightDirection;vec4 vLightFalloff; #elif defined(POINTLIGHT{X}) vec4 vLightFalloff; #elif defined(HEMILIGHT{X}) vec3 vLightGround; #elif defined(CLUSTLIGHT{X}) vec2 vSliceData;vec2 vSliceRanges[CLUSTLIGHT_SLICES]; #endif #if defined(AREALIGHT{X}) vec4 vLightWidth;vec4 vLightHeight; #endif vec4 shadowsInfo;vec2 depthValues;} light{X}; #ifdef IESLIGHTTEXTURE{X} uniform sampler2D iesLightTexture{X}; #endif #ifdef PROJECTEDLIGHTTEXTURE{X} uniform mat4 textureProjectionMatrix{X};uniform sampler2D projectionLightTexture{X}; #endif #ifdef CLUSTLIGHT{X} uniform sampler2D lightDataTexture{X};uniform highp sampler2D tileMaskTexture{X}; #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} uniform mat4 lightMatrix{X}[SHADOWCSMNUM_CASCADES{X}];uniform float viewFrustumZ{X}[SHADOWCSMNUM_CASCADES{X}];uniform float frustumLengths{X}[SHADOWCSMNUM_CASCADES{X}];uniform float cascadeBlendFactor{X};varying vec4 vPositionFromLight{X}[SHADOWCSMNUM_CASCADES{X}];varying float vDepthMetric{X}[SHADOWCSMNUM_CASCADES{X}];varying vec4 vPositionFromCamera{X}; #if defined(SHADOWPCSS{X}) uniform highp sampler2DArrayShadow shadowTexture{X};uniform highp sampler2DArray depthTexture{X};uniform vec2 lightSizeUVCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float depthCorrection{X}[SHADOWCSMNUM_CASCADES{X}];uniform float penumbraDarkness{X}; #elif defined(SHADOWPCF{X}) uniform highp sampler2DArrayShadow shadowTexture{X}; #else uniform highp sampler2DArray shadowTexture{X}; #endif #ifdef SHADOWCSMDEBUG{X} const vec3 vCascadeColorsMultiplier{X}[8]=vec3[8] ( vec3 ( 1.5,0.0,0.0 ), vec3 ( 0.0,1.5,0.0 ), vec3 ( 0.0,0.0,5.5 ), vec3 ( 1.5,0.0,5.5 ), vec3 ( 1.5,1.5,0.0 ), vec3 ( 1.0,1.0,1.0 ), vec3 ( 0.0,1.0,5.5 ), vec3 ( 0.5,3.5,0.75 ) );vec3 shadowDebug{X}; #endif #ifdef SHADOWCSMUSESHADOWMAXZ{X} int index{X}=-1; #else int index{X}=SHADOWCSMNUM_CASCADES{X}-1; #endif float diff{X}=0.; #elif defined(SHADOWCUBE{X}) uniform samplerCube shadowTexture{X}; #else varying vec4 vPositionFromLight{X};varying float vDepthMetric{X}; #if defined(SHADOWPCSS{X}) uniform highp sampler2DShadow shadowTexture{X};uniform highp sampler2D depthTexture{X}; #elif defined(SHADOWPCF{X}) uniform highp sampler2DShadow shadowTexture{X}; #else uniform sampler2D shadowTexture{X}; #endif uniform mat4 lightMatrix{X}; #endif #endif #endif `; if (!ShaderStore.IncludesShadersStore[name163]) { ShaderStore.IncludesShadersStore[name163] = shader163; } lightUboDeclaration = { name: name163, shader: shader163 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/ltcHelperFunctions.js var name164, shader164, ltcHelperFunctions; var init_ltcHelperFunctions2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/ltcHelperFunctions.js"() { init_shaderStore(); name164 = "ltcHelperFunctions"; shader164 = `vec2 LTCUv( const in vec3 N,const in vec3 V,const in float roughness ) {const float LUTSIZE=64.0;const float LUTSCALE=( LUTSIZE-1.0 )/LUTSIZE;const float LUTBIAS=0.5/LUTSIZE;float dotNV=saturate( dot( N,V ) );vec2 uv=vec2( roughness,sqrt( 1.0-dotNV ) );uv=uv*LUTSCALE+LUTBIAS;return uv;} float LTCClippedSphereFormFactor( const in vec3 f ) {float l=length( f );return max( ( l*l+f.z )/( l+1.0 ),0.0 );} vec3 LTCEdgeVectorFormFactor( const in vec3 v1,const in vec3 v2 ) {float x=dot( v1,v2 );float y=abs( x );float a=0.8543985+( 0.4965155+0.0145206*y )*y;float b=3.4175940+( 4.1616724+y )*y;float v=a/b;float thetaSintheta=0.0;if( x>0.0 ) {thetaSintheta=v;} else {thetaSintheta=0.5*inversesqrt( max( 1.0-x*x,1e-7 ) )-v;} return cross( v1,v2 )*thetaSintheta;} vec3 LTCEvaluate( const in vec3 N,const in vec3 V,const in vec3 P,const in mat3 mInv,const in vec3 rectCoords[ 4 ] ) {vec3 v1=rectCoords[ 1 ]-rectCoords[ 0 ];vec3 v2=rectCoords[ 3 ]-rectCoords[ 0 ];vec3 lightNormal=cross( v1,v2 );if( dot( lightNormal,P-rectCoords[ 0 ] )<0.0 ) return vec3( 0.0 );vec3 T1,T2;T1=normalize( V-N*dot( V,N ) );T2=- cross( N,T1 ); mat3 mat=mInv*transposeMat3( mat3( T1,T2,N ) );vec3 coords[ 4 ];coords[ 0 ]=mat*( rectCoords[ 0 ]-P );coords[ 1 ]=mat*( rectCoords[ 1 ]-P );coords[ 2 ]=mat*( rectCoords[ 2 ]-P );coords[ 3 ]=mat*( rectCoords[ 3 ]-P );coords[ 0 ]=normalize( coords[ 0 ] );coords[ 1 ]=normalize( coords[ 1 ] );coords[ 2 ]=normalize( coords[ 2 ] );coords[ 3 ]=normalize( coords[ 3 ] );vec3 vectorFormFactor=vec3( 0.0 );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 0 ],coords[ 1 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 1 ],coords[ 2 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 2 ],coords[ 3 ] );vectorFormFactor+=LTCEdgeVectorFormFactor( coords[ 3 ],coords[ 0 ] );float result=LTCClippedSphereFormFactor( vectorFormFactor );return vec3( result );} struct areaLightData {vec3 Diffuse;vec3 Specular;vec4 Fresnel;}; #define inline areaLightData computeAreaLightSpecularDiffuseFresnel(const in sampler2D ltc1,const in sampler2D ltc2,const in vec3 viewDir,const in vec3 normal,const in vec3 position,const in vec3 lightPos,const in vec3 halfWidth,const in vec3 halfHeight,const in float roughness) {areaLightData result;vec3 rectCoords[ 4 ];rectCoords[ 0 ]=lightPos+halfWidth-halfHeight; rectCoords[ 1 ]=lightPos-halfWidth-halfHeight;rectCoords[ 2 ]=lightPos-halfWidth+halfHeight;rectCoords[ 3 ]=lightPos+halfWidth+halfHeight; #ifdef SPECULARTERM vec2 uv=LTCUv( normal,viewDir,roughness );vec4 t1=texture2D( ltc1,uv );vec4 t2=texture2D( ltc2,uv );mat3 mInv=mat3( vec3( t1.x,0,t1.y ), vec3( 0,1, 0 ), vec3( t1.z,0,t1.w ) );result.Specular=LTCEvaluate( normal,viewDir,position,mInv,rectCoords );result.Fresnel=t2; #endif result.Diffuse=LTCEvaluate( normal,viewDir,position,mat3( 1.0 ),rectCoords );return result;}`; if (!ShaderStore.IncludesShadersStore[name164]) { ShaderStore.IncludesShadersStore[name164] = shader164; } ltcHelperFunctions = { name: name164, shader: shader164 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clusteredLightingFunctions.js var name165, shader165, clusteredLightingFunctions; var init_clusteredLightingFunctions2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clusteredLightingFunctions.js"() { init_shaderStore(); name165 = "clusteredLightingFunctions"; shader165 = `struct ClusteredLight {vec4 vLightData;vec4 vLightDiffuse;vec4 vLightSpecular;vec4 vLightDirection;vec4 vLightFalloff;}; #define inline ClusteredLight getClusteredLight(sampler2D lightDataTexture,int index) {return ClusteredLight( texelFetch(lightDataTexture,ivec2(0,index),0), texelFetch(lightDataTexture,ivec2(1,index),0), texelFetch(lightDataTexture,ivec2(2,index),0), texelFetch(lightDataTexture,ivec2(3,index),0), texelFetch(lightDataTexture,ivec2(4,index),0) );} int getClusteredSliceIndex(vec2 sliceData,float viewDepth) {return int(log(viewDepth)*sliceData.x+sliceData.y);} `; if (!ShaderStore.IncludesShadersStore[name165]) { ShaderStore.IncludesShadersStore[name165] = shader165; } clusteredLightingFunctions = { name: name165, shader: shader165 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/lightsFragmentFunctions.js var name166, shader166, lightsFragmentFunctions; var init_lightsFragmentFunctions2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/lightsFragmentFunctions.js"() { init_shaderStore(); init_ltcHelperFunctions2(); init_clusteredLightingFunctions2(); name166 = "lightsFragmentFunctions"; shader166 = `struct lightingInfo {vec3 diffuse; #ifdef SPECULARTERM vec3 specular; #endif #ifdef NDOTL float ndl; #endif };lightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {lightingInfo result;vec3 lightVectorW;float attenuation=1.0;if (lightData.w==0.) {vec3 direction=lightData.xyz-vPositionW;attenuation=max(0.,1.0-length(direction)/range);lightVectorW=normalize(direction);} else {lightVectorW=normalize(-lightData.xyz);} float ndl=max(0.,dot(vNormal,lightVectorW)); #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=ndl*diffuseColor*attenuation; #ifdef SPECULARTERM vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; #endif return result;} float getAttenuation(float cosAngle,float exponent) {return max(0.,pow(cosAngle,exponent));} float getIESAttenuation(float cosAngle,sampler2D iesLightSampler) {float angle=acos(cosAngle)/PI;return texture2D(iesLightSampler,vec2(angle,0.)).r;} lightingInfo basicSpotLighting(vec3 viewDirectionW,vec3 lightVectorW,vec3 vNormal,float attenuation,vec3 diffuseColor,vec3 specularColor,float glossiness) {lightingInfo result; float ndl=max(0.,dot(vNormal,lightVectorW)); #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=ndl*diffuseColor*attenuation; #ifdef SPECULARTERM vec3 angleW=normalize(viewDirectionW+lightVectorW);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor*attenuation; #endif return result;} lightingInfo computeIESSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness,sampler2D iesLightSampler) { vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float dotProduct=dot(lightDirection.xyz,-lightVectorW);float cosAngle=max(0.,dotProduct);if (cosAngle>=lightDirection.w) { attenuation*=getIESAttenuation(dotProduct,iesLightSampler);return basicSpotLighting(viewDirectionW,lightVectorW,vNormal,attenuation,diffuseColor,specularColor,glossiness);} lightingInfo result;result.diffuse=vec3(0.); #ifdef SPECULARTERM result.specular=vec3(0.); #endif #ifdef NDOTL result.ndl=0.; #endif return result;} lightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {vec3 direction=lightData.xyz-vPositionW;vec3 lightVectorW=normalize(direction);float attenuation=max(0.,1.0-length(direction)/range);float cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));if (cosAngle>=lightDirection.w) { attenuation*=getAttenuation(cosAngle,lightData.w);return basicSpotLighting(viewDirectionW,lightVectorW,vNormal,attenuation,diffuseColor,specularColor,glossiness);} lightingInfo result;result.diffuse=vec3(0.); #ifdef SPECULARTERM result.specular=vec3(0.); #endif #ifdef NDOTL result.ndl=0.; #endif return result;} lightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {lightingInfo result;float ndl=dot(vNormal,lightData.xyz)*0.5+0.5; #ifdef NDOTL result.ndl=ndl; #endif result.diffuse=mix(groundColor,diffuseColor,ndl); #ifdef SPECULARTERM vec3 angleW=normalize(viewDirectionW+lightData.xyz);float specComp=max(0.,dot(vNormal,angleW));specComp=pow(specComp,max(1.,glossiness));result.specular=specComp*specularColor; #endif return result;} #define inline vec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix,vec3 posW){vec4 strq=textureProjectionMatrix*vec4(posW,1.0);strq/=strq.w;vec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;return textureColor;} #if defined(AREALIGHTUSED) && defined(AREALIGHTSUPPORTED) #include uniform sampler2D areaLightsLTC1Sampler;uniform sampler2D areaLightsLTC2Sampler; #define inline lightingInfo computeAreaLighting(sampler2D ltc1,sampler2D ltc2,vec3 viewDirectionW,vec3 vNormal,vec3 vPosition,vec3 lightPosition,vec3 halfWidth,vec3 halfHeight,vec3 diffuseColor,vec3 specularColor,float roughness) {lightingInfo result;areaLightData data=computeAreaLightSpecularDiffuseFresnel(ltc1,ltc2,viewDirectionW,vNormal,vPosition,lightPosition,halfWidth,halfHeight,roughness); #ifdef SPECULARTERM vec3 fresnel=( specularColor*data.Fresnel.x+( vec3( 1.0 )-specularColor )*data.Fresnel.y );result.specular+=specularColor*fresnel*data.Specular; #endif result.diffuse+=diffuseColor*data.Diffuse;return result;} #endif #if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0 #include #define inline lightingInfo computeClusteredLighting( sampler2D lightDataTexture, sampler2D tileMaskTexture, vec3 viewDirectionW, vec3 vNormal, vec4 lightData, ivec2 sliceRange, float glossiness ) {lightingInfo result;ivec2 tilePosition=ivec2(gl_FragCoord.xy*lightData.xy);int maskHeight=int(lightData.z);tilePosition.y=min(tilePosition.y,maskHeight-1);ivec2 batchRange=sliceRange/CLUSTLIGHT_BATCH;int batchOffset=batchRange.x*CLUSTLIGHT_BATCH;tilePosition.y+=maskHeight*batchRange.x;for (int i=batchRange.x; i<=batchRange.y; i+=1) {uint mask=uint(texelFetch(tileMaskTexture,tilePosition,0).r);tilePosition.y+=maskHeight;int maskOffset=max(sliceRange.x-batchOffset,0);int maskWidth=min(sliceRange.y-batchOffset+1,CLUSTLIGHT_BATCH);mask=extractBits(mask,maskOffset,maskWidth);while (mask != 0u) {uint bit=mask & -mask;mask ^= bit;int position=onlyBitPosition(bit);ClusteredLight light=getClusteredLight(lightDataTexture,batchOffset+maskOffset+position);lightingInfo info;if (light.vLightDirection.w<0.0) {info=computeLighting(viewDirectionW,vNormal,light.vLightData,light.vLightDiffuse.rgb,light.vLightSpecular.rgb,light.vLightDiffuse.a,glossiness);} else {info=computeSpotLighting(viewDirectionW,vNormal,light.vLightData,light.vLightDirection,light.vLightDiffuse.rgb,light.vLightSpecular.rgb,light.vLightDiffuse.a,glossiness);} result.diffuse+=info.diffuse; #ifdef SPECULARTERM result.specular+=info.specular; #endif } batchOffset+=CLUSTLIGHT_BATCH;} return result;} #endif `; if (!ShaderStore.IncludesShadersStore[name166]) { ShaderStore.IncludesShadersStore[name166] = shader166; } lightsFragmentFunctions = { name: name166, shader: shader166 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowsFragmentFunctions.js var name167, shader167, shadowsFragmentFunctions; var init_shadowsFragmentFunctions2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/shadowsFragmentFunctions.js"() { init_shaderStore(); name167 = "shadowsFragmentFunctions"; shader167 = `#ifdef SHADOWS #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) #else #define TEXTUREFUNC(s,c,b) texture2D(s,c,b) #endif #ifndef SHADOWFLOAT float unpack(vec4 color) {const vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);return dot(color,bit_shift);} #endif float computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff) {float mask=smoothstep(1.0-frustumEdgeFalloff,1.00000012,clamp(dot(clipSpace,clipSpace),0.,1.));return mix(value,1.0,mask);} #define inline float computeShadowCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues) {vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y; #ifndef SHADOWFLOAT float shadow=unpack(textureCube(shadowSampler,directionToLight)); #else float shadow=textureCube(shadowSampler,directionToLight).x; #endif return depth>shadow ? darkness : 1.0;} #define inline float computeShadowWithPoissonSamplingCube(vec3 worldPos,vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues) {vec3 directionToLight=worldPos-lightPosition;float depth=length(directionToLight);depth=(depth+depthValues.x)/(depthValues.y);depth=clamp(depth,0.,1.0);directionToLight=normalize(directionToLight);directionToLight.y=-directionToLight.y;float visibility=1.;vec3 poissonDisk[4];poissonDisk[0]=vec3(-1.0,1.0,-1.0);poissonDisk[1]=vec3(1.0,-1.0,-1.0);poissonDisk[2]=vec3(-1.0,-1.0,-1.0);poissonDisk[3]=vec3(1.0,-1.0,1.0); #ifndef SHADOWFLOAT if (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;} #endif #define inline float computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {float shadowPixelDepth=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT float shadow=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); #else float shadow=TEXTUREFUNC(shadowSampler,uv,0.).x; #endif return shadowPixelDepth>shadow ? computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff) : 1.;}} #define inline float computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {float shadowPixelDepth=clamp(depthMetric,0.,1.0);float visibility=1.;vec2 poissonDisk[4];poissonDisk[0]=vec2(-0.94201624,-0.39906216);poissonDisk[1]=vec2(0.94558609,-0.76890725);poissonDisk[2]=vec2(-0.094184101,-0.92938870);poissonDisk[3]=vec2(0.34495938,0.29387760); #ifndef SHADOWFLOAT if (unpack(TEXTUREFUNC(shadowSampler,uv+poissonDisk[0]*mapSize,0.))1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {float shadowPixelDepth=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); #else float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; #endif float esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} #define inline float computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec2 uv=0.5*clipSpace.xy+vec2(0.5);if (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0) {return 1.0;} else {float shadowPixelDepth=clamp(depthMetric,0.,1.0); #ifndef SHADOWFLOAT float shadowMapSample=unpack(TEXTUREFUNC(shadowSampler,uv,0.)); #else float shadowMapSample=TEXTUREFUNC(shadowSampler,uv,0.).x; #endif float esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);return computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);}} #ifdef IS_NDC_HALF_ZRANGE #define ZINCLIP clipSpace.z #else #define ZINCLIP uvDepth.z #endif #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define SMALLEST_ABOVE_ZERO 1.1754943508e-38 #define GREATEST_LESS_THAN_ONE 0.99999994 #define DISABLE_UNIFORMITY_ANALYSIS #define inline float computeShadowWithCSMPCF1(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5)); #ifdef USE_REVERSE_DEPTHBUFFER uvDepth.z=clamp(ZINCLIP,SMALLEST_ABOVE_ZERO,1.); #else uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE); #endif vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float shadow=texture2D(shadowSampler,uvDepthLayer);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} #define inline float computeShadowWithCSMPCF3(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5)); #ifdef USE_REVERSE_DEPTHBUFFER uvDepth.z=clamp(ZINCLIP,SMALLEST_ABOVE_ZERO,1.); #else uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE); #endif vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; vec2 st=fract(uv); vec2 base_uv=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} #define inline float computeShadowWithCSMPCF5(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArrayShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5)); #ifdef USE_REVERSE_DEPTHBUFFER uvDepth.z=clamp(ZINCLIP,SMALLEST_ABOVE_ZERO,1.); #else uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE); #endif vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; vec2 st=fract(uv); vec2 base_uv=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[0]),layer,uvDepth.z));shadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[0]),layer,uvDepth.z));shadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[0]),layer,uvDepth.z));shadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[1]),layer,uvDepth.z));shadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[1]),layer,uvDepth.z));shadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[1]),layer,uvDepth.z));shadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[0],v[2]),layer,uvDepth.z));shadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[1],v[2]),layer,uvDepth.z));shadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec4(base_uv.xy+vec2(u[2],v[2]),layer,uvDepth.z));shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);} #define inline float computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff) {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float shadow=TEXTUREFUNC(shadowSampler,uvDepth,0.);shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} #define inline float computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; vec2 st=fract(uv); vec2 base_uv=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; vec2 uvw0=3.-2.*st;vec2 uvw1=1.+2.*st;vec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;vec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow=shadow/16.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} #define inline float computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,highp sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff) {if (depthMetric>1.0 || depthMetric<0.0) {return 1.0;} else {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;vec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; uv+=0.5; vec2 st=fract(uv); vec2 base_uv=floor(uv)-0.5; base_uv*=shadowMapSizeAndInverse.y; vec2 uvw0=4.-3.*st;vec2 uvw1=vec2(7.);vec2 uvw2=1.+3.*st;vec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;vec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;float shadow=0.;shadow+=uvw0.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z),0.);shadow+=uvw1.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z),0.);shadow+=uvw2.x*uvw0.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z),0.);shadow+=uvw0.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z),0.);shadow+=uvw1.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z),0.);shadow+=uvw2.x*uvw1.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z),0.);shadow+=uvw0.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z),0.);shadow+=uvw1.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z),0.);shadow+=uvw2.x*uvw2.y*TEXTUREFUNC(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z),0.);shadow=shadow/144.;shadow=mix(darkness,1.,shadow);return computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);}} const vec3 PoissonSamplers32[64]=vec3[64]( vec3(0.06407013,0.05409927,0.), vec3(0.7366577,0.5789394,0.), vec3(-0.6270542,-0.5320278,0.), vec3(-0.4096107,0.8411095,0.), vec3(0.6849564,-0.4990818,0.), vec3(-0.874181,-0.04579735,0.), vec3(0.9989998,0.0009880066,0.), vec3(-0.004920578,-0.9151649,0.), vec3(0.1805763,0.9747483,0.), vec3(-0.2138451,0.2635818,0.), vec3(0.109845,0.3884785,0.), vec3(0.06876755,-0.3581074,0.), vec3(0.374073,-0.7661266,0.), vec3(0.3079132,-0.1216763,0.), vec3(-0.3794335,-0.8271583,0.), vec3(-0.203878,-0.07715034,0.), vec3(0.5912697,0.1469799,0.), vec3(-0.88069,0.3031784,0.), vec3(0.5040108,0.8283722,0.), vec3(-0.5844124,0.5494877,0.), vec3(0.6017799,-0.1726654,0.), vec3(-0.5554981,0.1559997,0.), vec3(-0.3016369,-0.3900928,0.), vec3(-0.5550632,-0.1723762,0.), vec3(0.925029,0.2995041,0.), vec3(-0.2473137,0.5538505,0.), vec3(0.9183037,-0.2862392,0.), vec3(0.2469421,0.6718712,0.), vec3(0.3916397,-0.4328209,0.), vec3(-0.03576927,-0.6220032,0.), vec3(-0.04661255,0.7995201,0.), vec3(0.4402924,0.3640312,0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.), vec3(0.) );const vec3 PoissonSamplers64[64]=vec3[64]( vec3(-0.613392,0.617481,0.), vec3(0.170019,-0.040254,0.), vec3(-0.299417,0.791925,0.), vec3(0.645680,0.493210,0.), vec3(-0.651784,0.717887,0.), vec3(0.421003,0.027070,0.), vec3(-0.817194,-0.271096,0.), vec3(-0.705374,-0.668203,0.), vec3(0.977050,-0.108615,0.), vec3(0.063326,0.142369,0.), vec3(0.203528,0.214331,0.), vec3(-0.667531,0.326090,0.), vec3(-0.098422,-0.295755,0.), vec3(-0.885922,0.215369,0.), vec3(0.566637,0.605213,0.), vec3(0.039766,-0.396100,0.), vec3(0.751946,0.453352,0.), vec3(0.078707,-0.715323,0.), vec3(-0.075838,-0.529344,0.), vec3(0.724479,-0.580798,0.), vec3(0.222999,-0.215125,0.), vec3(-0.467574,-0.405438,0.), vec3(-0.248268,-0.814753,0.), vec3(0.354411,-0.887570,0.), vec3(0.175817,0.382366,0.), vec3(0.487472,-0.063082,0.), vec3(-0.084078,0.898312,0.), vec3(0.488876,-0.783441,0.), vec3(0.470016,0.217933,0.), vec3(-0.696890,-0.549791,0.), vec3(-0.149693,0.605762,0.), vec3(0.034211,0.979980,0.), vec3(0.503098,-0.308878,0.), vec3(-0.016205,-0.872921,0.), vec3(0.385784,-0.393902,0.), vec3(-0.146886,-0.859249,0.), vec3(0.643361,0.164098,0.), vec3(0.634388,-0.049471,0.), vec3(-0.688894,0.007843,0.), vec3(0.464034,-0.188818,0.), vec3(-0.440840,0.137486,0.), vec3(0.364483,0.511704,0.), vec3(0.034028,0.325968,0.), vec3(0.099094,-0.308023,0.), vec3(0.693960,-0.366253,0.), vec3(0.678884,-0.204688,0.), vec3(0.001801,0.780328,0.), vec3(0.145177,-0.898984,0.), vec3(0.062655,-0.611866,0.), vec3(0.315226,-0.604297,0.), vec3(-0.780145,0.486251,0.), vec3(-0.371868,0.882138,0.), vec3(0.200476,0.494430,0.), vec3(-0.494552,-0.711051,0.), vec3(0.612476,0.705252,0.), vec3(-0.578845,-0.768792,0.), vec3(-0.772454,-0.090976,0.), vec3(0.504440,0.372295,0.), vec3(0.155736,0.065157,0.), vec3(0.391522,0.849605,0.), vec3(-0.620106,-0.328104,0.), vec3(0.789239,-0.419965,0.), vec3(-0.545396,0.538133,0.), vec3(-0.178564,-0.596057,0.) ); #define inline float computeShadowWithCSMPCSS(float layer,vec4 vPositionFromLight,float depthMetric,highp sampler2DArray depthSampler,highp sampler2DArrayShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers,vec2 lightSizeUVCorrection,float depthCorrection,float penumbraDarkness) {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5)); #ifdef USE_REVERSE_DEPTHBUFFER uvDepth.z=clamp(ZINCLIP,SMALLEST_ABOVE_ZERO,1.); #else uvDepth.z=clamp(ZINCLIP,0.,GREATEST_LESS_THAN_ONE); #endif vec4 uvDepthLayer=vec4(uvDepth.x,uvDepth.y,layer,uvDepth.z);float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i1.0 || depthMetric<0.0) {return 1.0;} else {vec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;vec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));uvDepth.z=ZINCLIP;float blockerDepth=0.0;float sumBlockerDepth=0.0;float numBlocker=0.0;for (int i=0; i(_DEFINENAME_,BUMP,_VARYINGNAME_,Bump,_SAMPLERNAME_,bump) #endif #if defined(DETAIL) #include(_DEFINENAME_,DETAIL,_VARYINGNAME_,Detail,_SAMPLERNAME_,detail) #endif #if defined(BUMP) && defined(PARALLAX) const float minSamples=4.;const float maxSamples=15.;const int iMaxSamples=15;vec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {float parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;parallaxLimit*=parallaxScale;vec2 vOffsetDir=normalize(vViewDirCoT.xy);vec2 vMaxOffset=vOffsetDir*parallaxLimit;float numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));float stepSize=1.0/numSamples;float currRayHeight=1.0;vec2 vCurrOffset=vec2(0,0);vec2 vLastOffset=vec2(0,0);float lastSampledHeight=1.0;float currSampledHeight=1.0;bool keepWorking=true;for (int i=0; icurrRayHeight) {float delta1=currSampledHeight-currRayHeight;float delta2=(currRayHeight+stepSize)-lastSampledHeight;float ratio=delta1/(delta1+delta2);vCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;keepWorking=false;} else {currRayHeight-=stepSize;vLastOffset=vCurrOffset; #ifdef PARALLAX_RHS vCurrOffset-=stepSize*vMaxOffset; #else vCurrOffset+=stepSize*vMaxOffset; #endif lastSampledHeight=currSampledHeight;}} return vCurrOffset;} vec2 parallaxOffset(vec3 viewDir,float heightScale) {float height=texture2D(bumpSampler,vBumpUV).w;vec2 texCoordOffset=heightScale*viewDir.xy*height; #ifdef PARALLAX_RHS return texCoordOffset; #else return -texCoordOffset; #endif } #endif `; if (!ShaderStore.IncludesShadersStore[name174]) { ShaderStore.IncludesShadersStore[name174] = shader174; } bumpFragmentFunctions = { name: name174, shader: shader174 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/fogFragmentDeclaration.js var name175, shader175, fogFragmentDeclaration; var init_fogFragmentDeclaration2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/fogFragmentDeclaration.js"() { init_shaderStore(); name175 = "fogFragmentDeclaration"; shader175 = `#ifdef FOG #define FOGMODE_NONE 0. #define FOGMODE_EXP 1. #define FOGMODE_EXP2 2. #define FOGMODE_LINEAR 3. #define E 2.71828 uniform vec4 vFogInfos;uniform vec3 vFogColor;varying vec3 vFogDistance;float CalcFogFactor() {float fogCoeff=1.0;float fogStart=vFogInfos.y;float fogEnd=vFogInfos.z;float fogDensity=vFogInfos.w;float fogDistance=length(vFogDistance);if (FOGMODE_LINEAR==vFogInfos.x) {fogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);} else if (FOGMODE_EXP==vFogInfos.x) {fogCoeff=1.0/pow(E,fogDistance*fogDensity);} else if (FOGMODE_EXP2==vFogInfos.x) {fogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);} return clamp(fogCoeff,0.0,1.0);} #endif `; if (!ShaderStore.IncludesShadersStore[name175]) { ShaderStore.IncludesShadersStore[name175] = shader175; } fogFragmentDeclaration = { name: name175, shader: shader175 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpFragment.js var name176, shader176, bumpFragment; var init_bumpFragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/bumpFragment.js"() { init_shaderStore(); name176 = "bumpFragment"; shader176 = `vec2 uvOffset=vec2(0.0,0.0); #if defined(BUMP) || defined(PARALLAX) || defined(DETAIL) #ifdef NORMALXYSCALE float normalScale=1.0; #elif defined(BUMP) float normalScale=vBumpInfos.y; #else float normalScale=1.0; #endif #if defined(TANGENT) && defined(NORMAL) mat3 TBN=vTBN; #elif defined(BUMP) vec2 TBNUV=gl_FrontFacing ? vBumpUV : -vBumpUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vTangentSpaceParams); #else vec2 TBNUV=gl_FrontFacing ? vDetailUV : -vDetailUV;mat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,TBNUV,vec2(1.,1.)); #endif #elif defined(ANISOTROPIC) #if defined(TANGENT) && defined(NORMAL) mat3 TBN=vTBN; #else vec2 TBNUV=gl_FrontFacing ? vMainUV1 : -vMainUV1;mat3 TBN=cotangent_frame(normalW,vPositionW,TBNUV,vec2(1.,1.)); #endif #endif #ifdef PARALLAX mat3 invTBN=transposeMat3(TBN); #ifdef PARALLAXOCCLUSION uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z); #else uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z); #endif #endif #ifdef DETAIL vec4 detailColor=texture2D(detailSampler,vDetailUV+uvOffset);vec2 detailNormalRG=detailColor.wy*2.0-1.0;float detailNormalB=sqrt(1.-saturate(dot(detailNormalRG,detailNormalRG)));vec3 detailNormal=vec3(detailNormalRG,detailNormalB); #endif #ifdef BUMP #ifdef OBJECTSPACE_NORMALMAP #define CUSTOM_FRAGMENT_BUMP_FRAGMENT normalW=normalize(texture2D(bumpSampler,vBumpUV).xyz *2.0-1.0);normalW=normalize(mat3(normalMatrix)*normalW); #elif !defined(DETAIL) normalW=perturbNormal(TBN,texture2D(bumpSampler,vBumpUV+uvOffset).xyz,vBumpInfos.y); #else vec3 bumpNormal=texture2D(bumpSampler,vBumpUV+uvOffset).xyz*2.0-1.0; #if DETAIL_NORMALBLENDMETHOD==0 detailNormal.xy*=vDetailInfos.z;vec3 blendedNormal=normalize(vec3(bumpNormal.xy+detailNormal.xy,bumpNormal.z*detailNormal.z)); #elif DETAIL_NORMALBLENDMETHOD==1 detailNormal.xy*=vDetailInfos.z;bumpNormal+=vec3(0.0,0.0,1.0);detailNormal*=vec3(-1.0,-1.0,1.0);vec3 blendedNormal=bumpNormal*dot(bumpNormal,detailNormal)/bumpNormal.z-detailNormal; #endif normalW=perturbNormalBase(TBN,blendedNormal,vBumpInfos.y); #endif #elif defined(DETAIL) detailNormal.xy*=vDetailInfos.z;normalW=perturbNormalBase(TBN,detailNormal,vDetailInfos.z); #endif `; if (!ShaderStore.IncludesShadersStore[name176]) { ShaderStore.IncludesShadersStore[name176] = shader176; } bumpFragment = { name: name176, shader: shader176 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/decalFragment.js var name177, shader177, decalFragment; var init_decalFragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/decalFragment.js"() { init_shaderStore(); name177 = "decalFragment"; shader177 = `#ifdef DECAL #ifdef GAMMADECAL decalColor.rgb=toLinearSpace(decalColor.rgb); #endif #ifdef DECAL_SMOOTHALPHA decalColor.a*=decalColor.a; #endif surfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,decalColor.rgb,decalColor.a); #endif `; if (!ShaderStore.IncludesShadersStore[name177]) { ShaderStore.IncludesShadersStore[name177] = shader177; } decalFragment = { name: name177, shader: shader177 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/depthPrePass.js var name178, shader178, depthPrePass; var init_depthPrePass2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/depthPrePass.js"() { init_shaderStore(); name178 = "depthPrePass"; shader178 = `#ifdef DEPTHPREPASS gl_FragColor=vec4(0.,0.,0.,1.0);return; #endif `; if (!ShaderStore.IncludesShadersStore[name178]) { ShaderStore.IncludesShadersStore[name178] = shader178; } depthPrePass = { name: name178, shader: shader178 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/lightFragment.js var name179, shader179, lightFragment; var init_lightFragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/lightFragment.js"() { init_shaderStore(); name179 = "lightFragment"; shader179 = `#ifdef LIGHT{X} #if defined(SHADOWONLY) || defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}) #else vec4 diffuse{X}=light{X}.vLightDiffuse; #define CUSTOM_LIGHT{X}_COLOR #if defined(PBR) && defined(CLUSTLIGHT{X}) && defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0 {int sliceIndex=min(getClusteredSliceIndex(light{X}.vSliceData,vViewDepth),CLUSTLIGHT_SLICES-1);info=computeClusteredLighting( lightDataTexture{X}, tileMaskTexture{X}, light{X}.vLightData, ivec2(light{X}.vSliceRanges[sliceIndex]), viewDirectionW, normalW, vPositionW, surfaceAlbedo, reflectivityOut #ifdef IRIDESCENCE ,iridescenceIntensity #endif #ifdef SS_TRANSLUCENCY ,subSurfaceOut #endif #ifdef SPECULARTERM ,AARoughnessFactors.x #endif #ifdef ANISOTROPIC ,anisotropicOut #endif #ifdef SHEEN ,sheenOut #endif #ifdef CLEARCOAT ,clearcoatOut #endif );} #elif defined(PBR) #ifdef SPOTLIGHT{X} preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,vPositionW); #elif defined(POINTLIGHT{X}) preInfo=computePointAndSpotPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW,vPositionW); #elif defined(HEMILIGHT{X}) preInfo=computeHemisphericPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); #elif defined(DIRLIGHT{X}) preInfo=computeDirectionalPreLightingInfo(light{X}.vLightData,viewDirectionW,normalW); #elif defined(AREALIGHT{X}) && defined(AREALIGHTSUPPORTED) preInfo=computeAreaPreLightingInfo(areaLightsLTC1Sampler,areaLightsLTC2Sampler,viewDirectionW,normalW,vPositionW,light{X}.vLightData,light{X}.vLightWidth.xyz,light{X}.vLightHeight.xyz,roughness); #endif preInfo.NdotV=NdotV; #ifdef SPOTLIGHT{X} #ifdef LIGHT_FALLOFF_GLTF{X} preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); #ifdef IESLIGHTTEXTURE{X} preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X}); #else preInfo.attenuation*=computeDirectionalLightFalloff_GLTF(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); #endif #elif defined(LIGHT_FALLOFF_PHYSICAL{X}) preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); #ifdef IESLIGHTTEXTURE{X} preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X}); #else preInfo.attenuation*=computeDirectionalLightFalloff_Physical(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w); #endif #elif defined(LIGHT_FALLOFF_STANDARD{X}) preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); #ifdef IESLIGHTTEXTURE{X} preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X}); #else preInfo.attenuation*=computeDirectionalLightFalloff_Standard(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w); #endif #else preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); #ifdef IESLIGHTTEXTURE{X} preInfo.attenuation*=computeDirectionalLightFalloff_IES(light{X}.vLightDirection.xyz,preInfo.L,iesLightTexture{X}); #else preInfo.attenuation*=computeDirectionalLightFalloff(light{X}.vLightDirection.xyz,preInfo.L,light{X}.vLightDirection.w,light{X}.vLightData.w,light{X}.vLightFalloff.z,light{X}.vLightFalloff.w); #endif #endif #elif defined(POINTLIGHT{X}) #ifdef LIGHT_FALLOFF_GLTF{X} preInfo.attenuation=computeDistanceLightFalloff_GLTF(preInfo.lightDistanceSquared,light{X}.vLightFalloff.y); #elif defined(LIGHT_FALLOFF_PHYSICAL{X}) preInfo.attenuation=computeDistanceLightFalloff_Physical(preInfo.lightDistanceSquared); #elif defined(LIGHT_FALLOFF_STANDARD{X}) preInfo.attenuation=computeDistanceLightFalloff_Standard(preInfo.lightOffset,light{X}.vLightFalloff.x); #else preInfo.attenuation=computeDistanceLightFalloff(preInfo.lightOffset,preInfo.lightDistanceSquared,light{X}.vLightFalloff.x,light{X}.vLightFalloff.y); #endif #else preInfo.attenuation=1.0; #endif #if defined(HEMILIGHT{X}) || defined(AREALIGHT{X}) preInfo.roughness=roughness; #else preInfo.roughness=adjustRoughnessFromLightProperties(roughness,light{X}.vLightSpecular.a,preInfo.lightDistance); #endif preInfo.diffuseRoughness=diffuseRoughness;preInfo.surfaceAlbedo=surfaceAlbedo; #ifdef IRIDESCENCE preInfo.iridescenceIntensity=iridescenceIntensity; #endif #ifdef SS_TRANSLUCENCY info.diffuseTransmission=vec3(0.0); #endif #ifdef HEMILIGHT{X} info.diffuse=computeHemisphericDiffuseLighting(preInfo,diffuse{X}.rgb,light{X}.vLightGround); #elif defined(AREALIGHT{X}) info.diffuse=computeAreaDiffuseLighting(preInfo,diffuse{X}.rgb); #elif defined(SS_TRANSLUCENCY) #ifndef SS_TRANSLUCENCY_LEGACY info.diffuse=computeDiffuseLighting(preInfo,diffuse{X}.rgb)*(1.0-subSurfaceOut.translucencyIntensity);info.diffuseTransmission=computeDiffuseTransmittedLighting(preInfo,diffuse{X}.rgb,subSurfaceOut.transmittance); #else info.diffuse=computeDiffuseTransmittedLighting(preInfo,diffuse{X}.rgb,subSurfaceOut.transmittance); #endif #else info.diffuse=computeDiffuseLighting(preInfo,diffuse{X}.rgb); #endif #ifdef SPECULARTERM #if AREALIGHT{X} info.specular=computeAreaSpecularLighting(preInfo,light{X}.vLightSpecular.rgb,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90); #else #if (CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR) {vec3 metalFresnel=reflectivityOut.specularWeight*getF82Specular(preInfo.VdotH,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90,reflectivityOut.roughness);vec3 dielectricFresnel=fresnelSchlickGGX(preInfo.VdotH,reflectivityOut.dielectricColorF0,reflectivityOut.colorReflectanceF90);coloredFresnel=mix(dielectricFresnel,metalFresnel,reflectivityOut.metallic);} #else coloredFresnel=fresnelSchlickGGX(preInfo.VdotH,clearcoatOut.specularEnvironmentR0,reflectivityOut.colorReflectanceF90); #endif #ifndef LEGACY_SPECULAR_ENERGY_CONSERVATION {float NdotH=dot(normalW,preInfo.H);vec3 fresnel=fresnelSchlickGGX(NdotH,vec3(reflectanceF0),specularEnvironmentR90);info.diffuse*=(vec3(1.0)-fresnel);} #endif #ifdef ANISOTROPIC info.specular=computeAnisotropicSpecularLighting(preInfo,viewDirectionW,normalW,anisotropicOut.anisotropicTangent,anisotropicOut.anisotropicBitangent,anisotropicOut.anisotropy,clearcoatOut.specularEnvironmentR0,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb); #else info.specular=computeSpecularLighting(preInfo,normalW,clearcoatOut.specularEnvironmentR0,coloredFresnel,AARoughnessFactors.x,diffuse{X}.rgb); #endif #endif #endif #ifndef AREALIGHT{X} #ifdef SHEEN #ifdef SHEEN_LINKWITHALBEDO preInfo.roughness=sheenOut.sheenIntensity; #else #ifdef HEMILIGHT{X} preInfo.roughness=sheenOut.sheenRoughness; #else preInfo.roughness=adjustRoughnessFromLightProperties(sheenOut.sheenRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); #endif #endif info.sheen=computeSheenLighting(preInfo,normalW,sheenOut.sheenColor,specularEnvironmentR90,AARoughnessFactors.x,diffuse{X}.rgb); #endif #ifdef CLEARCOAT #ifdef HEMILIGHT{X} preInfo.roughness=clearcoatOut.clearCoatRoughness; #else preInfo.roughness=adjustRoughnessFromLightProperties(clearcoatOut.clearCoatRoughness,light{X}.vLightSpecular.a,preInfo.lightDistance); #endif info.clearCoat=computeClearCoatLighting(preInfo,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatAARoughnessFactors.x,clearcoatOut.clearCoatIntensity,diffuse{X}.rgb); #ifdef CLEARCOAT_TINT absorption=computeClearCoatLightingAbsorption(clearcoatOut.clearCoatNdotVRefract,preInfo.L,clearcoatOut.clearCoatNormalW,clearcoatOut.clearCoatColor,clearcoatOut.clearCoatThickness,clearcoatOut.clearCoatIntensity);info.diffuse*=absorption; #ifdef SS_TRANSLUCENCY info.diffuseTransmission*=absorption; #endif #ifdef SPECULARTERM info.specular*=absorption; #endif #endif info.diffuse*=info.clearCoat.w; #ifdef SS_TRANSLUCENCY info.diffuseTransmission*=info.clearCoat.w; #endif #ifdef SPECULARTERM info.specular*=info.clearCoat.w; #endif #ifdef SHEEN info.sheen*=info.clearCoat.w; #endif #endif #endif #else #ifdef SPOTLIGHT{X} #ifdef IESLIGHTTEXTURE{X} info=computeIESSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness,iesLightTexture{X}); #else info=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness); #endif #elif defined(HEMILIGHT{X}) info=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,light{X}.vLightGround,glossiness); #elif defined(POINTLIGHT{X}) || defined(DIRLIGHT{X}) info=computeLighting(viewDirectionW,normalW,light{X}.vLightData,diffuse{X}.rgb,light{X}.vLightSpecular.rgb,diffuse{X}.a,glossiness); #elif defined(AREALIGHT{X}) && defined(AREALIGHTSUPPORTED) info=computeAreaLighting(areaLightsLTC1Sampler,areaLightsLTC2Sampler,viewDirectionW,normalW,vPositionW,light{X}.vLightData.xyz,light{X}.vLightWidth.rgb,light{X}.vLightHeight.rgb,diffuse{X}.rgb,light{X}.vLightSpecular.rgb, #ifdef AREALIGHTNOROUGHTNESS 0.5 #else vReflectionInfos.y #endif ); #elif defined(CLUSTLIGHT{X}) && CLUSTLIGHT_BATCH>0 {int sliceIndex=min(getClusteredSliceIndex(light{X}.vSliceData,vViewDepth),CLUSTLIGHT_SLICES-1);info=computeClusteredLighting(lightDataTexture{X},tileMaskTexture{X},viewDirectionW,normalW,light{X}.vLightData,ivec2(light{X}.vSliceRanges[sliceIndex]),glossiness);} #endif #endif #ifdef PROJECTEDLIGHTTEXTURE{X} info.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightTexture{X},textureProjectionMatrix{X},vPositionW); #endif #endif #ifdef SHADOW{X} #ifdef SHADOWCSM{X} for (int i=0; i=0.) {index{X}=i;break;}} #ifdef SHADOWCSMUSESHADOWMAXZ{X} if (index{X}>=0) #endif { #if defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #else shadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #endif #else shadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #ifdef SHADOWCSMDEBUG{X} shadowDebug{X}=vec3(shadow)*vCascadeColorsMultiplier{X}[index{X}]; #endif #ifndef SHADOWCSMNOBLEND{X} float frustumLength=frustumLengths{X}[index{X}];float diffRatio=clamp(diff{X}/frustumLength,0.,1.)*cascadeBlendFactor{X};if (index{X}<(SHADOWCSMNUM_CASCADES{X}-1) && diffRatio<1.) {index{X}+=1;float nextShadow=0.; #if defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) nextShadow=computeShadowWithCSMPCF1(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) nextShadow=computeShadowWithCSMPCF3(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else nextShadow=computeShadowWithCSMPCF5(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) nextShadow=computeShadowWithCSMPCSS16(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #elif defined(SHADOWMEDIUMQUALITY{X}) nextShadow=computeShadowWithCSMPCSS32(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #else nextShadow=computeShadowWithCSMPCSS64(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w,lightSizeUVCorrection{X}[index{X}],depthCorrection{X}[index{X}],penumbraDarkness{X}); #endif #else nextShadow=computeShadowCSM(float(index{X}),vPositionFromLight{X}[index{X}],vDepthMetric{X}[index{X}],shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif shadow=mix(nextShadow,shadow,diffRatio); #ifdef SHADOWCSMDEBUG{X} shadowDebug{X}=mix(vec3(nextShadow)*vCascadeColorsMultiplier{X}[index{X}],shadowDebug{X},diffRatio); #endif } #endif } #elif defined(SHADOWCLOSEESM{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithCloseESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); #else shadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWESM{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithESMCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues); #else shadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPOISSON{X}) #if defined(SHADOWCUBE{X}) shadow=computeShadowWithPoissonSamplingCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues); #else shadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCF{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #elif defined(SHADOWPCSS{X}) #if defined(SHADOWLOWQUALITY{X}) shadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #elif defined(SHADOWMEDIUMQUALITY{X}) shadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #else shadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthTexture{X},shadowTexture{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #else #if defined(SHADOWCUBE{X}) shadow=computeShadowCube(vPositionW,light{X}.vLightData.xyz,shadowTexture{X},light{X}.shadowsInfo.x,light{X}.depthValues); #else shadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowTexture{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w); #endif #endif #ifdef SHADOWONLY #ifndef SHADOWINUSE #define SHADOWINUSE #endif globalShadow+=shadow;shadowLightCount+=1.0; #endif #else shadow=1.; #endif aggShadow+=shadow;numLights+=1.0; #ifndef SHADOWONLY #ifdef CUSTOMUSERLIGHTING diffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow); #ifdef SPECULARTERM specularBase+=computeCustomSpecularLighting(info,specularBase,shadow); #endif #elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) diffuseBase+=lightmapColor.rgb*shadow; #ifdef SPECULARTERM #ifndef LIGHTMAPNOSPECULAR{X} specularBase+=info.specular*shadow*lightmapColor.rgb; #endif #endif #ifdef CLEARCOAT #ifndef LIGHTMAPNOSPECULAR{X} clearCoatBase+=info.clearCoat.rgb*shadow*lightmapColor.rgb; #endif #endif #ifdef SHEEN #ifndef LIGHTMAPNOSPECULAR{X} sheenBase+=info.sheen.rgb*shadow; #endif #endif #else #ifdef SHADOWCSMDEBUG{X} diffuseBase+=info.diffuse*shadowDebug{X}; #else diffuseBase+=info.diffuse*shadow; #endif #ifdef SS_TRANSLUCENCY diffuseTransmissionBase+=info.diffuseTransmission*shadow; #endif #ifdef SPECULARTERM specularBase+=info.specular*shadow; #endif #ifdef CLEARCOAT clearCoatBase+=info.clearCoat.rgb*shadow; #endif #ifdef SHEEN sheenBase+=info.sheen.rgb*shadow; #endif #endif #endif #endif `; if (!ShaderStore.IncludesShadersStore[name179]) { ShaderStore.IncludesShadersStore[name179] = shader179; } lightFragment = { name: name179, shader: shader179 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/logDepthFragment.js var name180, shader180, logDepthFragment; var init_logDepthFragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/logDepthFragment.js"() { init_shaderStore(); name180 = "logDepthFragment"; shader180 = `#ifdef LOGARITHMICDEPTH gl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5; #endif `; if (!ShaderStore.IncludesShadersStore[name180]) { ShaderStore.IncludesShadersStore[name180] = shader180; } logDepthFragment = { name: name180, shader: shader180 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/fogFragment.js var name181, shader181, fogFragment; var init_fogFragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/fogFragment.js"() { init_shaderStore(); name181 = "fogFragment"; shader181 = `#ifdef FOG float fog=CalcFogFactor(); #ifdef PBR fog=toLinearSpace(fog); #endif color.rgb=mix(vFogColor,color.rgb,fog); #endif `; if (!ShaderStore.IncludesShadersStore[name181]) { ShaderStore.IncludesShadersStore[name181] = shader181; } fogFragment = { name: name181, shader: shader181 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/oitFragment.js var name182, shader182, oitFragment; var init_oitFragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/oitFragment.js"() { init_shaderStore(); name182 = "oitFragment"; shader182 = `#ifdef ORDER_INDEPENDENT_TRANSPARENCY float fragDepth=gl_FragCoord.z; #ifdef ORDER_INDEPENDENT_TRANSPARENCY_16BITS uint halfFloat=packHalf2x16(vec2(fragDepth));vec2 full=unpackHalf2x16(halfFloat);fragDepth=full.x; #endif ivec2 fragCoord=ivec2(gl_FragCoord.xy);vec2 lastDepth=texelFetch(oitDepthSampler,fragCoord,0).rg;vec4 lastFrontColor=texelFetch(oitFrontColorSampler,fragCoord,0);depth.rg=vec2(-MAX_DEPTH);frontColor=lastFrontColor;backColor=vec4(0.0); #ifdef USE_REVERSE_DEPTHBUFFER float furthestDepth=-lastDepth.x;float nearestDepth=lastDepth.y; #else float nearestDepth=-lastDepth.x;float furthestDepth=lastDepth.y; #endif float alphaMultiplier=1.0-lastFrontColor.a; #ifdef USE_REVERSE_DEPTHBUFFER if (fragDepth>nearestDepth || fragDepthfurthestDepth) { #endif return;} #ifdef USE_REVERSE_DEPTHBUFFER if (fragDepthfurthestDepth) { #else if (fragDepth>nearestDepth && fragDepth defaultPixelShader }); var name183, shader183, defaultPixelShader; var init_default_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/default.fragment.js"() { init_shaderStore(); init_defaultFragmentDeclaration(); init_defaultUboDeclaration2(); init_prePassDeclaration2(); init_oitDeclaration2(); init_mainUVVaryingDeclaration2(); init_helperFunctions2(); init_lightFragmentDeclaration(); init_lightUboDeclaration2(); init_lightsFragmentFunctions2(); init_shadowsFragmentFunctions2(); init_samplerFragmentDeclaration2(); init_fresnelFunction2(); init_reflectionFunction2(); init_imageProcessingDeclaration2(); init_imageProcessingFunctions2(); init_bumpFragmentMainFunctions2(); init_bumpFragmentFunctions2(); init_clipPlaneFragmentDeclaration2(); init_logDepthDeclaration2(); init_fogFragmentDeclaration2(); init_clipPlaneFragment2(); init_bumpFragment2(); init_decalFragment2(); init_depthPrePass2(); init_lightFragment2(); init_logDepthFragment2(); init_fogFragment2(); init_oitFragment2(); name183 = "defaultPixelShader"; shader183 = `#define CUSTOM_FRAGMENT_EXTENSION #include<__decl__defaultFragment> #if defined(BUMP) || !defined(NORMAL) #extension GL_OES_standard_derivatives : enable #endif #include[SCENE_MRT_COUNT] #include #define CUSTOM_FRAGMENT_BEGIN #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif varying vec3 vPositionW; #ifdef NORMAL varying vec3 vNormalW; #endif #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) varying vec4 vColor; #endif #if defined(CLUSTLIGHT_BATCH) && CLUSTLIGHT_BATCH>0 varying float vViewDepth; #endif #include[1..7] #include #include<__decl__lightFragment>[0..maxSimultaneousLights] #include #include #include(_DEFINENAME_,DIFFUSE,_VARYINGNAME_,Diffuse,_SAMPLERNAME_,diffuse) #include(_DEFINENAME_,AMBIENT,_VARYINGNAME_,Ambient,_SAMPLERNAME_,ambient) #include(_DEFINENAME_,OPACITY,_VARYINGNAME_,Opacity,_SAMPLERNAME_,opacity) #include(_DEFINENAME_,EMISSIVE,_VARYINGNAME_,Emissive,_SAMPLERNAME_,emissive) #include(_DEFINENAME_,LIGHTMAP,_VARYINGNAME_,Lightmap,_SAMPLERNAME_,lightmap) #include(_DEFINENAME_,DECAL,_VARYINGNAME_,Decal,_SAMPLERNAME_,decal) #ifdef REFRACTION #ifdef REFRACTIONMAP_3D uniform samplerCube refractionCubeSampler; #else uniform sampler2D refraction2DSampler; #endif #endif #if defined(SPECULARTERM) #include(_DEFINENAME_,SPECULAR,_VARYINGNAME_,Specular,_SAMPLERNAME_,specular) #endif #include #ifdef REFLECTION #ifdef REFLECTIONMAP_3D uniform samplerCube reflectionCubeSampler; #else uniform sampler2D reflection2DSampler; #endif #ifdef REFLECTIONMAP_SKYBOX varying vec3 vPositionUVW; #else #if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED) varying vec3 vDirectionW; #endif #endif #include #endif #include #include #include #include #include #include #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include vec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);vec4 baseColor=vec4(1.,1.,1.,1.);vec3 diffuseColor=vDiffuseColor.rgb;float alpha=vDiffuseColor.a; #ifdef NORMAL vec3 normalW=normalize(vNormalW); #else vec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); #endif #include #ifdef TWOSIDEDLIGHTING normalW=gl_FrontFacing ? normalW : -normalW; #endif #ifdef DIFFUSE baseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset); #if defined(ALPHATEST) && !defined(ALPHATEST_AFTERALLALPHACOMPUTATIONS) if (baseColor.a(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) #endif #include #if defined(VERTEXCOLOR) || defined(INSTANCESCOLOR) && defined(INSTANCES) baseColor.rgb*=vColor.rgb; #endif #ifdef DETAIL baseColor.rgb=baseColor.rgb*2.0*mix(0.5,detailColor.r,vDetailInfos.y); #endif #if defined(DECAL) && defined(DECAL_AFTER_DETAIL) vec4 decalColor=texture2D(decalSampler,vDecalUV+uvOffset); #include(surfaceAlbedo,baseColor,GAMMADECAL,_GAMMADECAL_NOTUSED_) #endif #define CUSTOM_FRAGMENT_UPDATE_DIFFUSE vec3 baseAmbientColor=vec3(1.,1.,1.); #ifdef AMBIENT baseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y; #endif #define CUSTOM_FRAGMENT_BEFORE_LIGHTS float glossiness=vSpecularColor.a;vec3 specularColor=vSpecularColor.rgb; #ifdef SPECULARTERM #ifdef SPECULAR vec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);specularColor=specularMapColor.rgb; #ifdef GLOSSINESS glossiness=glossiness*specularMapColor.a; #endif #endif #endif vec3 diffuseBase=vec3(0.,0.,0.);lightingInfo info; #ifdef SPECULARTERM vec3 specularBase=vec3(0.,0.,0.); #endif float shadow=1.;float aggShadow=0.;float numLights=0.; #ifdef LIGHTMAP vec4 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset); #ifdef RGBDLIGHTMAP lightmapColor.rgb=fromRGBD(lightmapColor); #endif lightmapColor.rgb*=vLightmapInfos.y; #endif #include[0..maxSimultaneousLights] aggShadow=aggShadow/numLights;vec4 refractionColor=vec4(0.,0.,0.,1.); #ifdef REFRACTION vec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y)); #ifdef REFRACTIONMAP_3D #ifdef USE_LOCAL_REFRACTIONMAP_CUBIC refractionVector=parallaxCorrectNormal(vPositionW,refractionVector,vRefractionSize,vRefractionPosition); #endif refractionVector.y=refractionVector.y*vRefractionInfos.w;vec4 refractionLookup=textureCube(refractionCubeSampler,refractionVector);if (dot(refractionVector,viewDirectionW)<1.0) {refractionColor=refractionLookup;} #else vec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));vec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;refractionCoords.y=1.0-refractionCoords.y;refractionColor=texture2D(refraction2DSampler,refractionCoords); #endif #ifdef RGBDREFRACTION refractionColor.rgb=fromRGBD(refractionColor); #endif #ifdef IS_REFRACTION_LINEAR refractionColor.rgb=toGammaSpace(refractionColor.rgb); #endif refractionColor.rgb*=vRefractionInfos.x; #endif vec4 reflectionColor=vec4(0.,0.,0.,1.); #ifdef REFLECTION vec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW); #ifdef REFLECTIONMAP_OPPOSITEZ vReflectionUVW.z*=-1.0; #endif #ifdef REFLECTIONMAP_3D #ifdef ROUGHNESS float bias=vReflectionInfos.y; #ifdef SPECULARTERM #ifdef SPECULAR #ifdef GLOSSINESS bias*=(1.0-specularMapColor.a); #endif #endif #endif reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias); #else reflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW); #endif #else vec2 coords=vReflectionUVW.xy; #ifdef REFLECTIONMAP_PROJECTION coords/=vReflectionUVW.z; #endif coords.y=1.0-coords.y;reflectionColor=texture2D(reflection2DSampler,coords); #endif #ifdef RGBDREFLECTION reflectionColor.rgb=fromRGBD(reflectionColor); #endif #ifdef IS_REFLECTION_LINEAR reflectionColor.rgb=toGammaSpace(reflectionColor.rgb); #endif reflectionColor.rgb*=vReflectionInfos.x; #ifdef REFLECTIONFRESNEL float reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a); #ifdef REFLECTIONFRESNELFROMSPECULAR #ifdef SPECULARTERM reflectionColor.rgb*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; #else reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; #endif #else reflectionColor.rgb*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb; #endif #endif #endif #ifdef REFRACTIONFRESNEL float refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);refractionColor.rgb*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb; #endif #ifdef OPACITY vec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset); #ifdef OPACITYRGB opacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);alpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y; #else alpha*=opacityMap.a*vOpacityInfos.y; #endif #endif #if defined(VERTEXALPHA) || defined(INSTANCESCOLOR) && defined(INSTANCES) alpha*=vColor.a; #endif #ifdef OPACITYFRESNEL float opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);alpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y; #endif #ifdef ALPHATEST #ifdef ALPHATEST_AFTERALLALPHACOMPUTATIONS if (alpha #include #ifdef IMAGEPROCESSINGPOSTPROCESS color.rgb=toLinearSpace(color.rgb); #else #ifdef IMAGEPROCESSING color.rgb=toLinearSpace(color.rgb);color=applyImageProcessing(color); #endif #endif color.a*=visibility; #ifdef PREMULTIPLYALPHA color.rgb*=color.a; #endif #define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR #ifdef PREPASS #if SCENE_MRT_COUNT>0 float writeGeometryInfo=color.a>0.4 ? 1.0 : 0.0; #ifdef PREPASS_COLOR gl_FragData[PREPASS_COLOR_INDEX]=color; #endif #ifdef PREPASS_POSITION gl_FragData[PREPASS_POSITION_INDEX]=vec4(vPositionW,writeGeometryInfo); #endif #ifdef PREPASS_LOCAL_POSITION gl_FragData[PREPASS_LOCAL_POSITION_INDEX]=vec4(vPosition,writeGeometryInfo); #endif #if defined(PREPASS_VELOCITY) vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[PREPASS_VELOCITY_INDEX]=vec4(velocity,0.0,writeGeometryInfo); #elif defined(PREPASS_VELOCITY_LINEAR) vec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w)-(vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[PREPASS_VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,writeGeometryInfo); #endif #ifdef PREPASS_IRRADIANCE gl_FragData[PREPASS_IRRADIANCE_INDEX]=vec4(0.0,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_DEPTH gl_FragData[PREPASS_DEPTH_INDEX]=vec4(vViewPos.z,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_SCREENSPACE_DEPTH gl_FragData[PREPASS_SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_NORMALIZED_VIEW_DEPTH gl_FragData[PREPASS_NORMALIZED_VIEW_DEPTH_INDEX]=vec4(vNormViewDepth,0.0,0.0,writeGeometryInfo); #endif #ifdef PREPASS_NORMAL #ifdef PREPASS_NORMAL_WORLDSPACE gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalW,writeGeometryInfo); #else gl_FragData[PREPASS_NORMAL_INDEX]=vec4(normalize((view*vec4(normalW,0.0)).rgb),writeGeometryInfo); #endif #endif #ifdef PREPASS_WORLD_NORMAL gl_FragData[PREPASS_WORLD_NORMAL_INDEX]=vec4(normalW*0.5+0.5,writeGeometryInfo); #endif #ifdef PREPASS_ALBEDO gl_FragData[PREPASS_ALBEDO_INDEX]=vec4(baseColor.rgb,writeGeometryInfo); #endif #ifdef PREPASS_ALBEDO_SQRT gl_FragData[PREPASS_ALBEDO_SQRT_INDEX]=vec4(sqrt(baseColor.rgb),writeGeometryInfo); #endif #ifdef PREPASS_REFLECTIVITY #if defined(SPECULAR) gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularMapColor))*writeGeometryInfo; #else gl_FragData[PREPASS_REFLECTIVITY_INDEX]=vec4(toLinearSpace(specularColor),1.0)*writeGeometryInfo; #endif #endif #endif #endif #if !defined(PREPASS) || defined(WEBGL2) gl_FragColor=color; #endif #include #if ORDER_INDEPENDENT_TRANSPARENCY if (fragDepth==nearestDepth) {frontColor.rgb+=color.rgb*color.a*alphaMultiplier;frontColor.a=1.0-alphaMultiplier*(1.0-color.a);} else {backColor+=color;} #endif #define CUSTOM_FRAGMENT_MAIN_END } `; if (!ShaderStore.ShadersStore[name183]) { ShaderStore.ShadersStore[name183] = shader183; } defaultPixelShader = { name: name183, shader: shader183 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/geometry.vertex.js var geometry_vertex_exports = {}; __export(geometry_vertex_exports, { geometryVertexShaderWGSL: () => geometryVertexShaderWGSL }); var name187, shader187, geometryVertexShaderWGSL; var init_geometry_vertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/geometry.vertex.js"() { init_shaderStore(); init_bonesDeclaration(); init_bakedVertexAnimationDeclaration(); init_morphTargetsVertexGlobalDeclaration(); init_morphTargetsVertexDeclaration(); init_instancesDeclaration(); init_sceneUboDeclaration(); init_clipPlaneVertexDeclaration(); init_morphTargetsVertexGlobal(); init_morphTargetsVertex(); init_instancesVertex(); init_bonesVertex(); init_bakedVertexAnimation(); init_clipPlaneVertex(); init_bumpVertex(); name187 = "geometryVertexShader"; shader187 = `#include #include #include #include[0..maxSimultaneousMorphTargets] #include #include #include attribute position: vec3f; #ifdef HAS_NORMAL_ATTRIBUTE attribute normal: vec3f; #endif #ifdef NEED_UV varying vUV: vec2f; #ifdef ALPHATEST uniform diffuseMatrix: mat4x4f; #endif #ifdef BUMP uniform bumpMatrix: mat4x4f;varying vBumpUV: vec2f; #endif #ifdef REFLECTIVITY uniform reflectivityMatrix: mat4x4f;uniform albedoMatrix: mat4x4f;varying vReflectivityUV: vec2f;varying vAlbedoUV: vec2f; #endif #ifdef METALLIC_TEXTURE varying vMetallicUV: vec2f;uniform metallicMatrix: mat4x4f; #endif #ifdef ROUGHNESS_TEXTURE varying vRoughnessUV: vec2f;uniform roughnessMatrix: mat4x4f; #endif #ifdef UV1 attribute uv: vec2f; #endif #ifdef UV2 attribute uv2: vec2f; #endif #endif #ifdef BUMP varying vWorldView0: vec4f;varying vWorldView1: vec4f;varying vWorldView2: vec4f;varying vWorldView3: vec4f; #endif #ifdef BUMP varying vNormalW: vec3f; #else varying vNormalV: vec3f; #endif varying vViewPos: vec4f; #if defined(POSITION) || defined(BUMP) varying vPositionW: vec3f; #endif #if defined(VELOCITY) || defined(VELOCITY_LINEAR) uniform previousViewProjection: mat4x4f;varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; #endif #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position; #ifdef HAS_NORMAL_ATTRIBUTE var normalUpdated: vec3f=input.normal; #else var normalUpdated: vec3f=vec3f(0.0,0.0,0.0); #endif #ifdef UV1 var uvUpdated: vec2f=input.uv; #endif #ifdef UV2 var uv2Updated: vec2f=input.uv2; #endif #include #include[0..maxSimultaneousMorphTargets] #include #if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED) vCurrentPosition=scene.viewProjection*finalWorld*vec4f(positionUpdated,1.0);vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0); #endif #include #include var worldPos: vec4f= vec4f(finalWorld* vec4f(positionUpdated,1.0)); #ifdef BUMP let vWorldView=scene.view*finalWorld;vertexOutputs.vWorldView0=vWorldView[0];vertexOutputs.vWorldView1=vWorldView[1];vertexOutputs.vWorldView2=vWorldView[2];vertexOutputs.vWorldView3=vWorldView[3];let normalWorld: mat3x3f= mat3x3f(finalWorld[0].xyz,finalWorld[1].xyz,finalWorld[2].xyz);vertexOutputs.vNormalW=normalize(normalWorld*normalUpdated); #else #ifdef NORMAL_WORLDSPACE vertexOutputs.vNormalV=normalize((finalWorld* vec4f(normalUpdated,0.0)).xyz); #else vertexOutputs.vNormalV=normalize(((scene.view*finalWorld)* vec4f(normalUpdated,0.0)).xyz); #endif #endif vertexOutputs.vViewPos=scene.view*worldPos; #if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED) vertexOutputs.vCurrentPosition=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0); #if NUM_BONE_INFLUENCERS>0 var previousInfluence: mat4x4f;previousInfluence=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[0])]*vertexInputs.matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[1])]*vertexInputs.matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[2])]*vertexInputs.matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndices[3])]*vertexInputs.matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[0])]*vertexInputs.matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[1])]*vertexInputs.matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[2])]*vertexInputs.matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 previousInfluence+=uniforms.mPreviousBones[ i32(vertexInputs.matricesIndicesExtra[3])]*vertexInputs.matricesWeightsExtra[3]; #endif vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld*previousInfluence* vec4f(positionUpdated,1.0); #else vertexOutputs.vPreviousPosition=uniforms.previousViewProjection*finalPreviousWorld* vec4f(positionUpdated,1.0); #endif #endif #if defined(POSITION) || defined(BUMP) vertexOutputs.vPositionW=worldPos.xyz/worldPos.w; #endif vertexOutputs.position=scene.viewProjection*finalWorld* vec4f(positionUpdated,1.0); #include #ifdef NEED_UV #ifdef UV1 #if defined(ALPHATEST) && defined(ALPHATEST_UV1) vertexOutputs.vUV=(uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #else vertexOutputs.vUV=uvUpdated; #endif #ifdef BUMP_UV1 vertexOutputs.vBumpUV=(uniforms.bumpMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef REFLECTIVITY_UV1 vertexOutputs.vReflectivityUV=(uniforms.reflectivityMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #else #ifdef METALLIC_UV1 vertexOutputs.vMetallicUV=(uniforms.metallicMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef ROUGHNESS_UV1 vertexOutputs.vRoughnessUV=(uniforms.roughnessMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #endif #ifdef ALBEDO_UV1 vertexOutputs.vAlbedoUV=(uniforms.albedoMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #endif #ifdef UV2 #if defined(ALPHATEST) && defined(ALPHATEST_UV2) vertexOutputs.vUV=(uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy; #else vertexOutputs.vUV=uv2Updated; #endif #ifdef BUMP_UV2 vertexOutputs.vBumpUV=(uniforms.bumpMatrix* vec4f(uv2Updated,1.0,0.0)).xy; #endif #ifdef REFLECTIVITY_UV2 vertexOutputs.vReflectivityUV=(uniforms.reflectivityMatrix* vec4f(uv2Updated,1.0,0.0)).xy; #else #ifdef METALLIC_UV2 vertexOutputs.vMetallicUV=(uniforms.metallicMatrix* vec4f(uv2Updated,1.0,0.0)).xy; #endif #ifdef ROUGHNESS_UV2 vertexOutputs.vRoughnessUV=(uniforms.roughnessMatrix* vec4f(uv2Updated,1.0,0.0)).xy; #endif #endif #ifdef ALBEDO_UV2 vertexOutputs.vAlbedoUV=(uniforms.albedoMatrix* vec4f(uv2Updated,1.0,0.0)).xy; #endif #endif #endif #include } `; if (!ShaderStore.ShadersStoreWGSL[name187]) { ShaderStore.ShadersStoreWGSL[name187] = shader187; } geometryVertexShaderWGSL = { name: name187, shader: shader187 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/geometry.fragment.js var geometry_fragment_exports = {}; __export(geometry_fragment_exports, { geometryPixelShaderWGSL: () => geometryPixelShaderWGSL }); var name188, shader188, geometryPixelShaderWGSL; var init_geometry_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/geometry.fragment.js"() { init_shaderStore(); init_clipPlaneFragmentDeclaration(); init_bumpFragmentMainFunctions(); init_bumpFragmentFunctions(); init_helperFunctions(); init_clipPlaneFragment(); init_bumpFragment(); name188 = "geometryPixelShader"; shader188 = `#ifdef BUMP varying vWorldView0: vec4f;varying vWorldView1: vec4f;varying vWorldView2: vec4f;varying vWorldView3: vec4f;varying vNormalW: vec3f; #else varying vNormalV: vec3f; #endif varying vViewPos: vec4f; #if defined(POSITION) || defined(BUMP) varying vPositionW: vec3f; #endif #if defined(VELOCITY) || defined(VELOCITY_LINEAR) varying vCurrentPosition: vec4f;varying vPreviousPosition: vec4f; #endif #ifdef NEED_UV varying vUV: vec2f; #endif #ifdef BUMP uniform vBumpInfos: vec3f;uniform vTangentSpaceParams: vec2f; #endif #if defined(REFLECTIVITY) #if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;varying vReflectivityUV: vec2f; #else #ifdef METALLIC_TEXTURE var metallicSamplerSampler: sampler;var metallicSampler: texture_2d;varying vMetallicUV: vec2f; #endif #ifdef ROUGHNESS_TEXTURE var roughnessSamplerSampler: sampler;var roughnessSampler: texture_2d;varying vRoughnessUV: vec2f; #endif #endif #ifdef ALBEDOTEXTURE varying vAlbedoUV: vec2f;var albedoSamplerSampler: sampler;var albedoSampler: texture_2d; #endif #ifdef REFLECTIVITYCOLOR uniform reflectivityColor: vec3f; #endif #ifdef ALBEDOCOLOR uniform albedoColor: vec3f; #endif #ifdef METALLIC uniform metallic: f32; #endif #if defined(ROUGHNESS) || defined(GLOSSINESS) uniform glossiness: f32; #endif #endif #if defined(ALPHATEST) && defined(NEED_UV) var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #endif #include #include #include #include @fragment fn main(input: FragmentInputs)->FragmentOutputs { #include #ifdef ALPHATEST if (textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV).a<0.4) {discard;} #endif var normalOutput: vec3f; #ifdef BUMP var normalW: vec3f=normalize(input.vNormalW); #include #ifdef NORMAL_WORLDSPACE normalOutput=normalW; #else normalOutput=normalize( (mat4x4f(input.vWorldView0,input.vWorldView1,input.vWorldView2,input.vWorldView3)* vec4f(normalW,0.0)).xyz); #endif #elif defined(HAS_NORMAL_ATTRIBUTE) normalOutput=normalize(input.vNormalV); #elif defined(POSITION) normalOutput=normalize(-cross(dpdx(input.vPositionW),dpdy(input.vPositionW))); #endif #ifdef ENCODE_NORMAL normalOutput=normalOutput*0.5+0.5; #endif var fragData: array,SCENE_MRT_COUNT>; #ifdef DEPTH fragData[DEPTH_INDEX]=vec4f(input.vViewPos.z/input.vViewPos.w,0.0,0.0,1.0); #endif #ifdef NORMAL fragData[NORMAL_INDEX]=vec4f(normalOutput,1.0); #endif #ifdef SCREENSPACE_DEPTH fragData[SCREENSPACE_DEPTH_INDEX]=vec4f(fragmentInputs.position.z,0.0,0.0,1.0); #endif #ifdef POSITION fragData[POSITION_INDEX]= vec4f(input.vPositionW,1.0); #endif #ifdef VELOCITY var a: vec2f=(input.vCurrentPosition.xy/input.vCurrentPosition.w)*0.5+0.5;var b: vec2f=(input.vPreviousPosition.xy/input.vPreviousPosition.w)*0.5+0.5;var velocity: vec2f=abs(a-b);velocity= vec2f(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;fragData[VELOCITY_INDEX]= vec4f(velocity,0.0,1.0); #endif #ifdef VELOCITY_LINEAR var velocity : vec2f=vec2f(0.5)*((input.vPreviousPosition.xy / input.vPreviousPosition.w) - (input.vCurrentPosition.xy / input.vCurrentPosition.w));fragData[VELOCITY_LINEAR_INDEX]=vec4f(velocity,0.0,1.0); #endif #ifdef REFLECTIVITY var reflectivity: vec4f= vec4f(0.0,0.0,0.0,1.0); #ifdef METALLICWORKFLOW var metal: f32=1.0;var roughness: f32=1.0; #ifdef ORMTEXTURE metal*=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV).b;roughness*=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV).g; #else #ifdef METALLIC_TEXTURE metal*=textureSample(metallicSampler,metallicSamplerSampler,input.vMetallicUV).r; #endif #ifdef ROUGHNESS_TEXTURE roughness*=textureSample(roughnessSampler,roughnessSamplerSampler,input.vRoughnessUV).r; #endif #endif #ifdef METALLIC metal*=uniforms.metallic; #endif #ifdef ROUGHNESS roughness*=(1.0-uniforms.glossiness); #endif reflectivity=vec4f(reflectivity.rgb,reflectivity.a-roughness);var color: vec3f= vec3f(1.0); #ifdef ALBEDOTEXTURE color=textureSample(albedoSampler,albedoSamplerSampler,input.vAlbedoUV).rgb; #ifdef GAMMAALBEDO color=toLinearSpaceVec4(color); #endif #endif #ifdef ALBEDOCOLOR color*=uniforms.albedoColor.xyz; #endif reflectivity=vec4f(mix( vec3f(0.04),color,metal),reflectivity.a); #else #if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) reflectivity=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vReflectivityUV); #ifdef GAMMAREFLECTIVITYTEXTURE reflectivity=vec4f(toLinearSpaceVec3(reflectivity.rgb),reflectivity.a); #endif #else #ifdef REFLECTIVITYCOLOR reflectivity=vec4f(toLinearSpaceVec3(uniforms.reflectivityColor.xyz),1.0); #endif #endif #ifdef GLOSSINESSS reflectivity=vec4f(reflectivity.rgb,reflectivity.a*glossiness); #endif #endif fragData[REFLECTIVITY_INDEX]=reflectivity; #endif #if SCENE_MRT_COUNT>0 fragmentOutputs.fragData0=fragData[0]; #endif #if SCENE_MRT_COUNT>1 fragmentOutputs.fragData1=fragData[1]; #endif #if SCENE_MRT_COUNT>2 fragmentOutputs.fragData2=fragData[2]; #endif #if SCENE_MRT_COUNT>3 fragmentOutputs.fragData3=fragData[3]; #endif #if SCENE_MRT_COUNT>4 fragmentOutputs.fragData4=fragData[4]; #endif #if SCENE_MRT_COUNT>5 fragmentOutputs.fragData5=fragData[5]; #endif #if SCENE_MRT_COUNT>6 fragmentOutputs.fragData6=fragData[6]; #endif #if SCENE_MRT_COUNT>7 fragmentOutputs.fragData7=fragData[7]; #endif } `; if (!ShaderStore.ShadersStoreWGSL[name188]) { ShaderStore.ShadersStoreWGSL[name188] = shader188; } geometryPixelShaderWGSL = { name: name188, shader: shader188 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/geometryVertexDeclaration.js var name189, shader189, geometryVertexDeclaration; var init_geometryVertexDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/geometryVertexDeclaration.js"() { init_shaderStore(); name189 = "geometryVertexDeclaration"; shader189 = `uniform mat4 viewProjection;uniform mat4 view;`; if (!ShaderStore.IncludesShadersStore[name189]) { ShaderStore.IncludesShadersStore[name189] = shader189; } geometryVertexDeclaration = { name: name189, shader: shader189 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/geometryUboDeclaration.js var name190, shader190, geometryUboDeclaration; var init_geometryUboDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/geometryUboDeclaration.js"() { init_shaderStore(); init_sceneUboDeclaration2(); name190 = "geometryUboDeclaration"; shader190 = `#include `; if (!ShaderStore.IncludesShadersStore[name190]) { ShaderStore.IncludesShadersStore[name190] = shader190; } geometryUboDeclaration = { name: name190, shader: shader190 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/geometry.vertex.js var geometry_vertex_exports2 = {}; __export(geometry_vertex_exports2, { geometryVertexShader: () => geometryVertexShader }); var name191, shader191, geometryVertexShader; var init_geometry_vertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/geometry.vertex.js"() { init_shaderStore(); init_bonesDeclaration2(); init_bakedVertexAnimationDeclaration2(); init_morphTargetsVertexGlobalDeclaration2(); init_morphTargetsVertexDeclaration2(); init_instancesDeclaration2(); init_geometryVertexDeclaration(); init_geometryUboDeclaration(); init_clipPlaneVertexDeclaration2(); init_morphTargetsVertexGlobal2(); init_morphTargetsVertex2(); init_instancesVertex2(); init_bonesVertex2(); init_bakedVertexAnimation2(); init_clipPlaneVertex2(); init_bumpVertex2(); name191 = "geometryVertexShader"; shader191 = `precision highp float; #include #include #include #include[0..maxSimultaneousMorphTargets] #include #include<__decl__geometryVertex> #include attribute vec3 position; #ifdef HAS_NORMAL_ATTRIBUTE attribute vec3 normal; #endif #ifdef NEED_UV varying vec2 vUV; #ifdef ALPHATEST uniform mat4 diffuseMatrix; #endif #ifdef BUMP uniform mat4 bumpMatrix;varying vec2 vBumpUV; #endif #ifdef REFLECTIVITY uniform mat4 reflectivityMatrix;uniform mat4 albedoMatrix;varying vec2 vReflectivityUV;varying vec2 vAlbedoUV; #endif #ifdef METALLIC_TEXTURE varying vec2 vMetallicUV;uniform mat4 metallicMatrix; #endif #ifdef ROUGHNESS_TEXTURE varying vec2 vRoughnessUV;uniform mat4 roughnessMatrix; #endif #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #endif #ifdef BUMP varying mat4 vWorldView; #endif #ifdef BUMP varying vec3 vNormalW; #else varying vec3 vNormalV; #endif varying vec4 vViewPos; #if defined(POSITION) || defined(BUMP) varying vec3 vPositionW; #endif #if defined(VELOCITY) || defined(VELOCITY_LINEAR) uniform mat4 previousViewProjection;varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; #endif #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position; #ifdef HAS_NORMAL_ATTRIBUTE vec3 normalUpdated=normal; #else vec3 normalUpdated=vec3(0.0,0.0,0.0); #endif #ifdef UV1 vec2 uvUpdated=uv; #endif #ifdef UV2 vec2 uv2Updated=uv2; #endif #include #include[0..maxSimultaneousMorphTargets] #include #if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && !defined(BONES_VELOCITY_ENABLED) vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #include #include vec4 worldPos=vec4(finalWorld*vec4(positionUpdated,1.0)); #ifdef BUMP vWorldView=view*finalWorld;mat3 normalWorld=mat3(finalWorld);vNormalW=normalize(normalWorld*normalUpdated); #else #ifdef NORMAL_WORLDSPACE vNormalV=normalize(vec3(finalWorld*vec4(normalUpdated,0.0))); #else vNormalV=normalize(vec3((view*finalWorld)*vec4(normalUpdated,0.0))); #endif #endif vViewPos=view*worldPos; #if (defined(VELOCITY) || defined(VELOCITY_LINEAR)) && defined(BONES_VELOCITY_ENABLED) vCurrentPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0); #if NUM_BONE_INFLUENCERS>0 mat4 previousInfluence;previousInfluence=mPreviousBones[int(matricesIndices[0])]*matricesWeights[0]; #if NUM_BONE_INFLUENCERS>1 previousInfluence+=mPreviousBones[int(matricesIndices[1])]*matricesWeights[1]; #endif #if NUM_BONE_INFLUENCERS>2 previousInfluence+=mPreviousBones[int(matricesIndices[2])]*matricesWeights[2]; #endif #if NUM_BONE_INFLUENCERS>3 previousInfluence+=mPreviousBones[int(matricesIndices[3])]*matricesWeights[3]; #endif #if NUM_BONE_INFLUENCERS>4 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0]; #endif #if NUM_BONE_INFLUENCERS>5 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1]; #endif #if NUM_BONE_INFLUENCERS>6 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2]; #endif #if NUM_BONE_INFLUENCERS>7 previousInfluence+=mPreviousBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3]; #endif vPreviousPosition=previousViewProjection*finalPreviousWorld*previousInfluence*vec4(positionUpdated,1.0); #else vPreviousPosition=previousViewProjection*finalPreviousWorld*vec4(positionUpdated,1.0); #endif #endif #if defined(POSITION) || defined(BUMP) vPositionW=worldPos.xyz/worldPos.w; #endif gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); #include #ifdef NEED_UV #ifdef UV1 #if defined(ALPHATEST) && defined(ALPHATEST_UV1) vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #else vUV=uvUpdated; #endif #ifdef BUMP_UV1 vBumpUV=vec2(bumpMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef REFLECTIVITY_UV1 vReflectivityUV=vec2(reflectivityMatrix*vec4(uvUpdated,1.0,0.0)); #else #ifdef METALLIC_UV1 vMetallicUV=vec2(metallicMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef ROUGHNESS_UV1 vRoughnessUV=vec2(roughnessMatrix*vec4(uvUpdated,1.0,0.0)); #endif #endif #ifdef ALBEDO_UV1 vAlbedoUV=vec2(albedoMatrix*vec4(uvUpdated,1.0,0.0)); #endif #endif #ifdef UV2 #if defined(ALPHATEST) && defined(ALPHATEST_UV2) vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0)); #else vUV=uv2Updated; #endif #ifdef BUMP_UV2 vBumpUV=vec2(bumpMatrix*vec4(uv2Updated,1.0,0.0)); #endif #ifdef REFLECTIVITY_UV2 vReflectivityUV=vec2(reflectivityMatrix*vec4(uv2Updated,1.0,0.0)); #else #ifdef METALLIC_UV2 vMetallicUV=vec2(metallicMatrix*vec4(uv2Updated,1.0,0.0)); #endif #ifdef ROUGHNESS_UV2 vRoughnessUV=vec2(roughnessMatrix*vec4(uv2Updated,1.0,0.0)); #endif #endif #ifdef ALBEDO_UV2 vAlbedoUV=vec2(albedoMatrix*vec4(uv2Updated,1.0,0.0)); #endif #endif #endif #include } `; if (!ShaderStore.ShadersStore[name191]) { ShaderStore.ShadersStore[name191] = shader191; } geometryVertexShader = { name: name191, shader: shader191 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/mrtFragmentDeclaration.js var name192, shader192, mrtFragmentDeclaration; var init_mrtFragmentDeclaration = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/mrtFragmentDeclaration.js"() { init_shaderStore(); name192 = "mrtFragmentDeclaration"; shader192 = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) layout(location=0) out vec4 glFragData[{X}]; #endif `; if (!ShaderStore.IncludesShadersStore[name192]) { ShaderStore.IncludesShadersStore[name192] = shader192; } mrtFragmentDeclaration = { name: name192, shader: shader192 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/geometry.fragment.js var geometry_fragment_exports2 = {}; __export(geometry_fragment_exports2, { geometryPixelShader: () => geometryPixelShader }); var name193, shader193, geometryPixelShader; var init_geometry_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/geometry.fragment.js"() { init_shaderStore(); init_clipPlaneFragmentDeclaration2(); init_mrtFragmentDeclaration(); init_bumpFragmentMainFunctions2(); init_bumpFragmentFunctions2(); init_helperFunctions2(); init_clipPlaneFragment2(); init_bumpFragment2(); name193 = "geometryPixelShader"; shader193 = `#extension GL_EXT_draw_buffers : require #if defined(BUMP) || !defined(NORMAL) #extension GL_OES_standard_derivatives : enable #endif precision highp float; #ifdef BUMP varying mat4 vWorldView;varying vec3 vNormalW; #else varying vec3 vNormalV; #endif varying vec4 vViewPos; #if defined(POSITION) || defined(BUMP) varying vec3 vPositionW; #endif #if defined(VELOCITY) || defined(VELOCITY_LINEAR) varying vec4 vCurrentPosition;varying vec4 vPreviousPosition; #endif #ifdef NEED_UV varying vec2 vUV; #endif #ifdef BUMP uniform vec3 vBumpInfos;uniform vec2 vTangentSpaceParams; #endif #if defined(REFLECTIVITY) #if defined(ORMTEXTURE) || defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) uniform sampler2D reflectivitySampler;varying vec2 vReflectivityUV; #else #ifdef METALLIC_TEXTURE uniform sampler2D metallicSampler;varying vec2 vMetallicUV; #endif #ifdef ROUGHNESS_TEXTURE uniform sampler2D roughnessSampler;varying vec2 vRoughnessUV; #endif #endif #ifdef ALBEDOTEXTURE varying vec2 vAlbedoUV;uniform sampler2D albedoSampler; #endif #ifdef REFLECTIVITYCOLOR uniform vec3 reflectivityColor; #endif #ifdef ALBEDOCOLOR uniform vec3 albedoColor; #endif #ifdef METALLIC uniform float metallic; #endif #if defined(ROUGHNESS) || defined(GLOSSINESS) uniform float glossiness; #endif #endif #if defined(ALPHATEST) && defined(NEED_UV) uniform sampler2D diffuseSampler; #endif #include #include[SCENE_MRT_COUNT] #include #include #include void main() { #include #ifdef ALPHATEST if (texture2D(diffuseSampler,vUV).a<0.4) discard; #endif vec3 normalOutput; #ifdef BUMP vec3 normalW=normalize(vNormalW); #include #ifdef NORMAL_WORLDSPACE normalOutput=normalW; #else normalOutput=normalize(vec3(vWorldView*vec4(normalW,0.0))); #endif #elif defined(HAS_NORMAL_ATTRIBUTE) normalOutput=normalize(vNormalV); #elif defined(POSITION) normalOutput=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW))); #endif #ifdef ENCODE_NORMAL normalOutput=normalOutput*0.5+0.5; #endif #ifdef DEPTH gl_FragData[DEPTH_INDEX]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0); #endif #ifdef NORMAL gl_FragData[NORMAL_INDEX]=vec4(normalOutput,1.0); #endif #ifdef SCREENSPACE_DEPTH gl_FragData[SCREENSPACE_DEPTH_INDEX]=vec4(gl_FragCoord.z,0.0,0.0,1.0); #endif #ifdef POSITION gl_FragData[POSITION_INDEX]=vec4(vPositionW,1.0); #endif #ifdef VELOCITY vec2 a=(vCurrentPosition.xy/vCurrentPosition.w)*0.5+0.5;vec2 b=(vPreviousPosition.xy/vPreviousPosition.w)*0.5+0.5;vec2 velocity=abs(a-b);velocity=vec2(pow(velocity.x,1.0/3.0),pow(velocity.y,1.0/3.0))*sign(a-b)*0.5+0.5;gl_FragData[VELOCITY_INDEX]=vec4(velocity,0.0,1.0); #endif #ifdef VELOCITY_LINEAR vec2 velocity=vec2(0.5)*((vPreviousPosition.xy/vPreviousPosition.w) - (vCurrentPosition.xy/vCurrentPosition.w));gl_FragData[VELOCITY_LINEAR_INDEX]=vec4(velocity,0.0,1.0); #endif #ifdef REFLECTIVITY vec4 reflectivity=vec4(0.0,0.0,0.0,1.0); #ifdef METALLICWORKFLOW float metal=1.0;float roughness=1.0; #ifdef ORMTEXTURE metal*=texture2D(reflectivitySampler,vReflectivityUV).b;roughness*=texture2D(reflectivitySampler,vReflectivityUV).g; #else #ifdef METALLIC_TEXTURE metal*=texture2D(metallicSampler,vMetallicUV).r; #endif #ifdef ROUGHNESS_TEXTURE roughness*=texture2D(roughnessSampler,vRoughnessUV).r; #endif #endif #ifdef METALLIC metal*=metallic; #endif #ifdef ROUGHNESS roughness*=(1.0-glossiness); #endif reflectivity.a-=roughness;vec3 color=vec3(1.0); #ifdef ALBEDOTEXTURE color=texture2D(albedoSampler,vAlbedoUV).rgb; #ifdef GAMMAALBEDO color=toLinearSpace(color); #endif #endif #ifdef ALBEDOCOLOR color*=albedoColor.xyz; #endif reflectivity.rgb=mix(vec3(0.04),color,metal); #else #if defined(SPECULARGLOSSINESSTEXTURE) || defined(REFLECTIVITYTEXTURE) reflectivity=texture2D(reflectivitySampler,vReflectivityUV); #ifdef GAMMAREFLECTIVITYTEXTURE reflectivity.rgb=toLinearSpace(reflectivity.rgb); #endif #else #ifdef REFLECTIVITYCOLOR reflectivity.rgb=toLinearSpace(reflectivityColor.xyz);reflectivity.a=1.0; #endif #endif #ifdef GLOSSINESSS reflectivity.a*=glossiness; #endif #endif gl_FragData[REFLECTIVITY_INDEX]=reflectivity; #endif } `; if (!ShaderStore.ShadersStore[name193]) { ShaderStore.ShadersStore[name193] = shader193; } geometryPixelShader = { name: name193, shader: shader193 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBRDFFunctions.js var name194, shader194, pbrBRDFFunctionsWGSL; var init_pbrBRDFFunctions = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/pbrBRDFFunctions.js"() { init_shaderStore(); name194 = "pbrBRDFFunctions"; shader194 = `#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 #define BRDF_DIFFUSE_MODEL_EON 0 #define BRDF_DIFFUSE_MODEL_BURLEY 1 #define BRDF_DIFFUSE_MODEL_LAMBERT 2 #define BRDF_DIFFUSE_MODEL_LEGACY 3 #define DIELECTRIC_SPECULAR_MODEL_GLTF 0 #define DIELECTRIC_SPECULAR_MODEL_OPENPBR 1 #define CONDUCTOR_SPECULAR_MODEL_GLTF 0 #define CONDUCTOR_SPECULAR_MODEL_OPENPBR 1 #if !defined(PBR_VERTEX_SHADER) && !defined(OPENPBR_VERTEX_SHADER) #ifdef MS_BRDF_ENERGY_CONSERVATION fn getEnergyConservationFactor(specularEnvironmentR0: vec3f,environmentBrdf: vec3f)->vec3f {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} #endif #if CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR fn getF82Specular(NdotV: f32,F0: vec3f,edgeTint: vec3f,roughness: f32)->vec3f {const cos_theta_max: f32=0.142857143; const one_minus_cos_theta_max_to_the_fifth: f32=0.462664366; const one_minus_cos_theta_max_to_the_sixth: f32=0.396569457; let white_minus_F0: vec3f=vec3f(1.0f)-F0;let b_numerator: vec3f=(F0+white_minus_F0*one_minus_cos_theta_max_to_the_fifth)*(vec3f(1.0)-edgeTint);const b_denominator: f32=cos_theta_max*one_minus_cos_theta_max_to_the_sixth;const b_denominator_reciprocal: f32=1.0f/b_denominator;let b: vec3f=b_numerator*b_denominator_reciprocal; let cos_theta: f32=max(roughness,NdotV);let one_minus_cos_theta: f32=1.0-cos_theta;let offset_from_F0: vec3f=(white_minus_F0-b*cos_theta*one_minus_cos_theta)*pow(one_minus_cos_theta,5.0f);return clamp(F0+offset_from_F0,vec3f(0.0f),vec3f(1.0f));} #endif #ifdef FUZZENVIRONMENTBRDF fn getFuzzBRDFLookup(NdotV: f32,perceptualRoughness: f32)->vec3f {let UV: vec2f=vec2f(perceptualRoughness,NdotV);var brdfLookup: vec4f=textureSample(environmentFuzzBrdfSampler,environmentFuzzBrdfSamplerSampler,UV);const RiRange: vec2f=vec2f(0.0f,0.75f);const ARange: vec2f=vec2f(0.005f,0.88f);const BRange: vec2f=vec2f(-0.18f,0.002f);brdfLookup.r=mix(ARange.x, ARange.y, brdfLookup.r);brdfLookup.g=mix(BRange.x, BRange.y, brdfLookup.g);brdfLookup.b=mix(RiRange.x,RiRange.y,brdfLookup.b);return brdfLookup.rgb;} #endif #ifdef ENVIRONMENTBRDF fn getBRDFLookup(NdotV: f32,perceptualRoughness: f32)->vec3f {var UV: vec2f= vec2f(NdotV,perceptualRoughness);var brdfLookup: vec4f= textureSample(environmentBrdfSampler,environmentBrdfSamplerSampler,UV); #ifdef ENVIRONMENTBRDF_RGBD brdfLookup=vec4f(fromRGBD(brdfLookup.rgba),brdfLookup.a); #endif return brdfLookup.rgb;} fn getReflectanceFromBRDFWithEnvLookup(specularEnvironmentR0: vec3f,specularEnvironmentR90: vec3f,environmentBrdf: vec3f)->vec3f { #ifdef BRDF_V_HEIGHT_CORRELATED var reflectance: vec3f=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; #else var reflectance: vec3f=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; #endif return reflectance;} fn getReflectanceFromBRDFLookup(specularEnvironmentR0: vec3f,environmentBrdf: vec3f)->vec3f { #ifdef BRDF_V_HEIGHT_CORRELATED var reflectance: vec3f=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); #else var reflectance: vec3f=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; #endif return reflectance;} #endif /* NOT USED #if defined(SHEEN) && defined(SHEEN_SOFTER) fn getBRDFLookupCharlieSheen(NdotV: f32,perceptualRoughness: f32)->f32 {var c: f32=1.0-NdotV;var c3: f32=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));} #endif */ #if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL) fn getReflectanceFromAnalyticalBRDFLookup_Jones(VdotN: f32,reflectance0: vec3f,reflectance90: vec3f,smoothness: f32)->vec3f {var weight: f32=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} #endif #if defined(SHEEN) && defined(ENVIRONMENTBRDF) /** * The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture. * The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table */ fn getSheenReflectanceFromBRDFLookup(reflectance0: vec3f,environmentBrdf: vec3f)->vec3f {var sheenEnvironmentReflectance: vec3f=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} #endif fn fresnelSchlickGGXVec3(VdotH: f32,reflectance0: vec3f,reflectance90: vec3f)->vec3f {return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} fn fresnelSchlickGGX(VdotH: f32,reflectance0: f32,reflectance90: f32)->f32 {return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} #ifdef CLEARCOAT fn getR0RemappedForClearCoat(f0: vec3f)->vec3f { #ifdef CLEARCOAT_DEFAULTIOR #ifdef MOBILE return saturateVec3(f0*(f0*0.526868+0.529324)-0.0482256); #else return saturateVec3(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); #endif #else var s: vec3f=sqrt(f0);var t: vec3f=(uniforms.vClearCoatRefractionParams.z+uniforms.vClearCoatRefractionParams.w*s)/(uniforms.vClearCoatRefractionParams.w+uniforms.vClearCoatRefractionParams.z*s);return squareVec3(t); #endif } #endif #ifdef IRIDESCENCE const XYZ_TO_REC709: mat3x3f= mat3x3f( 3.2404542,-0.9692660, 0.0556434, -1.5371385, 1.8760108,-0.2040259, -0.4985314, 0.0415560, 1.0572252 );fn getIORTfromAirToSurfaceR0(f0: vec3f)->vec3f {var sqrtF0: vec3f=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} fn getR0fromIORsVec3(iorT: vec3f,iorI: f32)->vec3f {return squareVec3((iorT- vec3f(iorI))/(iorT+ vec3f(iorI)));} fn getR0fromIORs(iorT: f32,iorI: f32)->f32 {return square((iorT-iorI)/(iorT+iorI));} fn evalSensitivity(opd: f32,shift: vec3f)->vec3f {var phase: f32=2.0*PI*opd*1.0e-9;const val: vec3f= vec3f(5.4856e-13,4.4201e-13,5.2481e-13);const pos: vec3f= vec3f(1.6810e+06,1.7953e+06,2.2084e+06);const vr: vec3f= vec3f(4.3278e+09,9.3046e+09,6.6121e+09);var xyz: vec3f=val*sqrt(2.0*PI*vr)*cos(pos*phase+shift)*exp(-square(phase)*vr);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;var srgb: vec3f=XYZ_TO_REC709*xyz;return srgb;} fn evalIridescence(outsideIOR: f32,eta2: f32,cosTheta1: f32,thinFilmThickness: f32,baseF0: vec3f)->vec3f {var I: vec3f= vec3f(1.0);var iridescenceIOR: f32=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));var sinTheta2Sq: f32=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));var cosTheta2Sq: f32=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} var cosTheta2: f32=sqrt(cosTheta2Sq);var R0: f32=getR0fromIORs(iridescenceIOR,outsideIOR);var R12: f32=fresnelSchlickGGX(cosTheta1,R0,1.);var R21: f32=R12;var T121: f32=1.0-R12;var phi12: f32=0.0;if (iridescenceIORf32 {var a2: f32=alphaG*alphaG;var d: f32=NdotH*NdotH*(a2-1.0)+1.0;return a2/(PI*d*d);} #ifdef SHEEN fn normalDistributionFunction_CharlieSheen(NdotH: f32,alphaG: f32)->f32 {var invR: f32=1./alphaG;var cos2h: f32=NdotH*NdotH;var sin2h: f32=1.-cos2h;return (2.+invR)*pow(sin2h,invR*.5)/(2.*PI);} #endif #ifdef ANISOTROPIC fn normalDistributionFunction_BurleyGGX_Anisotropic(NdotH: f32,TdotH: f32,BdotH: f32,alphaTB: vec2f)->f32 {var a2: f32=alphaTB.x*alphaTB.y;var v: vec3f= vec3f(alphaTB.y*TdotH,alphaTB.x *BdotH,a2*NdotH);var v2: f32=dot(v,v);var w2: f32=a2/v2;return a2*w2*w2*RECIPROCAL_PI;} #endif #ifdef BRDF_V_HEIGHT_CORRELATED fn smithVisibility_GGXCorrelated(NdotL: f32,NdotV: f32,alphaG: f32)->f32 { #ifdef MOBILE var GGXV: f32=NdotL*(NdotV*(1.0-alphaG)+alphaG);var GGXL: f32=NdotV*(NdotL*(1.0-alphaG)+alphaG);return 0.5/(GGXV+GGXL); #else var a2: f32=alphaG*alphaG;var GGXV: f32=NdotL*sqrt(NdotV*(NdotV-a2*NdotV)+a2);var GGXL: f32=NdotV*sqrt(NdotL*(NdotL-a2*NdotL)+a2);return 0.5/(GGXV+GGXL); #endif } #else fn smithVisibilityG1_TrowbridgeReitzGGXFast(dot: f32,alphaG: f32)->f32 { #ifdef MOBILE return 1.0/(dot+alphaG+(1.0-alphaG)*dot )); #else var alphaSquared: f32=alphaG*alphaG;return 1.0/(dot+sqrt(alphaSquared+(1.0-alphaSquared)*dot*dot)); #endif } fn smithVisibility_TrowbridgeReitzGGXFast(NdotL: f32,NdotV: f32,alphaG: f32)->f32 {var visibility: f32=smithVisibilityG1_TrowbridgeReitzGGXFast(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGXFast(NdotV,alphaG);return visibility;} #endif #ifdef ANISOTROPIC fn smithVisibility_GGXCorrelated_Anisotropic(NdotL: f32,NdotV: f32,TdotV: f32,BdotV: f32,TdotL: f32,BdotL: f32,alphaTB: vec2f)->f32 {var lambdaV: f32=NdotL*length( vec3f(alphaTB.x*TdotV,alphaTB.y*BdotV,NdotV));var lambdaL: f32=NdotV*length( vec3f(alphaTB.x*TdotL,alphaTB.y*BdotL,NdotL));var v: f32=0.5/(lambdaV+lambdaL);return v;} #endif #ifdef CLEARCOAT fn visibility_Kelemen(VdotH: f32)->f32 {return 0.25/(VdotH*VdotH); } #endif #ifdef SHEEN fn visibility_Ashikhmin(NdotL: f32,NdotV: f32)->f32 {return 1./(4.*(NdotL+NdotV-NdotL*NdotV));} /* NOT USED #ifdef SHEEN_SOFTER fn l(x: f32,alphaG: f32)->f32 {var oneMinusAlphaSq: f32=(1.0-alphaG)*(1.0-alphaG);var a: f32=mix(21.5473,25.3245,oneMinusAlphaSq);var b: f32=mix(3.82987,3.32435,oneMinusAlphaSq);var c: f32=mix(0.19823,0.16801,oneMinusAlphaSq);var d: f32=mix(-1.97760,-1.27393,oneMinusAlphaSq);var e: f32=mix(-4.32054,-4.85967,oneMinusAlphaSq);return a/(1.0+b*pow(x,c))+d*x+e;} fn lambdaSheen(cosTheta: f32,alphaG: f32)->f32 {return abs(cosTheta)<0.5 ? exp(l(cosTheta,alphaG)) : exp(2.0*l(0.5,alphaG)-l(1.0-cosTheta,alphaG));} fn visibility_CharlieSheen(NdotL: f32,NdotV: f32,alphaG: f32)->f32 {var G: f32=1.0/(1.0+lambdaSheen(NdotV,alphaG)+lambdaSheen(NdotL,alphaG));return G/(4.0*NdotV*NdotL);} #endif */ #endif const constant1_FON: f32=0.5f-2.0f/(3.0f*PI);const constant2_FON: f32=2.0f/3.0f-28.0f/(15.0f*PI);fn E_FON_approx(mu: f32,roughness: f32)->f32 {var sigma: f32=roughness; var mucomp: f32=1.0f-mu;var mucomp2: f32=mucomp*mucomp;const Gcoeffs: mat2x2f=mat2x2f(0.0571085289f,-0.332181442f, 0.491881867f,0.0714429953f);var GoverPi: f32=dot(Gcoeffs*vec2f(mucomp,mucomp2),vec2f(1.0f,mucomp2));return (1.0f+sigma*GoverPi)/(1.0f+constant1_FON*sigma);} fn diffuseBRDF_EON(albedo: vec3f,roughness: f32,NdotL: f32,NdotV: f32,LdotV: f32)->vec3f {var rho: vec3f=albedo;var sigma: f32=roughness; var mu_i: f32=NdotL; var mu_o: f32=NdotV; var s: f32=LdotV-mu_i*mu_o; var sovertF: f32=select(s,s/max(mu_i,mu_o),s>0.0f); var AF: f32=1.0f/(1.0f+constant1_FON*sigma); var f_ss: vec3f=(rho*RECIPROCAL_PI)*AF*(1.0f+sigma*sovertF); var EFo: f32=E_FON_approx(mu_o,sigma); var EFi: f32=E_FON_approx(mu_i,sigma); var avgEF: f32=AF*(1.0f+constant2_FON*sigma); var rho_ms: vec3f=(rho*rho)*avgEF/(vec3f(1.0f)-rho*(1.0f-avgEF));const eps: f32=1.0e-7f;var f_ms: vec3f=(rho_ms*RECIPROCAL_PI)*max(eps,1.0f-EFo) * max(eps,1.0f-EFi) / max(eps,1.0f-avgEF);return (f_ss+f_ms);} fn diffuseBRDF_Burley(NdotL: f32,NdotV: f32,VdotH: f32,roughness: f32)->f32 {var diffuseFresnelNV: f32=pow5(saturateEps(1.0-NdotL));var diffuseFresnelNL: f32=pow5(saturateEps(1.0-NdotV));var diffuseFresnel90: f32=0.5+2.0*VdotH*VdotH*roughness;var fresnel: f32 = (1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) * (1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);return fresnel/PI;} #ifdef SS_TRANSLUCENCY fn transmittanceBRDF_Burley(tintColor: vec3f,diffusionDistance: vec3f,thickness: f32)->vec3f {var S: vec3f=1./maxEpsVec3(diffusionDistance);var temp: vec3f=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);} fn computeWrappedDiffuseNdotL(NdotL: f32,w: f32)->f32 {var t: f32=1.0+w;var invt2: f32=1.0/(t*t);return saturate((NdotL+w)*invt2);} #endif #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name194]) { ShaderStore.IncludesShadersStoreWGSL[name194] = shader194; } pbrBRDFFunctionsWGSL = { name: name194, shader: shader194 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/screenSpaceRayTrace.js var name195, shader195, screenSpaceRayTraceWGSL; var init_screenSpaceRayTrace = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/screenSpaceRayTrace.js"() { init_shaderStore(); name195 = "screenSpaceRayTrace"; shader195 = `fn distanceSquared(a: vec2f,b: vec2f)->f32 { var temp=a-b; return dot(temp,temp); } #ifdef SSRAYTRACE_SCREENSPACE_DEPTH fn linearizeDepth(depth: f32,near: f32,far: f32)->f32 { #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE return -(near*far)/(far-depth*(far-near)); #else return (near*far)/(far-depth*(far-near)); #endif } #endif /** param csOrigin Camera-space ray origin,which must be within the view volume and must have z>0.01 and project within the valid screen rectangle param csDirection Unit length camera-space ray direction param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates (**not** [-1,+1] normalized device coordinates). param csZBuffer The camera-space Z buffer param csZBufferSize Dimensions of csZBuffer param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value for clipping rays headed towards the camera. Should be the actual near plane if screen-space depth is enabled. param farPlaneZ The far plane for the camera. Used when screen-space depth is enabled. param stride Step in horizontal or vertical pixels between samples. This is a var because: f32 integer math is slow on GPUs,but should be set to an integer>=1 param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units to conceal banding artifacts,plus the stride ray offset. param maxSteps Maximum number of iterations. Higher gives better images but may be slow param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss param selfCollisionNumSkip Number of steps to skip at start when raytracing to avar self: voidnull collisions. 1 is a reasonable value,depending on the scene you may need to set this value to 2 param hitPixel Pixel coordinates of the first intersection with the scene param numIterations number of iterations performed param csHitPovar Camera: i32 space location of the ray hit */ fn traceScreenSpaceRay1( csOrigin: vec3f, csDirection: vec3f, projectToPixelMatrix: mat4x4f, csZBuffer: texture_2d, csZBufferSize: vec2f, #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER csZBackBuffer: texture_2d, csZBackSizeFactor: f32, #endif csZThickness: f32, nearPlaneZ: f32, farPlaneZ: f32, stride: f32, jitterFraction: f32, maxSteps: f32, maxRayTraceDistance: f32, selfCollisionNumSkip: f32, startPixel: ptr, hitPixel: ptr, csHitPoint: ptr, numIterations: ptr #ifdef SSRAYTRACE_DEBUG ,debugColor: ptr #endif )->bool { #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE var rayLength: f32=select(maxRayTraceDistance,(-nearPlaneZ-csOrigin.z)/csDirection.z,(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ); #else var rayLength: f32=select(maxRayTraceDistance,(nearPlaneZ-csOrigin.z)/csDirection.z,(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax)))/(P1.y-P0.y);} if ((P1.x>xMax) || (P1.xxMax)))/(P1.x-P0.x));} P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); #endif P1+= vec2f(select(0.0,0.01,distanceSquared(P0,P1)<0.0001));var delta: vec2f=P1-P0;var permute: bool=false;if (abs(delta.x)rayZMax) { var t: f32=rayZMin; rayZMin=rayZMax; rayZMax=t;} sceneZMax=textureLoad(csZBuffer,vec2(*hitPixel),0).r; #ifdef SSRAYTRACE_SCREENSPACE_DEPTH sceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ); #endif if (sceneZMax==0.0) { sceneZMax=1e8; } #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER var sceneBackZ: f32=textureLoad(csZBackBuffer,vec2(*hitPixel/csZBackSizeFactor),0).r; #ifdef SSRAYTRACE_SCREENSPACE_DEPTH sceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ); #endif if (sceneBackZ==0.0) { sceneBackZ=-1e8; } hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); #else hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); #endif #else #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER var sceneBackZ: f32=textureLoad(csZBackBuffer,vec2(*hitPixel/csZBackSizeFactor),0).r; #ifdef SSRAYTRACE_SCREENSPACE_DEPTH sceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ); #endif if (sceneBackZ==0.0) { sceneBackZ=1e8; } hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); #else hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); #endif #endif stepCount+=1.0;} pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} #ifdef SSRAYTRACE_ENABLE_REFINEMENT if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;var invStride: f32=1.0/stride;dPQK*=invStride;var refinementStepCount: f32=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || ((refinementStepCount<=stride*1.4) && (rayZMax(*hitPixel),0).r; #ifdef SSRAYTRACE_SCREENSPACE_DEPTH sceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ); #endif refinementStepCount+=1.0;} pqk-=dPQK;refinementStepCount-=1.0;stepCount+=refinementStepCount/stride;} #endif Q0=vec3f(Q0.xy+dQ.xy*stepCount,pqk.z);*csHitPoint=Q0/pqk.w;*numIterations=stepCount+1.0; #ifdef SSRAYTRACE_DEBUG if (((pqk.x+dPQK.x)*stepDirection)>end) {*debugColor= vec3f(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {*debugColor= vec3f(1,0,0);} else if (sceneZMax==0.0) {*debugColor= vec3f(1,1,0);} else {*debugColor= vec3f(0,stepCount/maxSteps,0);} #endif return hit;} /** texCoord: in the [0,1] range depth: depth in view space (range [znear,zfar]]) */ fn computeViewPosFromUVDepth(texCoord: vec2f,depth: f32,projection: mat4x4f,invProjectionMatrix: mat4x4f)->vec3f {var xy=texCoord*2.0-1.0;var z: f32; #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE #ifdef ORTHOGRAPHIC_CAMERA z=-projection[2].z*depth+projection[3].z; #else z=-projection[2].z-projection[3].z/depth; #endif #else #ifdef ORTHOGRAPHIC_CAMERA z=projection[2].z*depth+projection[3].z; #else z=projection[2].z+projection[3].z/depth; #endif #endif var w=1.0;var ndc=vec4f(xy,z,w);var eyePos: vec4f=invProjectionMatrix*ndc;var result=eyePos.xyz/eyePos.w;return result;} `; if (!ShaderStore.IncludesShadersStoreWGSL[name195]) { ShaderStore.IncludesShadersStoreWGSL[name195] = shader195; } screenSpaceRayTraceWGSL = { name: name195, shader: shader195 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/screenSpaceReflection2.fragment.js var screenSpaceReflection2_fragment_exports = {}; __export(screenSpaceReflection2_fragment_exports, { screenSpaceReflection2PixelShaderWGSL: () => screenSpaceReflection2PixelShaderWGSL }); var name196, shader196, screenSpaceReflection2PixelShaderWGSL; var init_screenSpaceReflection2_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/screenSpaceReflection2.fragment.js"() { init_shaderStore(); init_helperFunctions(); init_pbrBRDFFunctions(); init_screenSpaceRayTrace(); name196 = "screenSpaceReflection2PixelShader"; shader196 = `var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f; #ifdef SSR_SUPPORTED var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;var normalSampler: texture_2d;var depthSampler: texture_2d; #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER var backDepthSampler: texture_2d;uniform backSizeFactor: f32; #endif #ifdef SSR_USE_ENVIRONMENT_CUBE var envCubeSamplerSampler: sampler;var envCubeSampler: texture_cube; #ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC uniform vReflectionPosition: vec3f;uniform vReflectionSize: vec3f; #endif #endif uniform view: mat4x4f;uniform invView: mat4x4f;uniform projection: mat4x4f;uniform invProjectionMatrix: mat4x4f;uniform projectionPixel: mat4x4f;uniform nearPlaneZ: f32;uniform farPlaneZ: f32;uniform stepSize: f32;uniform maxSteps: f32;uniform strength: f32;uniform thickness: f32;uniform roughnessFactor: f32;uniform reflectionSpecularFalloffExponent: f32;uniform maxDistance: f32;uniform selfCollisionNumSkip: f32;uniform reflectivityThreshold: f32; #include #include #include fn hash(a: vec3f)->vec3f {var result=fract(a*0.8);result+=dot(result,result.yxz+19.19);return fract((result.xxy+result.yxx)*result.zyx);} fn computeAttenuationForIntersection(ihitPixel: vec2f,hitUV: vec2f,vsRayOrigin: vec3f,vsHitPoint: vec3f,reflectionVector: vec3f,maxRayDistance: f32,numIterations: f32)->f32 {var attenuation: f32=1.0; #ifdef SSR_ATTENUATE_SCREEN_BORDERS var dCoords: vec2f=smoothstep(vec2f(0.2),vec2f(0.6),abs( vec2f(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); #endif #ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0); #endif #ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS attenuation*=1.0-(numIterations/uniforms.maxSteps); #endif #ifdef SSR_ATTENUATE_BACKFACE_REFLECTION var reflectionNormal: vec3f=texelFetch(normalSampler,hitPixel,0).xyz;var directionBasedAttenuation: f32=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; #endif return attenuation;} #endif @fragment fn main(input: FragmentInputs)->FragmentOutputs { #ifdef SSR_SUPPORTED var colorFull: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var color: vec3f=colorFull.rgb;var reflectivity: vec4f=max(textureSampleLevel(reflectivitySampler,reflectivitySamplerSampler,input.vUV,0.0),vec4f(0.0)); #ifndef SSR_DISABLE_REFLECTIVITY_TEST if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=uniforms.reflectivityThreshold) { #ifdef SSR_USE_BLUR fragmentOutputs.color= vec4f(0.); #else fragmentOutputs.color=colorFull; #endif return fragmentOutputs;} #endif #ifdef SSR_INPUT_IS_GAMMA_SPACE color=toLinearSpaceVec3(color); #endif var texSize: vec2f= vec2f(textureDimensions(depthSampler,0));var csNormal: vec3f=textureLoad(normalSampler,vec2(input.vUV*texSize),0).xyz; #ifdef SSR_DECODE_NORMAL csNormal=csNormal*2.0-1.0; #endif #ifdef SSR_NORMAL_IS_IN_WORLDSPACE csNormal=(uniforms.view* vec4f(csNormal,0.0)).xyz; #endif var depth: f32=textureLoad(depthSampler,vec2(input.vUV*texSize),0).r; #ifdef SSRAYTRACE_SCREENSPACE_DEPTH depth=linearizeDepth(depth,uniforms.nearPlaneZ,uniforms.farPlaneZ); #endif var csPosition: vec3f=computeViewPosFromUVDepth(input.vUV,depth,uniforms.projection,uniforms.invProjectionMatrix); #ifdef ORTHOGRAPHIC_CAMERA var csViewDirection: vec3f= vec3f(0.,0.,1.); #else var csViewDirection: vec3f=normalize(csPosition); #endif var csReflectedVector: vec3f=reflect(csViewDirection,csNormal); #ifdef SSR_USE_ENVIRONMENT_CUBE var wReflectedVector: vec3f=(uniforms.invView* vec4f(csReflectedVector,0.0)).xyz; #ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC var worldPos: vec4f=uniforms.invView* vec4f(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),uniforms.vReflectionSize,uniforms.vReflectionPosition); #endif #ifdef SSR_INVERTCUBICMAP wReflectedVector.y*=-1.0; #endif #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE wReflectedVector.z*=-1.0; #endif var envColor: vec3f=textureSampleLevel(envCubeSampler,envCubeSamplerSampler,wReflectedVector,0.0).xyz; #ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE envColor=toLinearSpaceVec3(envColor); #endif #else var envColor: vec3f=color; #endif var reflectionAttenuation: f32=1.0;var rayHasHit: bool=false;var startPixel: vec2f;var hitPixel: vec2f;var hitPoint: vec3f;var numIterations: f32; #ifdef SSRAYTRACE_DEBUG var debugColor: vec3f; #endif #ifdef SSR_ATTENUATE_FACING_CAMERA reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); #endif if (reflectionAttenuation>0.0) { #ifdef SSR_USE_BLUR var jitt: vec3f= vec3f(0.); #else var roughness: f32=1.0-reflectivity.a;var jitt: vec3f=mix( vec3f(0.0),hash(csPosition)- vec3f(0.5),roughness)*uniforms.roughnessFactor; #endif var uv2: vec2f=input.vUV*texSize;var c: f32=(uv2.x+uv2.y)*0.25;var jitter: f32=((c)%(1.0)); rayHasHit=traceScreenSpaceRay1( csPosition, normalize(csReflectedVector+jitt), uniforms.projectionPixel, depthSampler, texSize, #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER backDepthSampler, uniforms.backSizeFactor, #endif uniforms.thickness, uniforms.nearPlaneZ, uniforms.farPlaneZ, uniforms.stepSize, jitter, uniforms.maxSteps, uniforms.maxDistance, uniforms.selfCollisionNumSkip, &startPixel, &hitPixel, &hitPoint, &numIterations #ifdef SSRAYTRACE_DEBUG ,&debugColor #endif );} #ifdef SSRAYTRACE_DEBUG fragmentOutputs.color= vec4f(debugColor,1.);return fragmentOutputs; #endif var F0: vec3f=reflectivity.rgb;var fresnel: vec3f=fresnelSchlickGGXVec3(max(dot(csNormal,-csViewDirection),0.0),F0, vec3f(1.));var SSR: vec3f=envColor;if (rayHasHit) {var reflectedColor: vec3f=textureLoad(textureSampler,vec2(hitPixel),0).rgb; #ifdef SSR_INPUT_IS_GAMMA_SPACE reflectedColor=toLinearSpaceVec3(reflectedColor); #endif reflectionAttenuation*=computeAttenuationForIntersection(hitPixel,hitPixel/texSize,csPosition,hitPoint,csReflectedVector,uniforms.maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} #ifndef SSR_BLEND_WITH_FRESNEL SSR*=fresnel; #endif #ifdef SSR_USE_BLUR var blur_radius: f32=0.0;var roughness: f32=1.0-reflectivity.a*(1.0-uniforms.roughnessFactor);if (roughness>0.001) {var cone_angle: f32=min(roughness,0.999)*3.14159265*0.5;var cone_len: f32=distance(startPixel,hitPixel);var op_len: f32=2.0*tan(cone_angle)*cone_len; var a: f32=op_len;var h: f32=cone_len;var a2: f32=a*a;var fh2: f32=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} fragmentOutputs.color= vec4f(SSR,blur_radius/255.0); #else #ifdef SSR_BLEND_WITH_FRESNEL var reflectionMultiplier: vec3f=clamp(pow(fresnel*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0)); #else var reflectionMultiplier: vec3f=clamp(pow(reflectivity.rgb*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0)); #endif var colorMultiplier: vec3f=1.0-reflectionMultiplier;var finalColor: vec3f=(color*colorMultiplier)+(SSR*reflectionMultiplier); #ifdef SSR_OUTPUT_IS_GAMMA_SPACE finalColor=toGammaSpaceVec3(finalColor); #endif fragmentOutputs.color= vec4f(finalColor,colorFull.a); #endif #else fragmentOutputs.color=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0); #endif } `; if (!ShaderStore.ShadersStoreWGSL[name196]) { ShaderStore.ShadersStoreWGSL[name196] = shader196; } screenSpaceReflection2PixelShaderWGSL = { name: name196, shader: shader196 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBRDFFunctions.js var name197, shader197, pbrBRDFFunctions; var init_pbrBRDFFunctions2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/pbrBRDFFunctions.js"() { init_shaderStore(); name197 = "pbrBRDFFunctions"; shader197 = `#define FRESNEL_MAXIMUM_ON_ROUGH 0.25 #define BRDF_DIFFUSE_MODEL_EON 0 #define BRDF_DIFFUSE_MODEL_BURLEY 1 #define BRDF_DIFFUSE_MODEL_LAMBERT 2 #define BRDF_DIFFUSE_MODEL_LEGACY 3 #define DIELECTRIC_SPECULAR_MODEL_GLTF 0 #define DIELECTRIC_SPECULAR_MODEL_OPENPBR 1 #define CONDUCTOR_SPECULAR_MODEL_GLTF 0 #define CONDUCTOR_SPECULAR_MODEL_OPENPBR 1 #if !defined(PBR_VERTEX_SHADER) && !defined(OPENPBR_VERTEX_SHADER) #ifdef MS_BRDF_ENERGY_CONSERVATION vec3 getEnergyConservationFactor(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) {return 1.0+specularEnvironmentR0*(1.0/environmentBrdf.y-1.0);} #endif #if CONDUCTOR_SPECULAR_MODEL==CONDUCTOR_SPECULAR_MODEL_OPENPBR vec3 getF82Specular(float NdotV,vec3 F0,vec3 edgeTint,float roughness) {const float cos_theta_max=0.142857143; const float one_minus_cos_theta_max_to_the_fifth=0.462664366; const float one_minus_cos_theta_max_to_the_sixth=0.396569457; vec3 white_minus_F0=vec3(1.0)-F0;vec3 b_numerator=(F0+white_minus_F0*one_minus_cos_theta_max_to_the_fifth)*(vec3(1.0)-edgeTint);const float b_denominator=cos_theta_max*one_minus_cos_theta_max_to_the_sixth;const float b_denominator_reciprocal=1.0/b_denominator;vec3 b=b_numerator*b_denominator_reciprocal; float cos_theta=max(roughness,NdotV);float one_minus_cos_theta=1.0-cos_theta;vec3 offset_from_F0=(white_minus_F0-b*cos_theta*one_minus_cos_theta)*pow(one_minus_cos_theta,5.0);return clamp(F0+offset_from_F0,0.0,1.0);} #endif #ifdef FUZZENVIRONMENTBRDF vec3 getFuzzBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(perceptualRoughness,NdotV);vec4 brdfLookup=texture(environmentFuzzBrdfSampler,UV);const vec2 RiRange=vec2(0.0,0.75);const vec2 ARange =vec2(0.005,0.88);const vec2 BRange =vec2(-0.18,0.002);brdfLookup.r=mix(ARange.x, ARange.y, brdfLookup.r);brdfLookup.g=mix(BRange.x, BRange.y, brdfLookup.g);brdfLookup.b=mix(RiRange.x,RiRange.y,brdfLookup.b);return brdfLookup.rgb;} #endif #ifdef ENVIRONMENTBRDF vec3 getBRDFLookup(float NdotV,float perceptualRoughness) {vec2 UV=vec2(NdotV,perceptualRoughness);vec4 brdfLookup=texture2D(environmentBrdfSampler,UV); #ifdef ENVIRONMENTBRDF_RGBD brdfLookup.rgb=fromRGBD(brdfLookup.rgba); #endif return brdfLookup.rgb;} vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 specularEnvironmentR90,const vec3 environmentBrdf) { #ifdef BRDF_V_HEIGHT_CORRELATED vec3 reflectance=(specularEnvironmentR90-specularEnvironmentR0)*environmentBrdf.x+specularEnvironmentR0*environmentBrdf.y; #else vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+specularEnvironmentR90*environmentBrdf.y; #endif return reflectance;} vec3 getReflectanceFromBRDFLookup(const vec3 specularEnvironmentR0,const vec3 environmentBrdf) { #ifdef BRDF_V_HEIGHT_CORRELATED vec3 reflectance=mix(environmentBrdf.xxx,environmentBrdf.yyy,specularEnvironmentR0); #else vec3 reflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y; #endif return reflectance;} #endif /* NOT USED #if defined(SHEEN) && defined(SHEEN_SOFTER) float getBRDFLookupCharlieSheen(float NdotV,float perceptualRoughness) {float c=1.0-NdotV;float c3=c*c*c;return 0.65584461*c3+1.0/(4.16526551+exp(-7.97291361*perceptualRoughness+6.33516894));} #endif */ #if !defined(ENVIRONMENTBRDF) || defined(REFLECTIONMAP_SKYBOX) || defined(ALPHAFRESNEL) vec3 getReflectanceFromAnalyticalBRDFLookup_Jones(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness) {float weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);return reflectance0+weight*(reflectance90-reflectance0)*pow5(saturate(1.0-VdotN));} #endif #if defined(SHEEN) && defined(ENVIRONMENTBRDF) /** * The sheen BRDF not containing F can be easily stored in the blue channel of the BRDF texture. * The blue channel contains DCharlie*VAshikhmin*NdotL as a lokkup table */ vec3 getSheenReflectanceFromBRDFLookup(const vec3 reflectance0,const vec3 environmentBrdf) {vec3 sheenEnvironmentReflectance=reflectance0*environmentBrdf.b;return sheenEnvironmentReflectance;} #endif vec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90) {return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} float fresnelSchlickGGX(float VdotH,float reflectance0,float reflectance90) {return reflectance0+(reflectance90-reflectance0)*pow5(1.0-VdotH);} #ifdef CLEARCOAT vec3 getR0RemappedForClearCoat(vec3 f0) { #ifdef CLEARCOAT_DEFAULTIOR #ifdef MOBILE return saturate(f0*(f0*0.526868+0.529324)-0.0482256); #else return saturate(f0*(f0*(0.941892-0.263008*f0)+0.346479)-0.0285998); #endif #else vec3 s=sqrt(f0);vec3 t=(vClearCoatRefractionParams.z+vClearCoatRefractionParams.w*s)/(vClearCoatRefractionParams.w+vClearCoatRefractionParams.z*s);return square(t); #endif } #endif #ifdef IRIDESCENCE const mat3 XYZ_TO_REC709=mat3( 3.2404542,-0.9692660, 0.0556434, -1.5371385, 1.8760108,-0.2040259, -0.4985314, 0.0415560, 1.0572252 );vec3 getIORTfromAirToSurfaceR0(vec3 f0) {vec3 sqrtF0=sqrt(f0);return (1.+sqrtF0)/(1.-sqrtF0);} vec3 getR0fromIORs(vec3 iorT,float iorI) {return square((iorT-vec3(iorI))/(iorT+vec3(iorI)));} float getR0fromIORs(float iorT,float iorI) {return square((iorT-iorI)/(iorT+iorI));} vec3 evalSensitivity(float opd,vec3 shift) {float phase=2.0*PI*opd*1.0e-9;const vec3 val=vec3(5.4856e-13,4.4201e-13,5.2481e-13);const vec3 pos=vec3(1.6810e+06,1.7953e+06,2.2084e+06);const vec3 var=vec3(4.3278e+09,9.3046e+09,6.6121e+09);vec3 xyz=val*sqrt(2.0*PI*var)*cos(pos*phase+shift)*exp(-square(phase)*var);xyz.x+=9.7470e-14*sqrt(2.0*PI*4.5282e+09)*cos(2.2399e+06*phase+shift[0])*exp(-4.5282e+09*square(phase));xyz/=1.0685e-7;vec3 srgb=XYZ_TO_REC709*xyz;return srgb;} vec3 evalIridescence(float outsideIOR,float eta2,float cosTheta1,float thinFilmThickness,vec3 baseF0) {vec3 I=vec3(1.0);float iridescenceIOR=mix(outsideIOR,eta2,smoothstep(0.0,0.03,thinFilmThickness));float sinTheta2Sq=square(outsideIOR/iridescenceIOR)*(1.0-square(cosTheta1));float cosTheta2Sq=1.0-sinTheta2Sq;if (cosTheta2Sq<0.0) {return I;} float cosTheta2=sqrt(cosTheta2Sq);float R0=getR0fromIORs(iridescenceIOR,outsideIOR);float R12=fresnelSchlickGGX(cosTheta1,R0,1.);float R21=R12;float T121=1.0-R12;float phi12=0.0;if (iridescenceIOR0.0 ? s/max(mu_i,mu_o) : s; float AF=1.0/(1.0+constant1_FON*sigma); vec3 f_ss=(rho*RECIPROCAL_PI)*AF*(1.0+sigma*sovertF); float EFo=E_FON_approx(mu_o,sigma); float EFi=E_FON_approx(mu_i,sigma); float avgEF=AF*(1.0+constant2_FON*sigma); vec3 rho_ms=(rho*rho)*avgEF/(vec3(1.0)-rho*(1.0-avgEF));const float eps=1.0e-7;vec3 f_ms=(rho_ms*RECIPROCAL_PI)*max(eps,1.0-EFo) * max(eps,1.0-EFi) / max(eps,1.0-avgEF);return (f_ss+f_ms);} #ifdef SS_TRANSLUCENCY vec3 transmittanceBRDF_Burley(const vec3 tintColor,const vec3 diffusionDistance,float thickness) {vec3 S=1./maxEps(diffusionDistance);vec3 temp=exp((-0.333333333*thickness)*S);return tintColor.rgb*0.25*(temp*temp*temp+3.0*temp);} float computeWrappedDiffuseNdotL(float NdotL,float w) {float t=1.0+w;float invt2=1.0/square(t);return saturate((NdotL+w)*invt2);} #endif #endif `; if (!ShaderStore.IncludesShadersStore[name197]) { ShaderStore.IncludesShadersStore[name197] = shader197; } pbrBRDFFunctions = { name: name197, shader: shader197 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/screenSpaceRayTrace.js var name198, shader198, screenSpaceRayTrace; var init_screenSpaceRayTrace2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/screenSpaceRayTrace.js"() { init_shaderStore(); name198 = "screenSpaceRayTrace"; shader198 = `float distanceSquared(vec2 a,vec2 b) { a-=b; return dot(a,a); } #ifdef SSRAYTRACE_SCREENSPACE_DEPTH float linearizeDepth(float depth,float near,float far) { #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE return -(near*far)/(far-depth*(far-near)); #else return (near*far)/(far-depth*(far-near)); #endif } #endif /** param csOrigin Camera-space ray origin,which must be within the view volume and must have z>0.01 and project within the valid screen rectangle param csDirection Unit length camera-space ray direction param projectToPixelMatrix A projection matrix that maps to **pixel** coordinates (**not** [-1,+1] normalized device coordinates). param csZBuffer The camera-space Z buffer param csZBufferSize Dimensions of csZBuffer param csZThickness Camera space csZThickness to ascribe to each pixel in the depth buffer param nearPlaneZ Positive number. Doesn't have to be THE actual near plane,just a reasonable value for clipping rays headed towards the camera param stride Step in horizontal or vertical pixels between samples. This is a float because integer math is slow on GPUs,but should be set to an integer>=1 param jitterFraction Number between 0 and 1 for how far to bump the ray in stride units to conceal banding artifacts,plus the stride ray offset. param maxSteps Maximum number of iterations. Higher gives better images but may be slow param maxRayTraceDistance Maximum camera-space distance to trace before returning a miss param selfCollisionNumSkip Number of steps to skip at start when raytracing to avoid self collisions. 1 is a reasonable value,depending on the scene you may need to set this value to 2 param hitPixel Pixel coordinates of the first intersection with the scene param numIterations number of iterations performed param csHitPoint Camera space location of the ray hit */ #define inline bool traceScreenSpaceRay1( vec3 csOrigin, vec3 csDirection, mat4 projectToPixelMatrix, sampler2D csZBuffer, vec2 csZBufferSize, #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER sampler2D csZBackBuffer, float csZBackSizeFactor, #endif float csZThickness, float nearPlaneZ, float farPlaneZ, float stride, float jitterFraction, float maxSteps, float maxRayTraceDistance, float selfCollisionNumSkip, out vec2 startPixel, out vec2 hitPixel, out vec3 csHitPoint, out float numIterations #ifdef SSRAYTRACE_DEBUG ,out vec3 debugColor #endif ) { #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)>-nearPlaneZ ? (-nearPlaneZ-csOrigin.z)/csDirection.z : maxRayTraceDistance; #else float rayLength=(csOrigin.z+csDirection.z*maxRayTraceDistance)yMax) || (P1.yyMax) ? yMax : yMin))/(P1.y-P0.y);} if ((P1.x>xMax) || (P1.xxMax) ? xMax : xMin))/(P1.x-P0.x));} P1=mix(P1,P0,alpha); k1=mix(k1,k0,alpha); Q1=mix(Q1,Q0,alpha); #endif P1+=vec2((distanceSquared(P0,P1)<0.0001) ? 0.01 : 0.0);vec2 delta=P1-P0;bool permute=false;if (abs(delta.x)rayZMax) { float t=rayZMin; rayZMin=rayZMax; rayZMax=t;} sceneZMax=texelFetch(csZBuffer,ivec2(hitPixel),0).r; #ifdef SSRAYTRACE_SCREENSPACE_DEPTH sceneZMax=linearizeDepth(sceneZMax,nearPlaneZ,farPlaneZ); #endif if (sceneZMax==0.0) sceneZMax=1e8; #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r; #ifdef SSRAYTRACE_SCREENSPACE_DEPTH sceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ); #endif if (sceneBackZ==0.0) sceneBackZ=-1e8;hit=(rayZMax>=sceneBackZ-csZThickness) && (rayZMin<=sceneZMax); #else hit=(rayZMax>=sceneZMax-csZThickness) && (rayZMin<=sceneZMax); #endif #else #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER float sceneBackZ=texelFetch(csZBackBuffer,ivec2(hitPixel/csZBackSizeFactor),0).r; #ifdef SSRAYTRACE_SCREENSPACE_DEPTH sceneBackZ=linearizeDepth(sceneBackZ,nearPlaneZ,farPlaneZ); #endif if (sceneBackZ==0.0) sceneBackZ=1e8;hit=(rayZMin<=sceneBackZ+csZThickness) && (rayZMax>=sceneZMax) && (sceneZMax != 0.0); #else hit=(rayZMin<=sceneZMax+csZThickness) && (rayZMax>=sceneZMax); #endif #endif } pqk-=dPQK;stepCount-=1.0;if (((pqk.x+dPQK.x)*stepDirection)>end || (stepCount+1.0)>=maxSteps || sceneZMax==0.0) {hit=false;} #ifdef SSRAYTRACE_ENABLE_REFINEMENT if (stride>1.0 && hit) {pqk-=dPQK;stepCount-=1.0;float invStride=1.0/stride;dPQK*=invStride;float refinementStepCount=0.0;prevZMaxEstimate=pqk.z/pqk.w;rayZMax=prevZMaxEstimate;sceneZMax=rayZMax+1e7;for (;refinementStepCount<=1.0 || (refinementStepCount<=stride*1.4) && (rayZMaxend) {debugColor=vec3(0,0,1);} else if ((stepCount+1.0)>=maxSteps) {debugColor=vec3(1,0,0);} else if (sceneZMax==0.0) {debugColor=vec3(1,1,0);} else {debugColor=vec3(0,stepCount/maxSteps,0);} #endif return hit;} /** texCoord: in the [0,1] range depth: depth in view space (range [znear,zfar]]) */ vec3 computeViewPosFromUVDepth(vec2 texCoord,float depth,mat4 projection,mat4 invProjectionMatrix) {vec4 ndc;ndc.xy=texCoord*2.0-1.0; #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE #ifdef ORTHOGRAPHIC_CAMERA ndc.z=-projection[2].z*depth+projection[3].z; #else ndc.z=-projection[2].z-projection[3].z/depth; #endif #else #ifdef ORTHOGRAPHIC_CAMERA ndc.z=projection[2].z*depth+projection[3].z; #else ndc.z=projection[2].z+projection[3].z/depth; #endif #endif ndc.w=1.0;vec4 eyePos=invProjectionMatrix*ndc;eyePos.xyz/=eyePos.w;return eyePos.xyz;} `; if (!ShaderStore.IncludesShadersStore[name198]) { ShaderStore.IncludesShadersStore[name198] = shader198; } screenSpaceRayTrace = { name: name198, shader: shader198 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/screenSpaceReflection2.fragment.js var screenSpaceReflection2_fragment_exports2 = {}; __export(screenSpaceReflection2_fragment_exports2, { screenSpaceReflection2PixelShader: () => screenSpaceReflection2PixelShader }); var name199, shader199, screenSpaceReflection2PixelShader; var init_screenSpaceReflection2_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/screenSpaceReflection2.fragment.js"() { init_shaderStore(); init_helperFunctions2(); init_pbrBRDFFunctions2(); init_screenSpaceRayTrace2(); name199 = "screenSpaceReflection2PixelShader"; shader199 = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) #define TEXTURECUBEFUNC(s,c,lod) textureLod(s,c,lod) #else #define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) #define TEXTURECUBEFUNC(s,c,bias) textureCube(s,c,bias) #endif uniform sampler2D textureSampler;varying vec2 vUV; #ifdef SSR_SUPPORTED uniform sampler2D reflectivitySampler;uniform sampler2D normalSampler;uniform sampler2D depthSampler; #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER uniform sampler2D backDepthSampler;uniform float backSizeFactor; #endif #ifdef SSR_USE_ENVIRONMENT_CUBE uniform samplerCube envCubeSampler; #ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC uniform vec3 vReflectionPosition;uniform vec3 vReflectionSize; #endif #endif uniform mat4 view;uniform mat4 invView;uniform mat4 projection;uniform mat4 invProjectionMatrix;uniform mat4 projectionPixel;uniform float nearPlaneZ;uniform float farPlaneZ;uniform float stepSize;uniform float maxSteps;uniform float strength;uniform float thickness;uniform float roughnessFactor;uniform float reflectionSpecularFalloffExponent;uniform float maxDistance;uniform float selfCollisionNumSkip;uniform float reflectivityThreshold; #include #include #include vec3 hash(vec3 a) {a=fract(a*0.8);a+=dot(a,a.yxz+19.19);return fract((a.xxy+a.yxx)*a.zyx);} float computeAttenuationForIntersection(ivec2 hitPixel,vec2 hitUV,vec3 vsRayOrigin,vec3 vsHitPoint,vec3 reflectionVector,float maxRayDistance,float numIterations) {float attenuation=1.0; #ifdef SSR_ATTENUATE_SCREEN_BORDERS vec2 dCoords=smoothstep(0.2,0.6,abs(vec2(0.5,0.5)-hitUV.xy));attenuation*=clamp(1.0-(dCoords.x+dCoords.y),0.0,1.0); #endif #ifdef SSR_ATTENUATE_INTERSECTION_DISTANCE attenuation*=1.0-clamp(distance(vsRayOrigin,vsHitPoint)/maxRayDistance,0.0,1.0); #endif #ifdef SSR_ATTENUATE_INTERSECTION_NUMITERATIONS attenuation*=1.0-(numIterations/maxSteps); #endif #ifdef SSR_ATTENUATE_BACKFACE_REFLECTION vec3 reflectionNormal=texelFetch(normalSampler,hitPixel,0).xyz;float directionBasedAttenuation=smoothstep(-0.17,0.0,dot(reflectionNormal,-reflectionVector));attenuation*=directionBasedAttenuation; #endif return attenuation;} #endif void main() { #ifdef SSR_SUPPORTED vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);vec3 color=colorFull.rgb;vec4 reflectivity=max(TEXTUREFUNC(reflectivitySampler,vUV,0.0),vec4(0.)); #ifndef SSR_DISABLE_REFLECTIVITY_TEST if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) { #ifdef SSR_USE_BLUR gl_FragColor=vec4(0.); #else gl_FragColor=colorFull; #endif return;} #endif #ifdef SSR_INPUT_IS_GAMMA_SPACE color=toLinearSpace(color); #endif vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; #ifdef SSR_DECODE_NORMAL csNormal=csNormal*2.0-1.0; #endif #ifdef SSR_NORMAL_IS_IN_WORLDSPACE csNormal=(view*vec4(csNormal,0.0)).xyz; #endif float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r; #ifdef SSRAYTRACE_SCREENSPACE_DEPTH depth=linearizeDepth(depth,nearPlaneZ,farPlaneZ); #endif vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix); #ifdef ORTHOGRAPHIC_CAMERA vec3 csViewDirection=vec3(0.,0.,1.); #else vec3 csViewDirection=normalize(csPosition); #endif vec3 csReflectedVector=reflect(csViewDirection,csNormal); #ifdef SSR_USE_ENVIRONMENT_CUBE vec3 wReflectedVector=vec3(invView*vec4(csReflectedVector,0.0)); #ifdef SSR_USE_LOCAL_REFLECTIONMAP_CUBIC vec4 worldPos=invView*vec4(csPosition,1.0);wReflectedVector=parallaxCorrectNormal(worldPos.xyz,normalize(wReflectedVector),vReflectionSize,vReflectionPosition); #endif #ifdef SSR_INVERTCUBICMAP wReflectedVector.y*=-1.0; #endif #ifdef SSRAYTRACE_RIGHT_HANDED_SCENE wReflectedVector.z*=-1.0; #endif vec3 envColor=TEXTURECUBEFUNC(envCubeSampler,wReflectedVector,0.0).xyz; #ifdef SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE envColor=toLinearSpace(envColor); #endif #else vec3 envColor=color; #endif float reflectionAttenuation=1.0;bool rayHasHit=false;vec2 startPixel;vec2 hitPixel;vec3 hitPoint;float numIterations; #ifdef SSRAYTRACE_DEBUG vec3 debugColor; #endif #ifdef SSR_ATTENUATE_FACING_CAMERA reflectionAttenuation*=1.0-smoothstep(0.25,0.5,dot(-csViewDirection,csReflectedVector)); #endif if (reflectionAttenuation>0.0) { #ifdef SSR_USE_BLUR vec3 jitt=vec3(0.); #else float roughness=1.0-reflectivity.a;vec3 jitt=mix(vec3(0.0),hash(csPosition)-vec3(0.5),roughness)*roughnessFactor; #endif vec2 uv2=vUV*texSize;float c=(uv2.x+uv2.y)*0.25;float jitter=mod(c,1.0); rayHasHit=traceScreenSpaceRay1( csPosition, normalize(csReflectedVector+jitt), projectionPixel, depthSampler, texSize, #ifdef SSRAYTRACE_USE_BACK_DEPTHBUFFER backDepthSampler, backSizeFactor, #endif thickness, nearPlaneZ, farPlaneZ, stepSize, jitter, maxSteps, maxDistance, selfCollisionNumSkip, startPixel, hitPixel, hitPoint, numIterations #ifdef SSRAYTRACE_DEBUG ,debugColor #endif );} #ifdef SSRAYTRACE_DEBUG gl_FragColor=vec4(debugColor,1.);return; #endif vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 SSR=envColor;if (rayHasHit) {vec3 reflectedColor=texelFetch(textureSampler,ivec2(hitPixel),0).rgb; #ifdef SSR_INPUT_IS_GAMMA_SPACE reflectedColor=toLinearSpace(reflectedColor); #endif reflectionAttenuation*=computeAttenuationForIntersection(ivec2(hitPixel),hitPixel/texSize,csPosition,hitPoint,csReflectedVector,maxDistance,numIterations);SSR=reflectedColor*reflectionAttenuation+(1.0-reflectionAttenuation)*envColor;} #ifndef SSR_BLEND_WITH_FRESNEL SSR*=fresnel; #endif #ifdef SSR_USE_BLUR float blur_radius=0.0;float roughness=1.0-reflectivity.a*(1.0-roughnessFactor);if (roughness>0.001) {float cone_angle=min(roughness,0.999)*3.14159265*0.5;float cone_len=distance(startPixel,hitPixel);float op_len=2.0*tan(cone_angle)*cone_len; float a=op_len;float h=cone_len;float a2=a*a;float fh2=4.0f*h*h;blur_radius=(a*(sqrt(a2+fh2)-a))/(4.0f*h);} gl_FragColor=vec4(SSR,blur_radius/255.0); #else #ifdef SSR_BLEND_WITH_FRESNEL vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); #else vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); #endif vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color*colorMultiplier)+(SSR*reflectionMultiplier); #ifdef SSR_OUTPUT_IS_GAMMA_SPACE finalColor=toGammaSpace(finalColor); #endif gl_FragColor=vec4(finalColor,colorFull.a); #endif #else gl_FragColor=TEXTUREFUNC(textureSampler,vUV,0.0); #endif } `; if (!ShaderStore.ShadersStore[name199]) { ShaderStore.ShadersStore[name199] = shader199; } screenSpaceReflection2PixelShader = { name: name199, shader: shader199 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/screenSpaceReflection2Blur.fragment.js var screenSpaceReflection2Blur_fragment_exports = {}; __export(screenSpaceReflection2Blur_fragment_exports, { screenSpaceReflection2BlurPixelShaderWGSL: () => screenSpaceReflection2BlurPixelShaderWGSL }); var name200, shader200, screenSpaceReflection2BlurPixelShaderWGSL; var init_screenSpaceReflection2Blur_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/screenSpaceReflection2Blur.fragment.js"() { init_shaderStore(); name200 = "screenSpaceReflection2BlurPixelShader"; shader200 = `var textureSamplerSampler: sampler;var textureSampler: texture_2d;varying vUV: vec2f;uniform texelOffsetScale: vec2f;const weights: array=array(0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);fn processSample(uv: vec2f,i: f32,stepSize: vec2f,accumulator: ptr,denominator: ptr) {var offsetUV: vec2f=stepSize*i+uv;var coefficient: f32=weights[ i32(2.0-abs(i))];*accumulator+=textureSampleLevel(textureSampler,textureSamplerSampler,offsetUV,0.0)*coefficient;*denominator+=coefficient;} @fragment fn main(input: FragmentInputs)->FragmentOutputs {var colorFull: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);if (dot(colorFull, vec4f(1.0))==0.0) {fragmentOutputs.color=colorFull;return fragmentOutputs;} var blurRadius: f32=colorFull.a*255.0; var stepSize: vec2f=uniforms.texelOffsetScale.xy*blurRadius;var accumulator: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0)*0.214607;var denominator: f32=0.214607;processSample(input.vUV,1.0,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.2,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.4,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.6,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*0.8,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.2,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.4,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.6,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*1.8,stepSize,&accumulator,&denominator);processSample(input.vUV,1.0*2.0,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.2,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.4,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.6,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*0.8,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.2,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.4,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.6,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*1.8,stepSize,&accumulator,&denominator);processSample(input.vUV,-1.0*2.0,stepSize,&accumulator,&denominator);fragmentOutputs.color= vec4f(accumulator.rgb/denominator,colorFull.a);} `; if (!ShaderStore.ShadersStoreWGSL[name200]) { ShaderStore.ShadersStoreWGSL[name200] = shader200; } screenSpaceReflection2BlurPixelShaderWGSL = { name: name200, shader: shader200 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/screenSpaceReflection2Blur.fragment.js var screenSpaceReflection2Blur_fragment_exports2 = {}; __export(screenSpaceReflection2Blur_fragment_exports2, { screenSpaceReflection2BlurPixelShader: () => screenSpaceReflection2BlurPixelShader }); var name201, shader201, screenSpaceReflection2BlurPixelShader; var init_screenSpaceReflection2Blur_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/screenSpaceReflection2Blur.fragment.js"() { init_shaderStore(); name201 = "screenSpaceReflection2BlurPixelShader"; shader201 = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) #else #define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) #endif uniform sampler2D textureSampler;varying vec2 vUV;uniform vec2 texelOffsetScale;const float weights[8]=float[8] (0.071303,0.131514,0.189879,0.321392,0.452906, 0.584419,0.715932,0.847445);void processSample(vec2 uv,float i,vec2 stepSize,inout vec4 accumulator,inout float denominator) {vec2 offsetUV=stepSize*i+uv;float coefficient=weights[int(2.0-abs(i))];accumulator+=TEXTUREFUNC(textureSampler,offsetUV,0.0)*coefficient;denominator+=coefficient;} void main() {vec4 colorFull=TEXTUREFUNC(textureSampler,vUV,0.0);if (dot(colorFull,vec4(1.0))==0.0) {gl_FragColor=colorFull;return;} float blurRadius=colorFull.a*255.0; vec2 stepSize=texelOffsetScale.xy*blurRadius;vec4 accumulator=TEXTUREFUNC(textureSampler,vUV,0.0)*0.214607;float denominator=0.214607;processSample(vUV,1.0,stepSize,accumulator,denominator);processSample(vUV,1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,1.0*2.0,stepSize,accumulator,denominator);processSample(vUV,-1.0,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*0.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.2,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.4,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.6,stepSize,accumulator,denominator);processSample(vUV,-1.0*1.8,stepSize,accumulator,denominator);processSample(vUV,-1.0*2.0,stepSize,accumulator,denominator);gl_FragColor=vec4(accumulator.rgb/denominator,colorFull.a);} `; if (!ShaderStore.ShadersStore[name201]) { ShaderStore.ShadersStore[name201] = shader201; } screenSpaceReflection2BlurPixelShader = { name: name201, shader: shader201 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/screenSpaceReflection2BlurCombiner.fragment.js var screenSpaceReflection2BlurCombiner_fragment_exports = {}; __export(screenSpaceReflection2BlurCombiner_fragment_exports, { screenSpaceReflection2BlurCombinerPixelShaderWGSL: () => screenSpaceReflection2BlurCombinerPixelShaderWGSL }); var name202, shader202, screenSpaceReflection2BlurCombinerPixelShaderWGSL; var init_screenSpaceReflection2BlurCombiner_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/screenSpaceReflection2BlurCombiner.fragment.js"() { init_shaderStore(); init_helperFunctions(); init_pbrBRDFFunctions(); init_screenSpaceRayTrace(); name202 = "screenSpaceReflection2BlurCombinerPixelShader"; shader202 = `var textureSamplerSampler: sampler;var textureSampler: texture_2d; var mainSamplerSampler: sampler;var mainSampler: texture_2d;var reflectivitySamplerSampler: sampler;var reflectivitySampler: texture_2d;uniform strength: f32;uniform reflectionSpecularFalloffExponent: f32;uniform reflectivityThreshold: f32;varying vUV: vec2f; #include #ifdef SSR_BLEND_WITH_FRESNEL #include #include uniform projection: mat4x4f;uniform invProjectionMatrix: mat4x4f; #ifdef SSR_NORMAL_IS_IN_WORLDSPACE uniform view: mat4x4f; #endif var normalSampler: texture_2d;var depthSampler: texture_2d; #ifdef SSRAYTRACE_SCREENSPACE_DEPTH uniform nearPlaneZ: f32;uniform farPlaneZ: f32; #endif #endif @fragment fn main(input: FragmentInputs)->FragmentOutputs { #ifdef SSRAYTRACE_DEBUG fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV); #else var SSR: vec3f=textureSample(textureSampler,textureSamplerSampler,input.vUV).rgb;var color: vec4f=textureSample(mainSampler,textureSamplerSampler,input.vUV);var reflectivity: vec4f=textureSample(reflectivitySampler,reflectivitySamplerSampler,input.vUV); #ifndef SSR_DISABLE_REFLECTIVITY_TEST if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=uniforms.reflectivityThreshold) {fragmentOutputs.color=color;return fragmentOutputs;} #endif #ifdef SSR_INPUT_IS_GAMMA_SPACE color=toLinearSpaceVec4(color); #endif #ifdef SSR_BLEND_WITH_FRESNEL var texSize: vec2f= vec2f(textureDimensions(depthSampler,0));var csNormal: vec3f=textureLoad(normalSampler,vec2(input.vUV*texSize),0).xyz; #ifdef SSR_DECODE_NORMAL csNormal=csNormal*2.0-1.0; #endif #ifdef SSR_NORMAL_IS_IN_WORLDSPACE csNormal=(uniforms.view*vec4f(csNormal,0.0)).xyz; #endif var depth: f32=textureLoad(depthSampler,vec2(input.vUV*texSize),0).r; #ifdef SSRAYTRACE_SCREENSPACE_DEPTH depth=linearizeDepth(depth,uniforms.nearPlaneZ,uniforms.farPlaneZ); #endif var csPosition: vec3f=computeViewPosFromUVDepth(input.vUV,depth,uniforms.projection,uniforms.invProjectionMatrix);var csViewDirection: vec3f=normalize(csPosition);var F0: vec3f=reflectivity.rgb;var fresnel: vec3f=fresnelSchlickGGXVec3(max(dot(csNormal,-csViewDirection),0.0),F0, vec3f(1.));var reflectionMultiplier: vec3f=clamp(pow(fresnel*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0)); #else var reflectionMultiplier: vec3f=clamp(pow(reflectivity.rgb*uniforms.strength, vec3f(uniforms.reflectionSpecularFalloffExponent)),vec3f(0.0),vec3f(1.0)); #endif var colorMultiplier: vec3f=1.0-reflectionMultiplier;var finalColor: vec3f=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); #ifdef SSR_OUTPUT_IS_GAMMA_SPACE finalColor=toGammaSpaceVec3(finalColor); #endif fragmentOutputs.color= vec4f(finalColor,color.a); #endif } `; if (!ShaderStore.ShadersStoreWGSL[name202]) { ShaderStore.ShadersStoreWGSL[name202] = shader202; } screenSpaceReflection2BlurCombinerPixelShaderWGSL = { name: name202, shader: shader202 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/screenSpaceReflection2BlurCombiner.fragment.js var screenSpaceReflection2BlurCombiner_fragment_exports2 = {}; __export(screenSpaceReflection2BlurCombiner_fragment_exports2, { screenSpaceReflection2BlurCombinerPixelShader: () => screenSpaceReflection2BlurCombinerPixelShader }); var name203, shader203, screenSpaceReflection2BlurCombinerPixelShader; var init_screenSpaceReflection2BlurCombiner_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/screenSpaceReflection2BlurCombiner.fragment.js"() { init_shaderStore(); init_helperFunctions2(); init_pbrBRDFFunctions2(); init_screenSpaceRayTrace2(); name203 = "screenSpaceReflection2BlurCombinerPixelShader"; shader203 = `uniform sampler2D textureSampler; uniform sampler2D mainSampler;uniform sampler2D reflectivitySampler;uniform float strength;uniform float reflectionSpecularFalloffExponent;uniform float reflectivityThreshold;varying vec2 vUV; #include #ifdef SSR_BLEND_WITH_FRESNEL #include #include uniform mat4 projection;uniform mat4 invProjectionMatrix; #ifdef SSR_NORMAL_IS_IN_WORLDSPACE uniform mat4 view; #endif uniform sampler2D normalSampler;uniform sampler2D depthSampler; #ifdef SSRAYTRACE_SCREENSPACE_DEPTH uniform float nearPlaneZ;uniform float farPlaneZ; #endif #endif void main() { #ifdef SSRAYTRACE_DEBUG gl_FragColor=texture2D(textureSampler,vUV); #else vec3 SSR=texture2D(textureSampler,vUV).rgb;vec4 color=texture2D(mainSampler,vUV);vec4 reflectivity=texture2D(reflectivitySampler,vUV); #ifndef SSR_DISABLE_REFLECTIVITY_TEST if (max(reflectivity.r,max(reflectivity.g,reflectivity.b))<=reflectivityThreshold) {gl_FragColor=color;return;} #endif #ifdef SSR_INPUT_IS_GAMMA_SPACE color=toLinearSpace(color); #endif #ifdef SSR_BLEND_WITH_FRESNEL vec2 texSize=vec2(textureSize(depthSampler,0));vec3 csNormal=texelFetch(normalSampler,ivec2(vUV*texSize),0).xyz; #ifdef SSR_DECODE_NORMAL csNormal=csNormal*2.0-1.0; #endif #ifdef SSR_NORMAL_IS_IN_WORLDSPACE csNormal=(view*vec4(csNormal,0.0)).xyz; #endif float depth=texelFetch(depthSampler,ivec2(vUV*texSize),0).r; #ifdef SSRAYTRACE_SCREENSPACE_DEPTH depth=linearizeDepth(depth,nearPlaneZ,farPlaneZ); #endif vec3 csPosition=computeViewPosFromUVDepth(vUV,depth,projection,invProjectionMatrix);vec3 csViewDirection=normalize(csPosition);vec3 F0=reflectivity.rgb;vec3 fresnel=fresnelSchlickGGX(max(dot(csNormal,-csViewDirection),0.0),F0,vec3(1.));vec3 reflectionMultiplier=clamp(pow(fresnel*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); #else vec3 reflectionMultiplier=clamp(pow(reflectivity.rgb*strength,vec3(reflectionSpecularFalloffExponent)),0.0,1.0); #endif vec3 colorMultiplier=1.0-reflectionMultiplier;vec3 finalColor=(color.rgb*colorMultiplier)+(SSR*reflectionMultiplier); #ifdef SSR_OUTPUT_IS_GAMMA_SPACE finalColor=toGammaSpace(finalColor); #endif gl_FragColor=vec4(finalColor,color.a); #endif } `; if (!ShaderStore.ShadersStore[name203]) { ShaderStore.ShadersStore[name203] = shader203; } screenSpaceReflection2BlurCombinerPixelShader = { name: name203, shader: shader203 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ssao2.fragment.js var ssao2_fragment_exports = {}; __export(ssao2_fragment_exports, { ssao2PixelShaderWGSL: () => ssao2PixelShaderWGSL }); var name204, shader204, ssao2PixelShaderWGSL; var init_ssao2_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ssao2.fragment.js"() { init_shaderStore(); name204 = "ssao2PixelShader"; shader204 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #ifdef SSAO const scales: array=array( 0.1, 0.11406250000000001, 0.131640625, 0.15625, 0.187890625, 0.2265625, 0.272265625, 0.325, 0.384765625, 0.4515625, 0.525390625, 0.60625, 0.694140625, 0.7890625, 0.891015625, 1.0 );uniform near: f32;uniform radius: f32;var depthSamplerSampler: sampler;var depthSampler: texture_2d;var randomSamplerSampler: sampler;var randomSampler: texture_2d;var normalSamplerSampler: sampler;var normalSampler: texture_2d;uniform randTextureTiles: f32;uniform samplesFactor: f32;uniform sampleSphere: array;uniform totalStrength: f32;uniform base: f32; #ifdef ORTHOGRAPHIC_CAMERA uniform viewport: vec4f; #else uniform xViewport: f32;uniform yViewport: f32; #endif uniform depthProjection: mat3x3f;uniform maxZ: f32;uniform minZAspect: f32;uniform texelSize: vec2f;uniform projection: mat4x4f;@fragment fn main(input: FragmentInputs)->FragmentOutputs {var random: vec3f=textureSampleLevel(randomSampler,randomSamplerSampler,input.vUV*uniforms.randTextureTiles,0.0).rgb;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.0).r;var depthSign: f32=sign(depth);depth=depth*depthSign;var normal: vec3f=textureSampleLevel(normalSampler,normalSamplerSampler,input.vUV,0.0).rgb;var occlusion: f32=0.0;var correctedRadius: f32=min(uniforms.radius,uniforms.minZAspect*depth/uniforms.near); #ifdef ORTHOGRAPHIC_CAMERA var vViewRay: vec3f= vec3f(mix(uniforms.viewport.x,uniforms.viewport.y,input.vUV.x),mix(uniforms.viewport.z,uniforms.viewport.w,input.vUV.y),depthSign); #else var vViewRay: vec3f= vec3f((input.vUV.x*2.0-1.0)*uniforms.xViewport,(input.vUV.y*2.0-1.0)*uniforms.yViewport,depthSign); #endif var vDepthFactor: vec3f=uniforms.depthProjection* vec3f(1.0,1.0,depth);var origin: vec3f=vViewRay*vDepthFactor;var rvec: vec3f=random*2.0-1.0;rvec.z=0.0;var dotProduct: f32=dot(rvec,normal);rvec=select( vec3f(-rvec.y,0.0,rvec.x),rvec,1.0-abs(dotProduct)>1e-2);var tangent: vec3f=normalize(rvec-normal*dot(rvec,normal));var bitangent: vec3f=cross(normal,tangent);var tbn: mat3x3f= mat3x3f(tangent,bitangent,normal);var difference: f32;for (var i: i32=0; i1.0 || offset.y>1.0) {continue;} var sampleDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;var rangeCheck: f32=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} occlusion=occlusion*(1.0-smoothstep(uniforms.maxZ*0.75,uniforms.maxZ,depth));var ao: f32=1.0-uniforms.totalStrength*occlusion*uniforms.samplesFactor;var result: f32=clamp(ao+uniforms.base,0.0,1.0);fragmentOutputs.color= vec4f( vec3f(result),1.0);} #else #ifdef BLUR uniform outSize: f32;uniform soften: f32;uniform tolerance: f32;uniform samples: i32; #ifndef BLUR_BYPASS var depthSamplerSampler: sampler;var depthSampler: texture_2d; #ifdef BLUR_LEGACY fn blur13Bilateral(image: texture_2d,imageSampler: sampler,uv: vec2f,step: vec2f)->f32 {var result: f32=0.0;var off1: vec2f= vec2f(1.411764705882353)*step;var off2: vec2f= vec2f(3.2941176470588234)*step;var off3: vec2f= vec2f(5.176470588235294)*step;var compareDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv,0.0).r);var sampleDepth: f32;var weight: f32;var weightSum: f32=30.0;result+=textureSampleLevel(image,imageSampler,uv,0.0).r*30.0;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureSampleLevel(image,imageSampler,uv+off1,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureSampleLevel(image,imageSampler,uv-off1,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv+off2,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv-off2,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv+off3,0.0).r*weight;sampleDepth=abs(textureSampleLevel(depthSampler,depthSamplerSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureSampleLevel(image,imageSampler,uv-off3,0.0).r*weight;return result/weightSum;} #endif #endif @fragment fn main(input: FragmentInputs)->FragmentOutputs {var result: f32=0.0; #ifdef BLUR_BYPASS result=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0).r; #else #ifdef BLUR_H var step: vec2f= vec2f(1.0/uniforms.outSize,0.0); #else var step: vec2f= vec2f(0.0,1.0/uniforms.outSize); #endif #ifdef BLUR_LEGACY result=blur13Bilateral(textureSampler,textureSamplerSampler,input.vUV,step); #else var compareDepth: f32=abs(textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.0).r);var weightSum: f32=0.0;for (var i: i32=-uniforms.samples; i ssao2PixelShader }); var name205, shader205, ssao2PixelShader; var init_ssao2_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ssao2.fragment.js"() { init_shaderStore(); name205 = "ssao2PixelShader"; shader205 = `precision highp float;uniform sampler2D textureSampler;varying vec2 vUV; #ifdef SSAO float scales[16]=float[16]( 0.1, 0.11406250000000001, 0.131640625, 0.15625, 0.187890625, 0.2265625, 0.272265625, 0.325, 0.384765625, 0.4515625, 0.525390625, 0.60625, 0.694140625, 0.7890625, 0.891015625, 1.0 );uniform float near;uniform float radius;uniform sampler2D depthSampler;uniform sampler2D randomSampler;uniform sampler2D normalSampler;uniform float randTextureTiles;uniform float samplesFactor;uniform vec3 sampleSphere[SAMPLES];uniform float totalStrength;uniform float base; #ifdef ORTHOGRAPHIC_CAMERA uniform vec4 viewport; #else uniform float xViewport;uniform float yViewport; #endif uniform mat3 depthProjection;uniform float maxZ;uniform float minZAspect;uniform vec2 texelSize;uniform mat4 projection;void main() {vec3 random=textureLod(randomSampler,vUV*randTextureTiles,0.0).rgb;float depth=textureLod(depthSampler,vUV,0.0).r;float depthSign=sign(depth);depth=depth*depthSign;vec3 normal=textureLod(normalSampler,vUV,0.0).rgb;float occlusion=0.0;float correctedRadius=min(radius,minZAspect*depth/near); #ifdef ORTHOGRAPHIC_CAMERA vec3 vViewRay=vec3(mix(viewport.x,viewport.y,vUV.x),mix(viewport.z,viewport.w,vUV.y),depthSign); #else vec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign); #endif vec3 vDepthFactor=depthProjection*vec3(1.0,1.0,depth);vec3 origin=vViewRay*vDepthFactor;vec3 rvec=random*2.0-1.0;rvec.z=0.0;float dotProduct=dot(rvec,normal);rvec=1.0-abs(dotProduct)>1e-2 ? rvec : vec3(-rvec.y,0.0,rvec.x);vec3 tangent=normalize(rvec-normal*dot(rvec,normal));vec3 bitangent=cross(normal,tangent);mat3 tbn=mat3(tangent,bitangent,normal);float difference;for (int i=0; i1.0 || offset.y>1.0) {continue;} float sampleDepth=abs(textureLod(depthSampler,offset.xy,0.0).r);difference=depthSign*samplePosition.z-sampleDepth;float rangeCheck=1.0-smoothstep(correctedRadius*0.5,correctedRadius,difference);occlusion+=step(EPSILON,difference)*rangeCheck;} occlusion=occlusion*(1.0-smoothstep(maxZ*0.75,maxZ,depth));float ao=1.0-totalStrength*occlusion*samplesFactor;float result=clamp(ao+base,0.0,1.0);gl_FragColor=vec4(vec3(result),1.0);} #endif #ifdef BLUR uniform float outSize;uniform float soften;uniform float tolerance;uniform int samples; #ifndef BLUR_BYPASS uniform sampler2D depthSampler; #ifdef BLUR_LEGACY #define inline float blur13Bilateral(sampler2D image,vec2 uv,vec2 step) {float result=0.0;vec2 off1=vec2(1.411764705882353)*step;vec2 off2=vec2(3.2941176470588234)*step;vec2 off3=vec2(5.176470588235294)*step;float compareDepth=abs(textureLod(depthSampler,uv,0.0).r);float sampleDepth;float weight;float weightSum=30.0;result+=textureLod(image,uv,0.0).r*30.0;sampleDepth=abs(textureLod(depthSampler,uv+off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv+off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off1,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+= weight;result+=textureLod(image,uv-off1,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off2,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off2,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv+off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv+off3,0.0).r*weight;sampleDepth=abs(textureLod(depthSampler,uv-off3,0.0).r);weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);weightSum+=weight;result+=textureLod(image,uv-off3,0.0).r*weight;return result/weightSum;} #endif #endif void main() {float result=0.0; #ifdef BLUR_BYPASS result=textureLod(textureSampler,vUV,0.0).r; #else #ifdef BLUR_H vec2 step=vec2(1.0/outSize,0.0); #else vec2 step=vec2(0.0,1.0/outSize); #endif #ifdef BLUR_LEGACY result=blur13Bilateral(textureSampler,vUV,step); #else float compareDepth=abs(textureLod(depthSampler,vUV,0.0).r);float weightSum=0.0;for (int i=-samples; i ssaoCombinePixelShaderWGSL }); var name206, shader206, ssaoCombinePixelShaderWGSL; var init_ssaoCombine_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ssaoCombine.fragment.js"() { init_shaderStore(); name206 = "ssaoCombinePixelShader"; shader206 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var originalColorSampler: sampler;var originalColor: texture_2d;uniform viewport: vec4f; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN var uv: vec2f=uniforms.viewport.xy+input.vUV*uniforms.viewport.zw;var ssaoColor: vec4f=textureSample(textureSampler,textureSamplerSampler,uv);var sceneColor: vec4f=textureSample(originalColor,originalColorSampler,uv);fragmentOutputs.color=sceneColor*ssaoColor; #define CUSTOM_FRAGMENT_MAIN_END } `; if (!ShaderStore.ShadersStoreWGSL[name206]) { ShaderStore.ShadersStoreWGSL[name206] = shader206; } ssaoCombinePixelShaderWGSL = { name: name206, shader: shader206 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ssaoCombine.fragment.js var ssaoCombine_fragment_exports2 = {}; __export(ssaoCombine_fragment_exports2, { ssaoCombinePixelShader: () => ssaoCombinePixelShader }); var name207, shader207, ssaoCombinePixelShader; var init_ssaoCombine_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ssaoCombine.fragment.js"() { init_shaderStore(); name207 = "ssaoCombinePixelShader"; shader207 = `uniform sampler2D textureSampler;uniform sampler2D originalColor;uniform vec4 viewport;varying vec2 vUV; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN vec2 uv=viewport.xy+vUV*viewport.zw;vec4 ssaoColor=texture2D(textureSampler,uv);vec4 sceneColor=texture2D(originalColor,uv);gl_FragColor=sceneColor*ssaoColor; #define CUSTOM_FRAGMENT_MAIN_END } `; if (!ShaderStore.ShadersStore[name207]) { ShaderStore.ShadersStore[name207] = shader207; } ssaoCombinePixelShader = { name: name207, shader: shader207 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/motionBlur.fragment.js var motionBlur_fragment_exports = {}; __export(motionBlur_fragment_exports, { motionBlurPixelShaderWGSL: () => motionBlurPixelShaderWGSL }); var name208, shader208, motionBlurPixelShaderWGSL; var init_motionBlur_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/motionBlur.fragment.js"() { init_shaderStore(); name208 = "motionBlurPixelShader"; shader208 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform motionStrength: f32;uniform motionScale: f32;uniform screenSize: vec2f; #ifdef OBJECT_BASED var velocitySamplerSampler: sampler;var velocitySampler: texture_2d; #else var depthSamplerSampler: sampler;var depthSampler: texture_2d;uniform inverseViewProjection: mat4x4f;uniform prevViewProjection: mat4x4f;uniform projection: mat4x4f; #endif #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #ifdef GEOMETRY_SUPPORTED #ifdef OBJECT_BASED var texelSize: vec2f=1.0/uniforms.screenSize;var velocityColor: vec4f=textureSampleLevel(velocitySampler,velocitySamplerSampler,input.vUV,0.0);velocityColor=vec4f(velocityColor.rg*2.0- vec2f(1.0),velocityColor.b,velocityColor.a);let signs=sign(velocityColor.rg);var velocity=pow(abs(velocityColor.rg),vec2f(3.0))*signs*velocityColor.a;velocity*=uniforms.motionScale*uniforms.motionStrength;var speed: f32=length(velocity/texelSize);var samplesCount: i32= i32(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;var hlim: f32= f32(-samplesCount)*0.5+0.5;var result: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler, input.vUV,0.0);for (var i: i32=1; i< i32(SAMPLES); i++) {if (i>=samplesCount) {break;} var offset: vec2f=input.vUV+velocity*(hlim+ f32(i));result+=textureSampleLevel(textureSampler,textureSamplerSampler, offset,0.0);} fragmentOutputs.color=vec4f(result.rgb/ f32(samplesCount),1.0); #else var result: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler, input.vUV,0.0);var texelSize: vec2f=1.0/uniforms.screenSize;var depth: f32=textureSampleLevel(depthSampler,depthSamplerSampler,input.vUV,0.0).r;if (depth==0.0) {fragmentOutputs.color=result;return fragmentOutputs;} depth=uniforms.projection[2].z+uniforms.projection[3].z/depth; var cpos: vec4f= vec4f(input.vUV*2.0-1.0,depth,1.0);cpos=uniforms.inverseViewProjection*cpos;cpos/=cpos.w;var ppos: vec4f=uniforms.prevViewProjection*cpos;ppos/=ppos.w;ppos=vec4f(ppos.xy*0.5+0.5,ppos.zw);var velocity: vec2f=(ppos.xy-input.vUV)*uniforms.motionScale*uniforms.motionStrength;var speed: f32=length(velocity/texelSize);var nSamples: i32= i32(clamp(speed,1.0,SAMPLES));for (var i: i32=1; i< i32(SAMPLES); i++) {if (i>=nSamples) {break;} var offset1: vec2f=input.vUV+velocity*( f32(i)/ f32(nSamples-1)-0.5);result+=textureSampleLevel(textureSampler,textureSamplerSampler, offset1,0.0);} fragmentOutputs.color=result/ f32(nSamples); #endif #else fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler, input.vUV); #endif } `; if (!ShaderStore.ShadersStoreWGSL[name208]) { ShaderStore.ShadersStoreWGSL[name208] = shader208; } motionBlurPixelShaderWGSL = { name: name208, shader: shader208 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/motionBlur.fragment.js var motionBlur_fragment_exports2 = {}; __export(motionBlur_fragment_exports2, { motionBlurPixelShader: () => motionBlurPixelShader }); var name209, shader209, motionBlurPixelShader; var init_motionBlur_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/motionBlur.fragment.js"() { init_shaderStore(); name209 = "motionBlurPixelShader"; shader209 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform float motionStrength;uniform float motionScale;uniform vec2 screenSize; #ifdef OBJECT_BASED uniform sampler2D velocitySampler; #else uniform sampler2D depthSampler;uniform mat4 inverseViewProjection;uniform mat4 prevViewProjection;uniform mat4 projection; #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #ifdef GEOMETRY_SUPPORTED #ifdef OBJECT_BASED vec2 texelSize=1.0/screenSize;vec4 velocityColor=textureLod(velocitySampler,vUV,0.0);velocityColor.rg=velocityColor.rg*2.0-vec2(1.0);vec2 signs=sign(velocityColor.rg);vec2 velocity=pow(abs(velocityColor.rg),vec2(3.0))*signs*velocityColor.a;velocity*=motionScale*motionStrength;float speed=length(velocity/texelSize);int samplesCount=int(clamp(speed,1.0,SAMPLES));velocity=normalize(velocity)*texelSize;float hlim=float(-samplesCount)*0.5+0.5;vec4 result=textureLod(textureSampler,vUV,0.0);for (int i=1; i=samplesCount) break;vec2 offset=vUV+velocity*(hlim+float(i));result+=textureLod(textureSampler,offset,0.0);} gl_FragColor=result/float(samplesCount);gl_FragColor.a=1.0; #else vec4 result=textureLod(textureSampler,vUV,0.0);vec2 texelSize=1.0/screenSize;float depth=textureLod(depthSampler,vUV,0.0).r;if (depth==0.0) {gl_FragColor=result;return;} depth=projection[2].z+projection[3].z/depth; vec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);cpos=inverseViewProjection*cpos;cpos/=cpos.w;vec4 ppos=prevViewProjection*cpos;ppos/=ppos.w;ppos.xy=ppos.xy*0.5+0.5;vec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;float speed=length(velocity/texelSize);int nSamples=int(clamp(speed,1.0,SAMPLES));for (int i=1; i=nSamples) break;vec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);result+=textureLod(textureSampler,offset1,0.0);} gl_FragColor=result/float(nSamples); #endif #else gl_FragColor=texture2D(textureSampler,vUV); #endif } `; if (!ShaderStore.ShadersStore[name209]) { ShaderStore.ShadersStore[name209] = shader209; } motionBlurPixelShader = { name: name209, shader: shader209 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/glowBlurPostProcess.fragment.js var glowBlurPostProcess_fragment_exports = {}; __export(glowBlurPostProcess_fragment_exports, { glowBlurPostProcessPixelShaderWGSL: () => glowBlurPostProcessPixelShaderWGSL }); var name210, shader210, glowBlurPostProcessPixelShaderWGSL; var init_glowBlurPostProcess_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/glowBlurPostProcess.fragment.js"() { init_shaderStore(); name210 = "glowBlurPostProcessPixelShader"; shader210 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform direction: vec2f;uniform blurWidth: f32;fn getLuminance(color: vec3f)->f32 {return dot(color, vec3f(0.2126,0.7152,0.0722));} #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var weights: array;weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;var texelSize: vec2f= vec2f(1.0/uniforms.screenSize.x,1.0/uniforms.screenSize.y);var texelStep: vec2f=texelSize*uniforms.direction*uniforms.blurWidth;var start: vec2f=input.vUV-3.0*texelStep;var baseColor: vec4f= vec4f(0.,0.,0.,0.);var texelOffset: vec2f= vec2f(0.,0.);for (var i: i32=0; i<7; i++) {var texel: vec4f=textureSample(textureSampler,textureSamplerSampler,start+texelOffset);baseColor=vec4f(baseColor.rgb,baseColor.a+texel.a*weights[i]);var luminance: f32=getLuminance(baseColor.rgb);var luminanceTexel: f32=getLuminance(texel.rgb);var choice: f32=step(luminanceTexel,luminance);baseColor=vec4f(choice*baseColor.rgb+(1.0-choice)*texel.rgb,baseColor.a);texelOffset+=texelStep;} fragmentOutputs.color=baseColor;}`; if (!ShaderStore.ShadersStoreWGSL[name210]) { ShaderStore.ShadersStoreWGSL[name210] = shader210; } glowBlurPostProcessPixelShaderWGSL = { name: name210, shader: shader210 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/glowBlurPostProcess.fragment.js var glowBlurPostProcess_fragment_exports2 = {}; __export(glowBlurPostProcess_fragment_exports2, { glowBlurPostProcessPixelShader: () => glowBlurPostProcessPixelShader }); var name211, shader211, glowBlurPostProcessPixelShader; var init_glowBlurPostProcess_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/glowBlurPostProcess.fragment.js"() { init_shaderStore(); name211 = "glowBlurPostProcessPixelShader"; shader211 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 direction;uniform float blurWidth;float getLuminance(vec3 color) {return dot(color,vec3(0.2126,0.7152,0.0722));} #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {float weights[7];weights[0]=0.05;weights[1]=0.1;weights[2]=0.2;weights[3]=0.3;weights[4]=0.2;weights[5]=0.1;weights[6]=0.05;vec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);vec2 texelStep=texelSize*direction*blurWidth;vec2 start=vUV-3.0*texelStep;vec4 baseColor=vec4(0.,0.,0.,0.);vec2 texelOffset=vec2(0.,0.);for (int i=0; i<7; i++) {vec4 texel=texture2D(textureSampler,start+texelOffset);baseColor.a+=texel.a*weights[i];float luminance=getLuminance(baseColor.rgb);float luminanceTexel=getLuminance(texel.rgb);float choice=step(luminanceTexel,luminance);baseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;texelOffset+=texelStep;} gl_FragColor=baseColor;}`; if (!ShaderStore.ShadersStore[name211]) { ShaderStore.ShadersStore[name211] = shader211; } glowBlurPostProcessPixelShader = { name: name211, shader: shader211 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/glowMapGeneration.vertex.js var glowMapGeneration_vertex_exports = {}; __export(glowMapGeneration_vertex_exports, { glowMapGenerationVertexShaderWGSL: () => glowMapGenerationVertexShaderWGSL }); var name212, shader212, glowMapGenerationVertexShaderWGSL; var init_glowMapGeneration_vertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/glowMapGeneration.vertex.js"() { init_shaderStore(); init_bonesDeclaration(); init_bakedVertexAnimationDeclaration(); init_morphTargetsVertexGlobalDeclaration(); init_morphTargetsVertexDeclaration(); init_clipPlaneVertexDeclaration(); init_instancesDeclaration(); init_morphTargetsVertexGlobal(); init_morphTargetsVertex(); init_instancesVertex(); init_bonesVertex(); init_bakedVertexAnimation(); init_clipPlaneVertex(); name212 = "glowMapGenerationVertexShader"; shader212 = `attribute position: vec3f; #include #include #include #include[0..maxSimultaneousMorphTargets] #include #include uniform viewProjection: mat4x4f;varying vPosition: vec4f; #ifdef UV1 attribute uv: vec2f; #endif #ifdef UV2 attribute uv2: vec2f; #endif #ifdef DIFFUSE varying vUVDiffuse: vec2f;uniform diffuseMatrix: mat4x4f; #endif #ifdef OPACITY varying vUVOpacity: vec2f;uniform opacityMatrix: mat4x4f; #endif #ifdef EMISSIVE varying vUVEmissive: vec2f;uniform emissiveMatrix: mat4x4f; #endif #ifdef VERTEXALPHA attribute color: vec4f;varying vColor: vec4f; #endif #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs {var positionUpdated: vec3f=input.position; #ifdef UV1 var uvUpdated: vec2f=input.uv; #endif #ifdef UV2 var uv2Updated: vec2f=input.uv2; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include var worldPos: vec4f=finalWorld* vec4f(positionUpdated,1.0); #ifdef CUBEMAP vertexOutputs.vPosition=worldPos;vertexOutputs.position=uniforms.viewProjection*finalWorld* vec4f(input.position,1.0); #else vertexOutputs.vPosition=uniforms.viewProjection*worldPos;vertexOutputs.position=vertexOutputs.vPosition; #endif #ifdef DIFFUSE #ifdef DIFFUSEUV1 vertexOutputs.vUVDiffuse= (uniforms.diffuseMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef DIFFUSEUV2 vertexOutputs.vUVDiffuse= (uniforms.diffuseMatrix* vec4f(uv2Updated,1.0,0.0)).xy; #endif #endif #ifdef OPACITY #ifdef OPACITYUV1 vertexOutputs.vUVOpacity= (uniforms.opacityMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef OPACITYUV2 vertexOutputs.vUVOpacity= (uniforms.opacityMatrix* vec4f(uv2Updated,1.0,0.0)).xy; #endif #endif #ifdef EMISSIVE #ifdef EMISSIVEUV1 vertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(uvUpdated,1.0,0.0)).xy; #endif #ifdef EMISSIVEUV2 vertexOutputs.vUVEmissive= (uniforms.emissiveMatrix* vec4f(uv2Updated,1.0,0.0)).xy; #endif #endif #ifdef VERTEXALPHA vertexOutputs.vColor=vertexInputs.color; #endif #include }`; if (!ShaderStore.ShadersStoreWGSL[name212]) { ShaderStore.ShadersStoreWGSL[name212] = shader212; } glowMapGenerationVertexShaderWGSL = { name: name212, shader: shader212 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/glowMapGeneration.fragment.js var glowMapGeneration_fragment_exports = {}; __export(glowMapGeneration_fragment_exports, { glowMapGenerationPixelShaderWGSL: () => glowMapGenerationPixelShaderWGSL }); var name213, shader213, glowMapGenerationPixelShaderWGSL; var init_glowMapGeneration_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/glowMapGeneration.fragment.js"() { init_shaderStore(); init_helperFunctions(); init_clipPlaneFragmentDeclaration(); init_clipPlaneFragment(); name213 = "glowMapGenerationPixelShader"; shader213 = `#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) #include #endif #ifdef DIFFUSE varying vUVDiffuse: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #endif #ifdef OPACITY varying vUVOpacity: vec2f;var opacitySamplerSampler: sampler;var opacitySampler: texture_2d;uniform opacityIntensity: f32; #endif #ifdef EMISSIVE varying vUVEmissive: vec2f;var emissiveSamplerSampler: sampler;var emissiveSampler: texture_2d; #endif #ifdef VERTEXALPHA varying vColor: vec4f; #endif uniform glowColor: vec4f;uniform glowIntensity: f32; #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #include var finalColor: vec4f=uniforms.glowColor; #ifdef DIFFUSE var albedoTexture: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,fragmentInputs.vUVDiffuse); #ifdef DIFFUSE_ISLINEAR albedoTexture=toGammaSpace(albedoTexture); #endif #ifdef GLOW finalColor=vec4f(finalColor.rgb,finalColor.a*albedoTexture.a); #endif #ifdef HIGHLIGHT finalColor=vec4f(finalColor.rgb,albedoTexture.a); #endif #endif #ifdef OPACITY var opacityMap: vec4f=textureSample(opacitySampler,opacitySamplerSampler,fragmentInputs.vUVOpacity); #ifdef OPACITYRGB finalColor=vec4f(finalColor.rgb,finalColor.a*getLuminance(opacityMap.rgb)); #else finalColor=vec4f(finalColor.rgb,finalColor.a*opacityMap.a); #endif finalColor=vec4f(finalColor.rgb,finalColor.a*uniforms.opacityIntensity); #endif #ifdef VERTEXALPHA finalColor=vec4f(finalColor.rgb,finalColor.a*fragmentInputs.vColor.a); #endif #ifdef ALPHATEST if (finalColor.a glowMapGenerationVertexShader }); var name214, shader214, glowMapGenerationVertexShader; var init_glowMapGeneration_vertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/glowMapGeneration.vertex.js"() { init_shaderStore(); init_bonesDeclaration2(); init_bakedVertexAnimationDeclaration2(); init_morphTargetsVertexGlobalDeclaration2(); init_morphTargetsVertexDeclaration2(); init_clipPlaneVertexDeclaration2(); init_instancesDeclaration2(); init_morphTargetsVertexGlobal2(); init_morphTargetsVertex2(); init_instancesVertex2(); init_bonesVertex2(); init_bakedVertexAnimation2(); init_clipPlaneVertex2(); name214 = "glowMapGenerationVertexShader"; shader214 = `attribute vec3 position; #include #include #include #include[0..maxSimultaneousMorphTargets] #include #include uniform mat4 viewProjection;varying vec4 vPosition; #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #ifdef DIFFUSE varying vec2 vUVDiffuse;uniform mat4 diffuseMatrix; #endif #ifdef OPACITY varying vec2 vUVOpacity;uniform mat4 opacityMatrix; #endif #ifdef EMISSIVE varying vec2 vUVEmissive;uniform mat4 emissiveMatrix; #endif #ifdef VERTEXALPHA attribute vec4 color;varying vec4 vColor; #endif #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position; #ifdef UV1 vec2 uvUpdated=uv; #endif #ifdef UV2 vec2 uv2Updated=uv2; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include vec4 worldPos=finalWorld*vec4(positionUpdated,1.0); #ifdef CUBEMAP vPosition=worldPos;gl_Position=viewProjection*finalWorld*vec4(position,1.0); #else vPosition=viewProjection*worldPos;gl_Position=vPosition; #endif #ifdef DIFFUSE #ifdef DIFFUSEUV1 vUVDiffuse=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef DIFFUSEUV2 vUVDiffuse=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0)); #endif #endif #ifdef OPACITY #ifdef OPACITYUV1 vUVOpacity=vec2(opacityMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef OPACITYUV2 vUVOpacity=vec2(opacityMatrix*vec4(uv2Updated,1.0,0.0)); #endif #endif #ifdef EMISSIVE #ifdef EMISSIVEUV1 vUVEmissive=vec2(emissiveMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef EMISSIVEUV2 vUVEmissive=vec2(emissiveMatrix*vec4(uv2Updated,1.0,0.0)); #endif #endif #ifdef VERTEXALPHA vColor=color; #endif #include }`; if (!ShaderStore.ShadersStore[name214]) { ShaderStore.ShadersStore[name214] = shader214; } glowMapGenerationVertexShader = { name: name214, shader: shader214 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/glowMapGeneration.fragment.js var glowMapGeneration_fragment_exports2 = {}; __export(glowMapGeneration_fragment_exports2, { glowMapGenerationPixelShader: () => glowMapGenerationPixelShader }); var name215, shader215, glowMapGenerationPixelShader; var init_glowMapGeneration_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/glowMapGeneration.fragment.js"() { init_shaderStore(); init_helperFunctions2(); init_clipPlaneFragmentDeclaration2(); init_clipPlaneFragment2(); name215 = "glowMapGenerationPixelShader"; shader215 = `#if defined(DIFFUSE_ISLINEAR) || defined(EMISSIVE_ISLINEAR) #include #endif #ifdef DIFFUSE varying vec2 vUVDiffuse;uniform sampler2D diffuseSampler; #endif #ifdef OPACITY varying vec2 vUVOpacity;uniform sampler2D opacitySampler;uniform float opacityIntensity; #endif #ifdef EMISSIVE varying vec2 vUVEmissive;uniform sampler2D emissiveSampler; #endif #ifdef VERTEXALPHA varying vec4 vColor; #endif uniform vec4 glowColor;uniform float glowIntensity; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #include vec4 finalColor=glowColor; #ifdef DIFFUSE vec4 albedoTexture=texture2D(diffuseSampler,vUVDiffuse); #ifdef DIFFUSE_ISLINEAR albedoTexture=toGammaSpace(albedoTexture); #endif #ifdef GLOW finalColor.a*=albedoTexture.a; #endif #ifdef HIGHLIGHT finalColor.a=albedoTexture.a; #endif #endif #ifdef OPACITY vec4 opacityMap=texture2D(opacitySampler,vUVOpacity); #ifdef OPACITYRGB finalColor.a*=getLuminance(opacityMap.rgb); #else finalColor.a*=opacityMap.a; #endif finalColor.a*=opacityIntensity; #endif #ifdef VERTEXALPHA finalColor.a*=vColor.a; #endif #ifdef ALPHATEST if (finalColor.a glowMapMergePixelShaderWGSL }); var name216, shader216, glowMapMergePixelShaderWGSL; var init_glowMapMerge_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/glowMapMerge.fragment.js"() { init_shaderStore(); name216 = "glowMapMergePixelShader"; shader216 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #ifdef EMISSIVE var textureSampler2Sampler: sampler;var textureSampler2: texture_2d; #endif uniform offset: f32; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN var baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV); #ifdef EMISSIVE baseColor+=textureSample(textureSampler2,textureSampler2Sampler,input.vUV);baseColor*=uniforms.offset; #else baseColor=vec4f(baseColor.rgb,abs(uniforms.offset-baseColor.a)); #ifdef STROKE var alpha: f32=smoothstep(.0,.1,baseColor.a);baseColor=vec4f(baseColor.rgb*alpha,alpha); #endif #endif #if LDR baseColor=clamp(baseColor,vec4f(0.),vec4f(1.0)); #endif fragmentOutputs.color=baseColor; #define CUSTOM_FRAGMENT_MAIN_END } `; if (!ShaderStore.ShadersStoreWGSL[name216]) { ShaderStore.ShadersStoreWGSL[name216] = shader216; } glowMapMergePixelShaderWGSL = { name: name216, shader: shader216 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/glowMapMerge.vertex.js var glowMapMerge_vertex_exports = {}; __export(glowMapMerge_vertex_exports, { glowMapMergeVertexShaderWGSL: () => glowMapMergeVertexShaderWGSL }); var name217, shader217, glowMapMergeVertexShaderWGSL; var init_glowMapMerge_vertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/glowMapMerge.vertex.js"() { init_shaderStore(); name217 = "glowMapMergeVertexShader"; shader217 = `attribute position: vec2f;varying vUV: vec2f; #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs {const madd: vec2f= vec2f(0.5,0.5); #define CUSTOM_VERTEX_MAIN_BEGIN vertexOutputs.vUV=input.position*madd+madd;vertexOutputs.position= vec4f(input.position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`; if (!ShaderStore.ShadersStoreWGSL[name217]) { ShaderStore.ShadersStoreWGSL[name217] = shader217; } glowMapMergeVertexShaderWGSL = { name: name217, shader: shader217 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/glowMapMerge.fragment.js var glowMapMerge_fragment_exports2 = {}; __export(glowMapMerge_fragment_exports2, { glowMapMergePixelShader: () => glowMapMergePixelShader }); var name218, shader218, glowMapMergePixelShader; var init_glowMapMerge_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/glowMapMerge.fragment.js"() { init_shaderStore(); name218 = "glowMapMergePixelShader"; shader218 = `varying vec2 vUV;uniform sampler2D textureSampler; #ifdef EMISSIVE uniform sampler2D textureSampler2; #endif uniform float offset; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN vec4 baseColor=texture2D(textureSampler,vUV); #ifdef EMISSIVE baseColor+=texture2D(textureSampler2,vUV);baseColor*=offset; #else baseColor.a=abs(offset-baseColor.a); #ifdef STROKE float alpha=smoothstep(.0,.1,baseColor.a);baseColor.a=alpha;baseColor.rgb=baseColor.rgb*alpha; #endif #endif #if LDR baseColor=clamp(baseColor,0.,1.0); #endif gl_FragColor=baseColor; #define CUSTOM_FRAGMENT_MAIN_END }`; if (!ShaderStore.ShadersStore[name218]) { ShaderStore.ShadersStore[name218] = shader218; } glowMapMergePixelShader = { name: name218, shader: shader218 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/glowMapMerge.vertex.js var glowMapMerge_vertex_exports2 = {}; __export(glowMapMerge_vertex_exports2, { glowMapMergeVertexShader: () => glowMapMergeVertexShader }); var name219, shader219, glowMapMergeVertexShader; var init_glowMapMerge_vertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/glowMapMerge.vertex.js"() { init_shaderStore(); name219 = "glowMapMergeVertexShader"; shader219 = `attribute vec2 position;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vUV=position*madd+madd;gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`; if (!ShaderStore.ShadersStore[name219]) { ShaderStore.ShadersStore[name219] = shader219; } glowMapMergeVertexShader = { name: name219, shader: shader219 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/sharpen.fragment.js var sharpen_fragment_exports = {}; __export(sharpen_fragment_exports, { sharpenPixelShader: () => sharpenPixelShader }); var name220, shader220, sharpenPixelShader; var init_sharpen_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/sharpen.fragment.js"() { init_shaderStore(); name220 = "sharpenPixelShader"; shader220 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec2 screenSize;uniform vec2 sharpnessAmounts; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec2 onePixel=vec2(1.0,1.0)/screenSize;vec4 color=texture2D(textureSampler,vUV);vec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) + texture2D(textureSampler,vUV+onePixel*vec2(-1,0)) + texture2D(textureSampler,vUV+onePixel*vec2(1,0)) + texture2D(textureSampler,vUV+onePixel*vec2(0,1)) - color*4.0;gl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);}`; if (!ShaderStore.ShadersStore[name220]) { ShaderStore.ShadersStore[name220] = shader220; } sharpenPixelShader = { name: name220, shader: shader220 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/sharpen.fragment.js var sharpen_fragment_exports2 = {}; __export(sharpen_fragment_exports2, { sharpenPixelShaderWGSL: () => sharpenPixelShaderWGSL }); var name221, shader221, sharpenPixelShaderWGSL; var init_sharpen_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/sharpen.fragment.js"() { init_shaderStore(); name221 = "sharpenPixelShader"; shader221 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform screenSize: vec2f;uniform sharpnessAmounts: vec2f; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var onePixel: vec2f= vec2f(1.0,1.0)/uniforms.screenSize;var color: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);var edgeDetection: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(0,-1)) + textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(-1,0)) + textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(1,0)) + textureSample(textureSampler,textureSamplerSampler,input.vUV+onePixel*vec2f(0,1)) - color*4.0;fragmentOutputs.color=max(vec4f(color.rgb*uniforms.sharpnessAmounts.y,color.a)-(uniforms.sharpnessAmounts.x* vec4f(edgeDetection.rgb,0)),vec4f(0.));}`; if (!ShaderStore.ShadersStoreWGSL[name221]) { ShaderStore.ShadersStoreWGSL[name221] = shader221; } sharpenPixelShaderWGSL = { name: name221, shader: shader221 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/imageProcessing.fragment.js var imageProcessing_fragment_exports = {}; __export(imageProcessing_fragment_exports, { imageProcessingPixelShaderWGSL: () => imageProcessingPixelShaderWGSL }); var name222, shader222, imageProcessingPixelShaderWGSL; var init_imageProcessing_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/imageProcessing.fragment.js"() { init_shaderStore(); init_imageProcessingDeclaration(); init_helperFunctions(); init_imageProcessingFunctions(); name222 = "imageProcessingPixelShader"; shader222 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d; #include #include #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var result: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV);result=vec4f(max(result.rgb,vec3f(0.)),result.a); #ifdef IMAGEPROCESSING #ifndef FROMLINEARSPACE result=vec4f(toLinearSpaceVec3(result.rgb),result.a); #endif result=applyImageProcessing(result); #else #ifdef FROMLINEARSPACE result=applyImageProcessing(result); #endif #endif fragmentOutputs.color=result;}`; if (!ShaderStore.ShadersStoreWGSL[name222]) { ShaderStore.ShadersStoreWGSL[name222] = shader222; } imageProcessingPixelShaderWGSL = { name: name222, shader: shader222 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/imageProcessing.fragment.js var imageProcessing_fragment_exports2 = {}; __export(imageProcessing_fragment_exports2, { imageProcessingPixelShader: () => imageProcessingPixelShader }); var name223, shader223, imageProcessingPixelShader; var init_imageProcessing_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/imageProcessing.fragment.js"() { init_shaderStore(); init_imageProcessingDeclaration2(); init_helperFunctions2(); init_imageProcessingFunctions2(); name223 = "imageProcessingPixelShader"; shader223 = `varying vec2 vUV;uniform sampler2D textureSampler; #include #include #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec4 result=texture2D(textureSampler,vUV);result.rgb=max(result.rgb,vec3(0.)); #ifdef IMAGEPROCESSING #ifndef FROMLINEARSPACE result.rgb=toLinearSpace(result.rgb); #endif result=applyImageProcessing(result); #else #ifdef FROMLINEARSPACE result=applyImageProcessing(result); #endif #endif gl_FragColor=result;}`; if (!ShaderStore.ShadersStore[name223]) { ShaderStore.ShadersStore[name223] = shader223; } imageProcessingPixelShader = { name: name223, shader: shader223 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/chromaticAberration.fragment.js var chromaticAberration_fragment_exports = {}; __export(chromaticAberration_fragment_exports, { chromaticAberrationPixelShaderWGSL: () => chromaticAberrationPixelShaderWGSL }); var name224, shader224, chromaticAberrationPixelShaderWGSL; var init_chromaticAberration_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/chromaticAberration.fragment.js"() { init_shaderStore(); name224 = "chromaticAberrationPixelShader"; shader224 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform chromatic_aberration: f32;uniform radialIntensity: f32;uniform direction: vec2f;uniform centerPosition: vec2f;uniform screen_width: f32;uniform screen_height: f32; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var centered_screen_pos: vec2f= vec2f(input.vUV.x-uniforms.centerPosition.x,input.vUV.y-uniforms.centerPosition.y);var directionOfEffect: vec2f=uniforms.direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);} var radius2: f32=centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;var radius: f32=sqrt(radius2);var ref_indices: vec3f= vec3f(-0.3,0.0,0.3);var ref_shiftX: f32=uniforms.chromatic_aberration*pow(radius,uniforms.radialIntensity)*directionOfEffect.x/uniforms.screen_width;var ref_shiftY: f32=uniforms.chromatic_aberration*pow(radius,uniforms.radialIntensity)*directionOfEffect.y/uniforms.screen_height;var ref_coords_r: vec2f=vec2f(input.vUV.x+ref_indices.r*ref_shiftX,input.vUV.y+ref_indices.r*ref_shiftY*0.5);var ref_coords_g: vec2f=vec2f(input.vUV.x+ref_indices.g*ref_shiftX,input.vUV.y+ref_indices.g*ref_shiftY*0.5);var ref_coords_b: vec2f=vec2f(input.vUV.x+ref_indices.b*ref_shiftX,input.vUV.y+ref_indices.b*ref_shiftY*0.5);var r=textureSample(textureSampler,textureSamplerSampler,ref_coords_r);var g=textureSample(textureSampler,textureSamplerSampler,ref_coords_g);var b=textureSample(textureSampler,textureSamplerSampler,ref_coords_b);var a=clamp(r.a+g.a+b.a,0.,1.);fragmentOutputs.color=vec4f(r.r,g.g,b.b,a);}`; if (!ShaderStore.ShadersStoreWGSL[name224]) { ShaderStore.ShadersStoreWGSL[name224] = shader224; } chromaticAberrationPixelShaderWGSL = { name: name224, shader: shader224 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/chromaticAberration.fragment.js var chromaticAberration_fragment_exports2 = {}; __export(chromaticAberration_fragment_exports2, { chromaticAberrationPixelShader: () => chromaticAberrationPixelShader }); var name225, shader225, chromaticAberrationPixelShader; var init_chromaticAberration_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/chromaticAberration.fragment.js"() { init_shaderStore(); name225 = "chromaticAberrationPixelShader"; shader225 = `uniform sampler2D textureSampler; uniform float chromatic_aberration;uniform float radialIntensity;uniform vec2 direction;uniform vec2 centerPosition;uniform float screen_width;uniform float screen_height;varying vec2 vUV; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {vec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);vec2 directionOfEffect=direction;if(directionOfEffect.x==0. && directionOfEffect.y==0.){directionOfEffect=normalize(centered_screen_pos);} float radius2=centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;float radius=sqrt(radius2);vec3 ref_indices=vec3(-0.3,0.0,0.3);float ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;float ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;vec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);vec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);vec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);vec4 r=texture2D(textureSampler,ref_coords_r);vec4 g=texture2D(textureSampler,ref_coords_g);vec4 b=texture2D(textureSampler,ref_coords_b);float a=clamp(r.a+g.a+b.a,0.,1.);gl_FragColor=vec4(r.r,g.g,b.b,a);}`; if (!ShaderStore.ShadersStore[name225]) { ShaderStore.ShadersStore[name225] = shader225; } chromaticAberrationPixelShader = { name: name225, shader: shader225 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/grain.fragment.js var grain_fragment_exports = {}; __export(grain_fragment_exports, { grainPixelShaderWGSL: () => grainPixelShaderWGSL }); var name226, shader226, grainPixelShaderWGSL; var init_grain_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/grain.fragment.js"() { init_shaderStore(); init_helperFunctions(); name226 = "grainPixelShader"; shader226 = `#include varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform intensity: f32;uniform animatedSeed: f32; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var seed: vec2f=input.vUV*uniforms.animatedSeed;var grain: f32=dither(seed,uniforms.intensity);var lum: f32=getLuminance(fragmentOutputs.color.rgb);var grainAmount: f32=(cos(-PI+(lum*PI*2.))+1.)/2.;fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb+grain*grainAmount,fragmentOutputs.color.a);fragmentOutputs.color=vec4f(max(fragmentOutputs.color.rgb,vec3f(0.0)),fragmentOutputs.color.a);}`; if (!ShaderStore.ShadersStoreWGSL[name226]) { ShaderStore.ShadersStoreWGSL[name226] = shader226; } grainPixelShaderWGSL = { name: name226, shader: shader226 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/grain.fragment.js var grain_fragment_exports2 = {}; __export(grain_fragment_exports2, { grainPixelShader: () => grainPixelShader }); var name227, shader227, grainPixelShader; var init_grain_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/grain.fragment.js"() { init_shaderStore(); init_helperFunctions2(); name227 = "grainPixelShader"; shader227 = `#include uniform sampler2D textureSampler; uniform float intensity;uniform float animatedSeed;varying vec2 vUV; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(textureSampler,vUV);vec2 seed=vUV*(animatedSeed);float grain=dither(seed,intensity);float lum=getLuminance(gl_FragColor.rgb);float grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;gl_FragColor.rgb+=grain*grainAmount;gl_FragColor.rgb=max(gl_FragColor.rgb,0.0);}`; if (!ShaderStore.ShadersStore[name227]) { ShaderStore.ShadersStore[name227] = shader227; } grainPixelShader = { name: name227, shader: shader227 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/fxaa.fragment.js var fxaa_fragment_exports = {}; __export(fxaa_fragment_exports, { fxaaPixelShaderWGSL: () => fxaaPixelShaderWGSL }); var name228, shader228, fxaaPixelShaderWGSL; var init_fxaa_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/fxaa.fragment.js"() { init_shaderStore(); name228 = "fxaaPixelShader"; shader228 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform texelSize: vec2f;varying sampleCoordS: vec2f;varying sampleCoordE: vec2f;varying sampleCoordN: vec2f;varying sampleCoordW: vec2f;varying sampleCoordNW: vec2f;varying sampleCoordSE: vec2f;varying sampleCoordNE: vec2f;varying sampleCoordSW: vec2f;const fxaaQualitySubpix: f32=1.0;const fxaaQualityEdgeThreshold: f32=0.166;const fxaaQualityEdgeThresholdMin: f32=0.0833;const kLumaCoefficients: vec3f= vec3f(0.2126,0.7152,0.0722);fn FxaaLuma(rgba: vec4f)->f32 {return dot(rgba.rgb,kLumaCoefficients);} @fragment fn main(input: FragmentInputs)->FragmentOutputs {var posM: vec2f;posM.x=input.vUV.x;posM.y=input.vUV.y;var rgbyM: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var lumaM: f32=FxaaLuma(rgbyM);var lumaS: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordS,0.0));var lumaE: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordE,0.0));var lumaN: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordN,0.0));var lumaW: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,input.sampleCoordW,0.0));var maxSM: f32=max(lumaS,lumaM);var minSM: f32=min(lumaS,lumaM);var maxESM: f32=max(lumaE,maxSM);var minESM: f32=min(lumaE,minSM);var maxWN: f32=max(lumaN,lumaW);var minWN: f32=min(lumaN,lumaW);var rangeMax: f32=max(maxWN,maxESM);var rangeMin: f32=min(minWN,minESM);var rangeMaxScaled: f32=rangeMax*fxaaQualityEdgeThreshold;var range: f32=rangeMax-rangeMin;var rangeMaxClamped: f32=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); #ifndef MALI if(range=edgeVert;var subpixA: f32=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) {lumaN=lumaW;} if (!horzSpan) {lumaS=lumaE;} if (horzSpan) {lengthSign=uniforms.texelSize.y;} var subpixB: f32=(subpixA*(1.0/12.0))-lumaM;var gradientN: f32=lumaN-lumaM;var gradientS: f32=lumaS-lumaM;var lumaNN: f32=lumaN+lumaM;var lumaSS: f32=lumaS+lumaM;var pairN: bool=abs(gradientN)>=abs(gradientS);var gradient: f32=max(abs(gradientN),abs(gradientS));if (pairN) {lengthSign=-lengthSign;} var subpixC: f32=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);var posB: vec2f;posB.x=posM.x;posB.y=posM.y;var offNP: vec2f;offNP.x=select(uniforms.texelSize.x,0.0,(!horzSpan));offNP.y=select(uniforms.texelSize.y,0.0,(horzSpan));if (!horzSpan) {posB.x+=lengthSign*0.5;} if (horzSpan) {posB.y+=lengthSign*0.5;} var posN: vec2f;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;var posP: vec2f;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;var subpixD: f32=((-2.0)*subpixC)+3.0;var lumaEndN: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posN,0.0));var subpixE: f32=subpixC*subpixC;var lumaEndP: f32=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posP,0.0));if (!pairN) {lumaNN=lumaSS;} var gradientScaled: f32=gradient*1.0/4.0;var lumaMM: f32=lumaM-lumaNN*0.5;var subpixF: f32=subpixD*subpixE;var lumaMLTZero: bool=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;var doneN: bool=abs(lumaEndN)>=gradientScaled;var doneP: bool=abs(lumaEndP)>=gradientScaled;if (!doneN) {posN.x-=offNP.x*3.0;} if (!doneN) {posN.y-=offNP.y*3.0;} var doneNP: bool=(!doneN) || (!doneP);if (!doneP) {posP.x+=offNP.x*3.0;} if (!doneP) {posP.y+=offNP.y*3.0;} if (doneNP) {if (!doneN) {lumaEndN=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posN.xy,0.0));} if (!doneP) {lumaEndP=FxaaLuma(textureSampleLevel(textureSampler,textureSamplerSampler,posP.xy,0.0));} if (!doneN) {lumaEndN=lumaEndN-lumaNN*0.5;} if (!doneP) {lumaEndP=lumaEndP-lumaNN*0.5;} doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) {posN.x-=offNP.x*12.0;} if (!doneN) {posN.y-=offNP.y*12.0;} doneNP=(!doneN) || (!doneP);if (!doneP) {posP.x+=offNP.x*12.0;} if (!doneP) {posP.y+=offNP.y*12.0;}} var dstN: f32=posM.x-posN.x;var dstP: f32=posP.x-posM.x;if (!horzSpan) {dstN=posM.y-posN.y;} if (!horzSpan) {dstP=posP.y-posM.y;} var goodSpanN: bool=(lumaEndN<0.0) != lumaMLTZero;var spanLength: f32=(dstP+dstN);var goodSpanP: bool=(lumaEndP<0.0) != lumaMLTZero;var spanLengthRcp: f32=1.0/spanLength;var directionN: bool=dstN fxaaVertexShaderWGSL }); var name229, shader229, fxaaVertexShaderWGSL; var init_fxaa_vertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/fxaa.vertex.js"() { init_shaderStore(); name229 = "fxaaVertexShader"; shader229 = `attribute position: vec2f;uniform texelSize: vec2f;varying vUV: vec2f;varying sampleCoordS: vec2f;varying sampleCoordE: vec2f;varying sampleCoordN: vec2f;varying sampleCoordW: vec2f;varying sampleCoordNW: vec2f;varying sampleCoordSE: vec2f;varying sampleCoordNE: vec2f;varying sampleCoordSW: vec2f;const madd: vec2f= vec2f(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN vertexOutputs.vUV=(input.position*madd+madd);vertexOutputs.sampleCoordS=vertexOutputs.vUV+ vec2f( 0.0,1.0)*uniforms.texelSize;vertexOutputs.sampleCoordE=vertexOutputs.vUV+ vec2f( 1.0,0.0)*uniforms.texelSize;vertexOutputs.sampleCoordN=vertexOutputs.vUV+ vec2f( 0.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordW=vertexOutputs.vUV+ vec2f(-1.0,0.0)*uniforms.texelSize;vertexOutputs.sampleCoordNW=vertexOutputs.vUV+ vec2f(-1.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordSE=vertexOutputs.vUV+ vec2f( 1.0,1.0)*uniforms.texelSize;vertexOutputs.sampleCoordNE=vertexOutputs.vUV+ vec2f( 1.0,-1.0)*uniforms.texelSize;vertexOutputs.sampleCoordSW=vertexOutputs.vUV+ vec2f(-1.0,1.0)*uniforms.texelSize;vertexOutputs.position=vec4f(input.position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`; if (!ShaderStore.ShadersStoreWGSL[name229]) { ShaderStore.ShadersStoreWGSL[name229] = shader229; } fxaaVertexShaderWGSL = { name: name229, shader: shader229 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/fxaa.fragment.js var fxaa_fragment_exports2 = {}; __export(fxaa_fragment_exports2, { fxaaPixelShader: () => fxaaPixelShader }); var name230, shader230, fxaaPixelShader; var init_fxaa_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/fxaa.fragment.js"() { init_shaderStore(); name230 = "fxaaPixelShader"; shader230 = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) #else #define TEXTUREFUNC(s,c,b) texture2D(s,c,b) #endif uniform sampler2D textureSampler;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const float fxaaQualitySubpix=1.0;const float fxaaQualityEdgeThreshold=0.166;const float fxaaQualityEdgeThresholdMin=0.0833;const vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722); #define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients) void main(){vec2 posM;posM.x=vUV.x;posM.y=vUV.y;vec4 rgbyM=TEXTUREFUNC(textureSampler,vUV,0.0);float lumaM=FxaaLuma(rgbyM);float lumaS=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordS,0.0));float lumaE=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordE,0.0));float lumaN=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordN,0.0));float lumaW=FxaaLuma(TEXTUREFUNC(textureSampler,sampleCoordW,0.0));float maxSM=max(lumaS,lumaM);float minSM=min(lumaS,lumaM);float maxESM=max(lumaE,maxSM);float minESM=min(lumaE,minSM);float maxWN=max(lumaN,lumaW);float minWN=min(lumaN,lumaW);float rangeMax=max(maxWN,maxESM);float rangeMin=min(minWN,minESM);float rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;float range=rangeMax-rangeMin;float rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled); #ifndef MALI if(range=edgeVert;float subpixA=subpixNSWE*2.0+subpixNWSWNESE;if (!horzSpan) {lumaN=lumaW;} if (!horzSpan) {lumaS=lumaE;} if (horzSpan) {lengthSign=texelSize.y;} float subpixB=(subpixA*(1.0/12.0))-lumaM;float gradientN=lumaN-lumaM;float gradientS=lumaS-lumaM;float lumaNN=lumaN+lumaM;float lumaSS=lumaS+lumaM;bool pairN=abs(gradientN)>=abs(gradientS);float gradient=max(abs(gradientN),abs(gradientS));if (pairN) {lengthSign=-lengthSign;} float subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);vec2 posB;posB.x=posM.x;posB.y=posM.y;vec2 offNP;offNP.x=(!horzSpan) ? 0.0 : texelSize.x;offNP.y=(horzSpan) ? 0.0 : texelSize.y;if (!horzSpan) {posB.x+=lengthSign*0.5;} if (horzSpan) {posB.y+=lengthSign*0.5;} vec2 posN;posN.x=posB.x-offNP.x*1.5;posN.y=posB.y-offNP.y*1.5;vec2 posP;posP.x=posB.x+offNP.x*1.5;posP.y=posB.y+offNP.y*1.5;float subpixD=((-2.0)*subpixC)+3.0;float lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN,0.0));float subpixE=subpixC*subpixC;float lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP,0.0));if (!pairN) {lumaNN=lumaSS;} float gradientScaled=gradient*1.0/4.0;float lumaMM=lumaM-lumaNN*0.5;float subpixF=subpixD*subpixE;bool lumaMLTZero=lumaMM<0.0;lumaEndN-=lumaNN*0.5;lumaEndP-=lumaNN*0.5;bool doneN=abs(lumaEndN)>=gradientScaled;bool doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) {posN.x-=offNP.x*3.0;} if (!doneN) {posN.y-=offNP.y*3.0;} bool doneNP=(!doneN) || (!doneP);if (!doneP) {posP.x+=offNP.x*3.0;} if (!doneP) {posP.y+=offNP.y*3.0;} if (doneNP) {if (!doneN) lumaEndN=FxaaLuma(TEXTUREFUNC(textureSampler,posN.xy,0.0));if (!doneP) lumaEndP=FxaaLuma(TEXTUREFUNC(textureSampler,posP.xy,0.0));if (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;if (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;doneN=abs(lumaEndN)>=gradientScaled;doneP=abs(lumaEndP)>=gradientScaled;if (!doneN) posN.x-=offNP.x*12.0;if (!doneN) posN.y-=offNP.y*12.0;doneNP=(!doneN) || (!doneP);if (!doneP) posP.x+=offNP.x*12.0;if (!doneP) posP.y+=offNP.y*12.0;} float dstN=posM.x-posN.x;float dstP=posP.x-posM.x;if (!horzSpan) {dstN=posM.y-posN.y;} if (!horzSpan) {dstP=posP.y-posM.y;} bool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;float spanLength=(dstP+dstN);bool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;float spanLengthRcp=1.0/spanLength;bool directionN=dstN fxaaVertexShader }); var name231, shader231, fxaaVertexShader; var init_fxaa_vertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/fxaa.vertex.js"() { init_shaderStore(); name231 = "fxaaVertexShader"; shader231 = `attribute vec2 position;uniform vec2 texelSize;varying vec2 vUV;varying vec2 sampleCoordS;varying vec2 sampleCoordE;varying vec2 sampleCoordN;varying vec2 sampleCoordW;varying vec2 sampleCoordNW;varying vec2 sampleCoordSE;varying vec2 sampleCoordNE;varying vec2 sampleCoordSW;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vUV=(position*madd+madd);sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;gl_Position=vec4(position,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`; if (!ShaderStore.ShadersStore[name231]) { ShaderStore.ShadersStore[name231] = shader231; } fxaaVertexShader = { name: name231, shader: shader231 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/circleOfConfusion.fragment.js var circleOfConfusion_fragment_exports = {}; __export(circleOfConfusion_fragment_exports, { circleOfConfusionPixelShaderWGSL: () => circleOfConfusionPixelShaderWGSL }); var name232, shader232, circleOfConfusionPixelShaderWGSL; var init_circleOfConfusion_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/circleOfConfusion.fragment.js"() { init_shaderStore(); name232 = "circleOfConfusionPixelShader"; shader232 = `varying vUV: vec2f;var depthSamplerSampler: sampler;var depthSampler: texture_2d; #ifndef COC_DEPTH_NOT_NORMALIZED uniform cameraMinMaxZ: vec2f; #endif uniform focusDistance: f32;uniform cocPrecalculation: f32; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var depth: f32=textureSample(depthSampler,depthSamplerSampler,input.vUV).r; #define CUSTOM_COC_DEPTH #ifdef COC_DEPTH_NOT_NORMALIZED let pixelDistance=depth*1000.0; #else let pixelDistance: f32=(uniforms.cameraMinMaxZ.x+uniforms.cameraMinMaxZ.y*depth)*1000.0; #endif #define CUSTOM_COC_PIXELDISTANCE var coc: f32=abs(uniforms.cocPrecalculation*((uniforms.focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);fragmentOutputs.color= vec4f(coc,coc,coc,1.0);} `; if (!ShaderStore.ShadersStoreWGSL[name232]) { ShaderStore.ShadersStoreWGSL[name232] = shader232; } circleOfConfusionPixelShaderWGSL = { name: name232, shader: shader232 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/circleOfConfusion.fragment.js var circleOfConfusion_fragment_exports2 = {}; __export(circleOfConfusion_fragment_exports2, { circleOfConfusionPixelShader: () => circleOfConfusionPixelShader }); var name233, shader233, circleOfConfusionPixelShader; var init_circleOfConfusion_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/circleOfConfusion.fragment.js"() { init_shaderStore(); name233 = "circleOfConfusionPixelShader"; shader233 = `uniform sampler2D depthSampler;varying vec2 vUV; #ifndef COC_DEPTH_NOT_NORMALIZED uniform vec2 cameraMinMaxZ; #endif uniform float focusDistance;uniform float cocPrecalculation; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {float depth=texture2D(depthSampler,vUV).r; #define CUSTOM_COC_DEPTH #ifdef COC_DEPTH_NOT_NORMALIZED float pixelDistance=depth*1000.0; #else float pixelDistance=(cameraMinMaxZ.x+cameraMinMaxZ.y*depth)*1000.0; #endif #define CUSTOM_COC_PIXELDISTANCE float coc=abs(cocPrecalculation*((focusDistance-pixelDistance)/pixelDistance));coc=clamp(coc,0.0,1.0);gl_FragColor=vec4(coc,coc,coc,1.0);} `; if (!ShaderStore.ShadersStore[name233]) { ShaderStore.ShadersStore[name233] = shader233; } circleOfConfusionPixelShader = { name: name233, shader: shader233 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/depthOfFieldMerge.fragment.js var depthOfFieldMerge_fragment_exports = {}; __export(depthOfFieldMerge_fragment_exports, { depthOfFieldMergePixelShaderWGSL: () => depthOfFieldMergePixelShaderWGSL }); var name234, shader234, depthOfFieldMergePixelShaderWGSL; var init_depthOfFieldMerge_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/depthOfFieldMerge.fragment.js"() { init_shaderStore(); name234 = "depthOfFieldMergePixelShader"; shader234 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var circleOfConfusionSamplerSampler: sampler;var circleOfConfusionSampler: texture_2d;var blurStep0Sampler: sampler;var blurStep0: texture_2d; #if BLUR_LEVEL>0 var blurStep1Sampler: sampler;var blurStep1: texture_2d; #endif #if BLUR_LEVEL>1 var blurStep2Sampler: sampler;var blurStep2: texture_2d; #endif #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {var coc: f32=textureSampleLevel(circleOfConfusionSampler,circleOfConfusionSamplerSampler,input.vUV,0.0).r; #if BLUR_LEVEL==0 var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred0,coc); #endif #if BLUR_LEVEL==1 if(coc<0.5){var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred1,coc/0.5);}else{var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred1,blurred0,(coc-0.5)/0.5);} #endif #if BLUR_LEVEL==2 if(coc<0.33){var original: vec4f=textureSampleLevel(textureSampler,textureSamplerSampler,input.vUV,0.0);var blurred2: vec4f=textureSampleLevel(blurStep2,blurStep2Sampler,input.vUV,0.0);fragmentOutputs.color=mix(original,blurred2,coc/0.33);}else if(coc<0.66){var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);var blurred2: vec4f=textureSampleLevel(blurStep2,blurStep2Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{var blurred0: vec4f=textureSampleLevel(blurStep0,blurStep0Sampler,input.vUV,0.0);var blurred1: vec4f=textureSampleLevel(blurStep1,blurStep1Sampler,input.vUV,0.0);fragmentOutputs.color=mix(blurred1,blurred0,(coc-0.66)/0.34);} #endif } `; if (!ShaderStore.ShadersStoreWGSL[name234]) { ShaderStore.ShadersStoreWGSL[name234] = shader234; } depthOfFieldMergePixelShaderWGSL = { name: name234, shader: shader234 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/depthOfFieldMerge.fragment.js var depthOfFieldMerge_fragment_exports2 = {}; __export(depthOfFieldMerge_fragment_exports2, { depthOfFieldMergePixelShader: () => depthOfFieldMergePixelShader }); var name235, shader235, depthOfFieldMergePixelShader; var init_depthOfFieldMerge_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/depthOfFieldMerge.fragment.js"() { init_shaderStore(); name235 = "depthOfFieldMergePixelShader"; shader235 = `#if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,lod) texture2DLodEXT(s,c,lod) #else #define TEXTUREFUNC(s,c,bias) texture2D(s,c,bias) #endif uniform sampler2D textureSampler;varying vec2 vUV;uniform sampler2D circleOfConfusionSampler;uniform sampler2D blurStep0; #if BLUR_LEVEL>0 uniform sampler2D blurStep1; #endif #if BLUR_LEVEL>1 uniform sampler2D blurStep2; #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {float coc=TEXTUREFUNC(circleOfConfusionSampler,vUV,0.0).r; #if BLUR_LEVEL==0 vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);gl_FragColor=mix(original,blurred0,coc); #endif #if BLUR_LEVEL==1 if(coc<0.5){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(original,blurred1,coc/0.5);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);} #endif #if BLUR_LEVEL==2 if(coc<0.33){vec4 original=TEXTUREFUNC(textureSampler,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(original,blurred2,coc/0.33);}else if(coc<0.66){vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);vec4 blurred2=TEXTUREFUNC(blurStep2,vUV,0.0);gl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);}else{vec4 blurred0=TEXTUREFUNC(blurStep0,vUV,0.0);vec4 blurred1=TEXTUREFUNC(blurStep1,vUV,0.0);gl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);} #endif } `; if (!ShaderStore.ShadersStore[name235]) { ShaderStore.ShadersStore[name235] = shader235; } depthOfFieldMergePixelShader = { name: name235, shader: shader235 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/extractHighlights.fragment.js var extractHighlights_fragment_exports = {}; __export(extractHighlights_fragment_exports, { extractHighlightsPixelShaderWGSL: () => extractHighlightsPixelShaderWGSL }); var name236, shader236, extractHighlightsPixelShaderWGSL; var init_extractHighlights_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/extractHighlights.fragment.js"() { init_shaderStore(); init_helperFunctions(); name236 = "extractHighlightsPixelShader"; shader236 = `#include varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform threshold: f32;uniform exposure: f32; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var luma: f32=dot(LuminanceEncodeApprox,fragmentOutputs.color.rgb*uniforms.exposure);fragmentOutputs.color=vec4f(step(uniforms.threshold,luma)*fragmentOutputs.color.rgb,fragmentOutputs.color.a);}`; if (!ShaderStore.ShadersStoreWGSL[name236]) { ShaderStore.ShadersStoreWGSL[name236] = shader236; } extractHighlightsPixelShaderWGSL = { name: name236, shader: shader236 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/extractHighlights.fragment.js var extractHighlights_fragment_exports2 = {}; __export(extractHighlights_fragment_exports2, { extractHighlightsPixelShader: () => extractHighlightsPixelShader }); var name237, shader237, extractHighlightsPixelShader; var init_extractHighlights_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/extractHighlights.fragment.js"() { init_shaderStore(); init_helperFunctions2(); name237 = "extractHighlightsPixelShader"; shader237 = `#include varying vec2 vUV;uniform sampler2D textureSampler;uniform float threshold;uniform float exposure; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(textureSampler,vUV);float luma=dot(LuminanceEncodeApprox,gl_FragColor.rgb*exposure);gl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;}`; if (!ShaderStore.ShadersStore[name237]) { ShaderStore.ShadersStore[name237] = shader237; } extractHighlightsPixelShader = { name: name237, shader: shader237 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/bloomMerge.fragment.js var bloomMerge_fragment_exports = {}; __export(bloomMerge_fragment_exports, { bloomMergePixelShaderWGSL: () => bloomMergePixelShaderWGSL }); var name238, shader238, bloomMergePixelShaderWGSL; var init_bloomMerge_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/bloomMerge.fragment.js"() { init_shaderStore(); name238 = "bloomMergePixelShader"; shader238 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;var bloomBlurSampler: sampler;var bloomBlur: texture_2d;uniform bloomWeight: f32; #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs {fragmentOutputs.color=textureSample(textureSampler,textureSamplerSampler,input.vUV);var blurred: vec3f=textureSample(bloomBlur,bloomBlurSampler,input.vUV).rgb;fragmentOutputs.color=vec4f(fragmentOutputs.color.rgb+(blurred.rgb*uniforms.bloomWeight),fragmentOutputs.color.a);} `; if (!ShaderStore.ShadersStoreWGSL[name238]) { ShaderStore.ShadersStoreWGSL[name238] = shader238; } bloomMergePixelShaderWGSL = { name: name238, shader: shader238 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/bloomMerge.fragment.js var bloomMerge_fragment_exports2 = {}; __export(bloomMerge_fragment_exports2, { bloomMergePixelShader: () => bloomMergePixelShader }); var name239, shader239, bloomMergePixelShader; var init_bloomMerge_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/bloomMerge.fragment.js"() { init_shaderStore(); name239 = "bloomMergePixelShader"; shader239 = `uniform sampler2D textureSampler;uniform sampler2D bloomBlur;varying vec2 vUV;uniform float bloomWeight; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) {gl_FragColor=texture2D(textureSampler,vUV);vec3 blurred=texture2D(bloomBlur,vUV).rgb;gl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); } `; if (!ShaderStore.ShadersStore[name239]) { ShaderStore.ShadersStore[name239] = shader239; } bloomMergePixelShader = { name: name239, shader: shader239 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/particles.vertex.js var particles_vertex_exports = {}; __export(particles_vertex_exports, { particlesVertexShaderWGSL: () => particlesVertexShaderWGSL }); var name240, shader240, particlesVertexShaderWGSL; var init_particles_vertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/particles.vertex.js"() { init_shaderStore(); init_clipPlaneVertexDeclaration(); init_fogVertexDeclaration(); init_logDepthDeclaration(); init_clipPlaneVertex(); init_fogVertex(); init_logDepthVertex(); name240 = "particlesVertexShader"; shader240 = `attribute position: vec3f;attribute color: vec4f;attribute angle: f32;attribute size: vec2f; #ifdef ANIMATESHEET attribute cellIndex: f32; #endif #ifndef BILLBOARD attribute direction: vec3f; #endif #ifdef BILLBOARDSTRETCHED attribute direction: vec3f; #endif #ifdef RAMPGRADIENT attribute remapData: vec4f; #endif attribute offset: vec2f;uniform view: mat4x4f;uniform projection: mat4x4f;uniform translationPivot: vec2f; #ifdef ANIMATESHEET uniform particlesInfos: vec3f; #endif varying vUV: vec2f;varying vColor: vec4f; #ifdef RAMPGRADIENT varying remapRanges: vec4f; #endif #if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) uniform invView: mat4x4f; #endif #include #include #include #ifdef BILLBOARD uniform eyePosition: vec3f; #endif fn rotate(yaxis: vec3f,rotatedCorner: vec3f)->vec3f {var xaxis: vec3f=normalize(cross( vec3f(0.,1.0,0.),yaxis));var zaxis: vec3f=normalize(cross(yaxis,xaxis));var row0: vec3f= vec3f(xaxis.x,xaxis.y,xaxis.z);var row1: vec3f= vec3f(yaxis.x,yaxis.y,yaxis.z);var row2: vec3f= vec3f(zaxis.x,zaxis.y,zaxis.z);var rotMatrix: mat3x3f= mat3x3f(row0,row1,row2);var alignedCorner: vec3f=rotMatrix*rotatedCorner;return vertexInputs.position+alignedCorner;} #ifdef BILLBOARDSTRETCHED fn rotateAlign(toCamera: vec3f,rotatedCorner: vec3f)->vec3f {var normalizedToCamera: vec3f=normalize(toCamera);var normalizedCrossDirToCamera: vec3f=normalize(cross(normalize(vertexInputs.direction),normalizedToCamera));var row0: vec3f= vec3f(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);var row2: vec3f= vec3f(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); #ifdef BILLBOARDSTRETCHED_LOCAL var row1: vec3f=vertexInputs.direction; #else var crossProduct: vec3f=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));var row1: vec3f= vec3f(crossProduct.x,crossProduct.y,crossProduct.z); #endif var rotMatrix: mat3x3f= mat3x3f(row0,row1,row2);var alignedCorner: vec3f=rotMatrix*rotatedCorner;return vertexInputs.position+alignedCorner;} #endif #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN var cornerPos: vec2f;var vPositionW: vec3f;cornerPos=( vec2f(input.offset.x-0.5,input.offset.y -0.5)-uniforms.translationPivot)*input.size; #ifdef BILLBOARD var rotatedCorner: vec3f; #ifdef BILLBOARDY rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.z=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.y=0.;var yaxis: vec3f=input.position-uniforms.eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);var viewPos: vec3f=(uniforms.view* vec4f(vPositionW,1.0)).xyz; #elif defined(BILLBOARDSTRETCHED) rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.y=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.z=0.;var toCamera: vec3f=input.position-uniforms.eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);var viewPos: vec3f=(uniforms.view* vec4f(vPositionW,1.0)).xyz; #else rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.y=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.z=0.;var viewPos: vec3f=(uniforms.view* vec4f(input.position,1.0)).xyz+rotatedCorner;vPositionW=(uniforms.invView* vec4f(viewPos,1)).xyz; #endif #ifdef RAMPGRADIENT vertexOutputs.remapRanges=input.remapData; #endif vertexOutputs.position=uniforms.projection* vec4f(viewPos,1.0); #else var rotatedCorner: vec3f;rotatedCorner.x=cornerPos.x*cos(input.angle)-cornerPos.y*sin(input.angle)+uniforms.translationPivot.x;rotatedCorner.z=cornerPos.x*sin(input.angle)+cornerPos.y*cos(input.angle)+uniforms.translationPivot.y;rotatedCorner.y=0.;var yaxis: vec3f=normalize(vertexInputs.direction);vPositionW=rotate(yaxis,rotatedCorner);vertexOutputs.position=uniforms.projection*uniforms.view* vec4f(vPositionW,1.0); #endif vertexOutputs.vColor=input.color; #ifdef ANIMATESHEET var rowOffset: f32=floor(input.cellIndex*uniforms.particlesInfos.z);var columnOffset: f32=input.cellIndex-rowOffset/uniforms.particlesInfos.z;var uvScale: vec2f=uniforms.particlesInfos.xy;var uvOffset: vec2f= vec2f(input.offset.x ,1.0-input.offset.y);vertexOutputs.vUV=(uvOffset+ vec2f(columnOffset,rowOffset))*uvScale; #else vertexOutputs.vUV=input.offset; #endif #if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG) var worldPos: vec4f= vec4f(vPositionW,1.0); #endif #include #include #include #define CUSTOM_VERTEX_MAIN_END }`; if (!ShaderStore.ShadersStoreWGSL[name240]) { ShaderStore.ShadersStoreWGSL[name240] = shader240; } particlesVertexShaderWGSL = { name: name240, shader: shader240 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/particles.fragment.js var particles_fragment_exports = {}; __export(particles_fragment_exports, { particlesPixelShaderWGSL: () => particlesPixelShaderWGSL }); var name241, shader241, particlesPixelShaderWGSL; var init_particles_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/particles.fragment.js"() { init_shaderStore(); init_clipPlaneFragmentDeclaration(); init_imageProcessingDeclaration(); init_logDepthDeclaration(); init_helperFunctions(); init_imageProcessingFunctions(); init_fogFragmentDeclaration(); init_clipPlaneFragment(); init_logDepthFragment(); init_fogFragment(); name241 = "particlesPixelShader"; shader241 = `varying vUV: vec2f;varying vColor: vec4f;uniform textureMask: vec4f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #include #include #include #include #include #ifdef RAMPGRADIENT varying remapRanges: vec4f;var rampSamplerSampler: sampler;var rampSampler: texture_2d; #endif #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include var textureColor: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,input.vUV);var baseColor: vec4f=(textureColor*uniforms.textureMask+( vec4f(1.,1.,1.,1.)-uniforms.textureMask))*input.vColor; #ifdef RAMPGRADIENT var alpha: f32=baseColor.a;var remappedColorIndex: f32=clamp((alpha-input.remapRanges.x)/input.remapRanges.y,0.0,1.0);var rampColor: vec4f=textureSample(rampSampler,rampSamplerSampler,vec2f(1.0-remappedColorIndex,0.));baseColor=vec4f(baseColor.rgb*rampColor.rgb,baseColor.a);var finalAlpha: f32=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-input.remapRanges.z)/input.remapRanges.w,0.0,1.0); #endif #ifdef BLENDMULTIPLYMODE var sourceAlpha: f32=input.vColor.a*textureColor.a;baseColor=vec4f(baseColor.rgb*sourceAlpha+ vec3f(1.0)*(1.0-sourceAlpha),baseColor.a); #endif #include #include(color,baseColor) #ifdef IMAGEPROCESSINGPOSTPROCESS baseColor=vec4f(toLinearSpaceVec3(baseColor.rgb),baseColor.a); #else #ifdef IMAGEPROCESSING baseColor=vec4f(toLinearSpaceVec3(baseColor.rgb),baseColor.a);baseColor=applyImageProcessing(baseColor); #endif #endif fragmentOutputs.color=baseColor; #define CUSTOM_FRAGMENT_MAIN_END }`; if (!ShaderStore.ShadersStoreWGSL[name241]) { ShaderStore.ShadersStoreWGSL[name241] = shader241; } particlesPixelShaderWGSL = { name: name241, shader: shader241 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/particles.vertex.js var particles_vertex_exports2 = {}; __export(particles_vertex_exports2, { particlesVertexShader: () => particlesVertexShader }); var name242, shader242, particlesVertexShader; var init_particles_vertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/particles.vertex.js"() { init_shaderStore(); init_clipPlaneVertexDeclaration2(); init_fogVertexDeclaration2(); init_logDepthDeclaration2(); init_clipPlaneVertex2(); init_fogVertex2(); init_logDepthVertex2(); name242 = "particlesVertexShader"; shader242 = `attribute vec3 position;attribute vec4 color;attribute float angle;attribute vec2 size; #ifdef ANIMATESHEET attribute float cellIndex; #endif #ifndef BILLBOARD attribute vec3 direction; #endif #ifdef BILLBOARDSTRETCHED attribute vec3 direction; #endif #ifdef RAMPGRADIENT attribute vec4 remapData; #endif attribute vec2 offset;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot; #ifdef ANIMATESHEET uniform vec3 particlesInfos; #endif varying vec2 vUV;varying vec4 vColor; #ifdef RAMPGRADIENT varying vec4 remapRanges; #endif #if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) uniform mat4 invView; #endif #include #include #include #ifdef BILLBOARD uniform vec3 eyePosition; #endif vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} #ifdef BILLBOARDSTRETCHED vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z); #ifdef BILLBOARDSTRETCHED_LOCAL vec3 row1=direction; #else vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z); #endif mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner;return position+alignedCorner;} #endif #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec2 cornerPos;vec3 vPositionW;cornerPos=(vec2(offset.x-0.5,offset.y -0.5)-translationPivot)*size; #ifdef BILLBOARD vec3 rotatedCorner; #ifdef BILLBOARDY rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=position-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; #elif defined(BILLBOARDSTRETCHED) rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=position-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner);vec3 viewPos=(view*vec4(vPositionW,1.0)).xyz; #else rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner;vPositionW=(invView*vec4(viewPos,1)).xyz; #endif #ifdef RAMPGRADIENT remapRanges=remapData; #endif gl_Position=projection*vec4(viewPos,1.0); #else vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(direction);vPositionW=rotate(yaxis,rotatedCorner);gl_Position=projection*view*vec4(vPositionW,1.0); #endif vColor=color; #ifdef ANIMATESHEET float rowOffset=floor(cellIndex*particlesInfos.z);float columnOffset=cellIndex-rowOffset/particlesInfos.z;vec2 uvScale=particlesInfos.xy;vec2 uvOffset=vec2(offset.x ,1.0-offset.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; #else vUV=offset; #endif #if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG) vec4 worldPos=vec4(vPositionW,1.0); #endif #include #include #include #define CUSTOM_VERTEX_MAIN_END }`; if (!ShaderStore.ShadersStore[name242]) { ShaderStore.ShadersStore[name242] = shader242; } particlesVertexShader = { name: name242, shader: shader242 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/particles.fragment.js var particles_fragment_exports2 = {}; __export(particles_fragment_exports2, { particlesPixelShader: () => particlesPixelShader }); var name243, shader243, particlesPixelShader; var init_particles_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/particles.fragment.js"() { init_shaderStore(); init_clipPlaneFragmentDeclaration2(); init_imageProcessingDeclaration2(); init_logDepthDeclaration2(); init_helperFunctions2(); init_imageProcessingFunctions2(); init_fogFragmentDeclaration2(); init_clipPlaneFragment2(); init_logDepthFragment2(); init_fogFragment2(); name243 = "particlesPixelShader"; shader243 = `#ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif varying vec2 vUV;varying vec4 vColor;uniform vec4 textureMask;uniform sampler2D diffuseSampler; #include #include #include #include #include #ifdef RAMPGRADIENT varying vec4 remapRanges;uniform sampler2D rampSampler; #endif #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #include vec4 textureColor=texture2D(diffuseSampler,vUV);vec4 baseColor=(textureColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor; #ifdef RAMPGRADIENT float alpha=baseColor.a;float remappedColorIndex=clamp((alpha-remapRanges.x)/remapRanges.y,0.0,1.0);vec4 rampColor=texture2D(rampSampler,vec2(1.0-remappedColorIndex,0.));baseColor.rgb*=rampColor.rgb;float finalAlpha=baseColor.a;baseColor.a=clamp((alpha*rampColor.a-remapRanges.z)/remapRanges.w,0.0,1.0); #endif #ifdef BLENDMULTIPLYMODE float sourceAlpha=vColor.a*textureColor.a;baseColor.rgb=baseColor.rgb*sourceAlpha+vec3(1.0)*(1.0-sourceAlpha); #endif #include #include(color,baseColor) #ifdef IMAGEPROCESSINGPOSTPROCESS baseColor.rgb=toLinearSpace(baseColor.rgb); #else #ifdef IMAGEPROCESSING baseColor.rgb=toLinearSpace(baseColor.rgb);baseColor=applyImageProcessing(baseColor); #endif #endif gl_FragColor=baseColor; #define CUSTOM_FRAGMENT_MAIN_END }`; if (!ShaderStore.ShadersStore[name243]) { ShaderStore.ShadersStore[name243] = shader243; } particlesPixelShader = { name: name243, shader: shader243 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/layer.vertex.js var layer_vertex_exports = {}; __export(layer_vertex_exports, { layerVertexShaderWGSL: () => layerVertexShaderWGSL }); var name248, shader248, layerVertexShaderWGSL; var init_layer_vertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/layer.vertex.js"() { init_shaderStore(); name248 = "layerVertexShader"; shader248 = `attribute position: vec2f;uniform scale: vec2f;uniform offset: vec2f;uniform textureMatrix: mat4x4f;varying vUV: vec2f;const madd: vec2f= vec2f(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN var shiftedPosition: vec2f=input.position*uniforms.scale+uniforms.offset;vertexOutputs.vUV=(uniforms.textureMatrix* vec4f(shiftedPosition*madd+madd,1.0,0.0)).xy;vertexOutputs.position= vec4f(shiftedPosition,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`; if (!ShaderStore.ShadersStoreWGSL[name248]) { ShaderStore.ShadersStoreWGSL[name248] = shader248; } layerVertexShaderWGSL = { name: name248, shader: shader248 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/layer.fragment.js var layer_fragment_exports = {}; __export(layer_fragment_exports, { layerPixelShaderWGSL: () => layerPixelShaderWGSL }); var name249, shader249, layerPixelShaderWGSL; var init_layer_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/layer.fragment.js"() { init_shaderStore(); init_helperFunctions(); name249 = "layerPixelShader"; shader249 = `varying vUV: vec2f;var textureSamplerSampler: sampler;var textureSampler: texture_2d;uniform color: vec4f; #include #define CUSTOM_FRAGMENT_DEFINITIONS @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN var baseColor: vec4f=textureSample(textureSampler,textureSamplerSampler,input.vUV); #if defined(CONVERT_TO_GAMMA) baseColor=toGammaSpace(baseColor); #elif defined(CONVERT_TO_LINEAR) baseColor=toLinearSpaceVec4(baseColor); #endif #ifdef ALPHATEST if (baseColor.a<0.4) {discard;} #endif fragmentOutputs.color=baseColor*uniforms.color; #define CUSTOM_FRAGMENT_MAIN_END }`; if (!ShaderStore.ShadersStoreWGSL[name249]) { ShaderStore.ShadersStoreWGSL[name249] = shader249; } layerPixelShaderWGSL = { name: name249, shader: shader249 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/layer.vertex.js var layer_vertex_exports2 = {}; __export(layer_vertex_exports2, { layerVertexShader: () => layerVertexShader }); var name250, shader250, layerVertexShader; var init_layer_vertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/layer.vertex.js"() { init_shaderStore(); name250 = "layerVertexShader"; shader250 = `attribute vec2 position;uniform vec2 scale;uniform vec2 offset;uniform mat4 textureMatrix;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5); #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec2 shiftedPosition=position*scale+offset;vUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));gl_Position=vec4(shiftedPosition,0.0,1.0); #define CUSTOM_VERTEX_MAIN_END }`; if (!ShaderStore.ShadersStore[name250]) { ShaderStore.ShadersStore[name250] = shader250; } layerVertexShader = { name: name250, shader: shader250 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/layer.fragment.js var layer_fragment_exports2 = {}; __export(layer_fragment_exports2, { layerPixelShader: () => layerPixelShader }); var name251, shader251, layerPixelShader; var init_layer_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/layer.fragment.js"() { init_shaderStore(); init_helperFunctions2(); name251 = "layerPixelShader"; shader251 = `varying vec2 vUV;uniform sampler2D textureSampler;uniform vec4 color; #include #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN vec4 baseColor=texture2D(textureSampler,vUV); #if defined(CONVERT_TO_GAMMA) baseColor.rgb=toGammaSpace(baseColor.rgb); #elif defined(CONVERT_TO_LINEAR) baseColor.rgb=toLinearSpace(baseColor.rgb); #endif #ifdef ALPHATEST if (baseColor.a<0.4) discard; #endif gl_FragColor=baseColor*color; #define CUSTOM_FRAGMENT_MAIN_END }`; if (!ShaderStore.ShadersStore[name251]) { ShaderStore.ShadersStore[name251] = shader251; } layerPixelShader = { name: name251, shader: shader251 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/sprites.vertex.js var sprites_vertex_exports = {}; __export(sprites_vertex_exports, { spritesVertexShaderWGSL: () => spritesVertexShaderWGSL }); var name254, shader254, spritesVertexShaderWGSL; var init_sprites_vertex = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/sprites.vertex.js"() { init_shaderStore(); init_fogVertexDeclaration(); init_logDepthDeclaration(); init_logDepthVertex(); name254 = "spritesVertexShader"; shader254 = `attribute position: vec4f;attribute options: vec2f;attribute offsets: vec2f;attribute inverts: vec2f;attribute cellInfo: vec4f;attribute color: vec4f;uniform view: mat4x4f;uniform projection: mat4x4f;varying vUV: vec2f;varying vColor: vec4f; #include #include #define CUSTOM_VERTEX_DEFINITIONS @vertex fn main(input : VertexInputs)->FragmentInputs { #define CUSTOM_VERTEX_MAIN_BEGIN var viewPos: vec3f=(uniforms.view* vec4f(input.position.xyz,1.0)).xyz; var cornerPos: vec2f;var angle: f32=input.position.w;var size: vec2f= vec2f(input.options.x,input.options.y);var offset: vec2f=input.offsets.xy;cornerPos= vec2f(offset.x-0.5,offset.y -0.5)*size;var rotatedCorner: vec3f;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;vertexOutputs.position=uniforms.projection*vec4f(viewPos,1.0); vertexOutputs.vColor=input.color;var uvOffset: vec2f= vec2f(abs(offset.x-input.inverts.x),abs(1.0-offset.y-input.inverts.y));var uvPlace: vec2f=input.cellInfo.xy;var uvSize: vec2f=input.cellInfo.zw;vertexOutputs.vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vertexOutputs.vUV.y=uvPlace.y+uvSize.y*uvOffset.y; #ifdef FOG vertexOutputs.vFogDistance=viewPos; #endif #include #define CUSTOM_VERTEX_MAIN_END }`; if (!ShaderStore.ShadersStoreWGSL[name254]) { ShaderStore.ShadersStoreWGSL[name254] = shader254; } spritesVertexShaderWGSL = { name: name254, shader: shader254 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/imageProcessingCompatibility.js var name255, shader255, imageProcessingCompatibilityWGSL; var init_imageProcessingCompatibility = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/ShadersInclude/imageProcessingCompatibility.js"() { init_shaderStore(); name255 = "imageProcessingCompatibility"; shader255 = `#ifdef IMAGEPROCESSINGPOSTPROCESS fragmentOutputs.color=vec4f(pow(fragmentOutputs.color.rgb, vec3f(2.2)),fragmentOutputs.color.a); #endif `; if (!ShaderStore.IncludesShadersStoreWGSL[name255]) { ShaderStore.IncludesShadersStoreWGSL[name255] = shader255; } imageProcessingCompatibilityWGSL = { name: name255, shader: shader255 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/sprites.fragment.js var sprites_fragment_exports = {}; __export(sprites_fragment_exports, { spritesPixelShaderWGSL: () => spritesPixelShaderWGSL }); var name256, shader256, spritesPixelShaderWGSL; var init_sprites_fragment = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/ShadersWGSL/sprites.fragment.js"() { init_shaderStore(); init_fogFragmentDeclaration(); init_logDepthDeclaration(); init_logDepthFragment(); init_fogFragment(); init_imageProcessingCompatibility(); name256 = "spritesPixelShader"; shader256 = `uniform alphaTest: i32;varying vColor: vec4f;varying vUV: vec2f;var diffuseSamplerSampler: sampler;var diffuseSampler: texture_2d; #include #include #define CUSTOM_FRAGMENT_DEFINITIONS #ifdef PIXEL_PERFECT fn uvPixelPerfect(uv: vec2f)->vec2f {var res: vec2f= vec2f(textureDimensions(diffuseSampler,0));var uvTemp=uv*res;var seam: vec2f=floor(uvTemp+0.5);uvTemp=seam+clamp((uvTemp-seam)/fwidth(uvTemp),vec2f(-0.5),vec2f(0.5));return uvTemp/res;} #endif @fragment fn main(input: FragmentInputs)->FragmentOutputs { #define CUSTOM_FRAGMENT_MAIN_BEGIN #ifdef PIXEL_PERFECT var uv: vec2f=uvPixelPerfect(input.vUV); #else var uv: vec2f=input.vUV; #endif var color: vec4f=textureSample(diffuseSampler,diffuseSamplerSampler,uv);var fAlphaTest: f32= f32(uniforms.alphaTest);if (fAlphaTest != 0.) {if (color.a<0.95) {discard;}} color*=input.vColor; #include #include fragmentOutputs.color=color; #include #define CUSTOM_FRAGMENT_MAIN_END }`; if (!ShaderStore.ShadersStoreWGSL[name256]) { ShaderStore.ShadersStoreWGSL[name256] = shader256; } spritesPixelShaderWGSL = { name: name256, shader: shader256 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/sprites.vertex.js var sprites_vertex_exports2 = {}; __export(sprites_vertex_exports2, { spritesVertexShader: () => spritesVertexShader }); var name257, shader257, spritesVertexShader; var init_sprites_vertex2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/sprites.vertex.js"() { init_shaderStore(); init_fogVertexDeclaration2(); init_logDepthDeclaration2(); init_logDepthVertex2(); name257 = "spritesVertexShader"; shader257 = `attribute vec4 position;attribute vec2 options;attribute vec2 offsets;attribute vec2 inverts;attribute vec4 cellInfo;attribute vec4 color;uniform mat4 view;uniform mat4 projection;varying vec2 vUV;varying vec4 vColor; #include #include #define CUSTOM_VERTEX_DEFINITIONS void main(void) { #define CUSTOM_VERTEX_MAIN_BEGIN vec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; vec2 cornerPos;float angle=position.w;vec2 size=vec2(options.x,options.y);vec2 offset=offsets.xy;cornerPos=vec2(offset.x-0.5,offset.y -0.5)*size;vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;viewPos+=rotatedCorner;gl_Position=projection*vec4(viewPos,1.0); vColor=color;vec2 uvOffset=vec2(abs(offset.x-inverts.x),abs(1.0-offset.y-inverts.y));vec2 uvPlace=cellInfo.xy;vec2 uvSize=cellInfo.zw;vUV.x=uvPlace.x+uvSize.x*uvOffset.x;vUV.y=uvPlace.y+uvSize.y*uvOffset.y; #ifdef FOG vFogDistance=viewPos; #endif #include #define CUSTOM_VERTEX_MAIN_END }`; if (!ShaderStore.ShadersStore[name257]) { ShaderStore.ShadersStore[name257] = shader257; } spritesVertexShader = { name: name257, shader: shader257 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/imageProcessingCompatibility.js var name258, shader258, imageProcessingCompatibility; var init_imageProcessingCompatibility2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/imageProcessingCompatibility.js"() { init_shaderStore(); name258 = "imageProcessingCompatibility"; shader258 = `#ifdef IMAGEPROCESSINGPOSTPROCESS gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(2.2)); #endif `; if (!ShaderStore.IncludesShadersStore[name258]) { ShaderStore.IncludesShadersStore[name258] = shader258; } imageProcessingCompatibility = { name: name258, shader: shader258 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/sprites.fragment.js var sprites_fragment_exports2 = {}; __export(sprites_fragment_exports2, { spritesPixelShader: () => spritesPixelShader }); var name259, shader259, spritesPixelShader; var init_sprites_fragment2 = __esm({ "Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/sprites.fragment.js"() { init_shaderStore(); init_fogFragmentDeclaration2(); init_logDepthDeclaration2(); init_logDepthFragment2(); init_fogFragment2(); init_imageProcessingCompatibility2(); name259 = "spritesPixelShader"; shader259 = `#ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif uniform bool alphaTest;varying vec4 vColor;varying vec2 vUV;uniform sampler2D diffuseSampler; #include #include #define CUSTOM_FRAGMENT_DEFINITIONS #ifdef PIXEL_PERFECT vec2 uvPixelPerfect(vec2 uv) {vec2 res=vec2(textureSize(diffuseSampler,0));uv=uv*res;vec2 seam=floor(uv+0.5);uv=seam+clamp((uv-seam)/fwidth(uv),-0.5,0.5);return uv/res;} #endif void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN #ifdef PIXEL_PERFECT vec2 uv=uvPixelPerfect(vUV); #else vec2 uv=vUV; #endif vec4 color=texture2D(diffuseSampler,uv);float fAlphaTest=float(alphaTest);if (fAlphaTest != 0.) {if (color.a<0.95) discard;} color*=vColor; #include #include gl_FragColor=color; #include #define CUSTOM_FRAGMENT_MAIN_END }`; if (!ShaderStore.ShadersStore[name259]) { ShaderStore.ShadersStore[name259] = shader259; } spritesPixelShader = { name: name259, shader: shader259 }; } }); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/src/scripts/box.ts var box_exports = {}; __export(box_exports, { default: () => SceneComponent }); module.exports = __toCommonJS(box_exports); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/constants.js var Constants = class { static { __name(this, "Constants"); } }; Constants.AUTOSAMPLERSUFFIX = "Sampler"; Constants.DISABLEUA = "#define DISABLE_UNIFORMITY_ANALYSIS"; Constants.ALPHA_DISABLE = 0; Constants.ALPHA_ADD = 1; Constants.ALPHA_COMBINE = 2; Constants.ALPHA_SUBTRACT = 3; Constants.ALPHA_MULTIPLY = 4; Constants.ALPHA_MAXIMIZED = 5; Constants.ALPHA_ONEONE = 6; Constants.ALPHA_PREMULTIPLIED = 7; Constants.ALPHA_PREMULTIPLIED_PORTERDUFF = 8; Constants.ALPHA_INTERPOLATE = 9; Constants.ALPHA_SCREENMODE = 10; Constants.ALPHA_ONEONE_ONEONE = 11; Constants.ALPHA_ALPHATOCOLOR = 12; Constants.ALPHA_REVERSEONEMINUS = 13; Constants.ALPHA_SRC_DSTONEMINUSSRCALPHA = 14; Constants.ALPHA_ONEONE_ONEZERO = 15; Constants.ALPHA_EXCLUSION = 16; Constants.ALPHA_LAYER_ACCUMULATE = 17; Constants.ALPHA_MIN = 18; Constants.ALPHA_MAX = 19; Constants.ALPHA_DUAL_SRC0_ADD_SRC1xDST = 20; Constants.ALPHA_EQUATION_ADD = 0; Constants.ALPHA_EQUATION_SUBSTRACT = 1; Constants.ALPHA_EQUATION_REVERSE_SUBTRACT = 2; Constants.ALPHA_EQUATION_MAX = 3; Constants.ALPHA_EQUATION_MIN = 4; Constants.ALPHA_EQUATION_DARKEN = 5; Constants.DELAYLOADSTATE_NONE = 0; Constants.DELAYLOADSTATE_LOADED = 1; Constants.DELAYLOADSTATE_LOADING = 2; Constants.DELAYLOADSTATE_NOTLOADED = 4; Constants.NEVER = 512; Constants.ALWAYS = 519; Constants.LESS = 513; Constants.EQUAL = 514; Constants.LEQUAL = 515; Constants.GREATER = 516; Constants.GEQUAL = 518; Constants.NOTEQUAL = 517; Constants.KEEP = 7680; Constants.ZERO = 0; Constants.REPLACE = 7681; Constants.INCR = 7682; Constants.DECR = 7683; Constants.INVERT = 5386; Constants.INCR_WRAP = 34055; Constants.DECR_WRAP = 34056; Constants.TEXTURE_CLAMP_ADDRESSMODE = 0; Constants.TEXTURE_WRAP_ADDRESSMODE = 1; Constants.TEXTURE_MIRROR_ADDRESSMODE = 2; Constants.TEXTURE_CREATIONFLAG_STORAGE = 1; Constants.TEXTUREFORMAT_ALPHA = 0; Constants.TEXTUREFORMAT_LUMINANCE = 1; Constants.TEXTUREFORMAT_LUMINANCE_ALPHA = 2; Constants.TEXTUREFORMAT_RGB = 4; Constants.TEXTUREFORMAT_RGBA = 5; Constants.TEXTUREFORMAT_RED = 6; Constants.TEXTUREFORMAT_R = 6; Constants.TEXTUREFORMAT_R16_UNORM = 33322; Constants.TEXTUREFORMAT_RG16_UNORM = 33324; Constants.TEXTUREFORMAT_RGB16_UNORM = 32852; Constants.TEXTUREFORMAT_RGBA16_UNORM = 32859; Constants.TEXTUREFORMAT_R16_SNORM = 36760; Constants.TEXTUREFORMAT_RG16_SNORM = 36761; Constants.TEXTUREFORMAT_RGB16_SNORM = 36762; Constants.TEXTUREFORMAT_RGBA16_SNORM = 36763; Constants.TEXTUREFORMAT_RG = 7; Constants.TEXTUREFORMAT_RED_INTEGER = 8; Constants.TEXTUREFORMAT_R_INTEGER = 8; Constants.TEXTUREFORMAT_RG_INTEGER = 9; Constants.TEXTUREFORMAT_RGB_INTEGER = 10; Constants.TEXTUREFORMAT_RGBA_INTEGER = 11; Constants.TEXTUREFORMAT_BGRA = 12; Constants.TEXTUREFORMAT_DEPTH24_STENCIL8 = 13; Constants.TEXTUREFORMAT_DEPTH32_FLOAT = 14; Constants.TEXTUREFORMAT_DEPTH16 = 15; Constants.TEXTUREFORMAT_DEPTH24 = 16; Constants.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8 = 17; Constants.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8 = 18; Constants.TEXTUREFORMAT_STENCIL8 = 19; Constants.TEXTUREFORMAT_UNDEFINED = 4294967295; Constants.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM = 36492; Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM = 36493; Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT = 36495; Constants.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT = 36494; Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5 = 33779; Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 35919; Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3 = 33778; Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 35918; Constants.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1 = 33777; Constants.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1 = 33776; Constants.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 35917; Constants.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT = 35916; Constants.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4 = 37808; Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 37840; Constants.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL = 36196; Constants.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2 = 37492; Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2 = 37493; Constants.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37494; Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 37495; Constants.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC = 37496; Constants.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 37497; Constants.TEXTURETYPE_UNSIGNED_BYTE = 0; Constants.TEXTURETYPE_UNSIGNED_INT = 0; Constants.TEXTURETYPE_FLOAT = 1; Constants.TEXTURETYPE_HALF_FLOAT = 2; Constants.TEXTURETYPE_BYTE = 3; Constants.TEXTURETYPE_SHORT = 4; Constants.TEXTURETYPE_UNSIGNED_SHORT = 5; Constants.TEXTURETYPE_INT = 6; Constants.TEXTURETYPE_UNSIGNED_INTEGER = 7; Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8; Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9; Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10; Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11; Constants.TEXTURETYPE_UNSIGNED_INT_24_8 = 12; Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13; Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14; Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15; Constants.TEXTURETYPE_UNDEFINED = 16; Constants.TEXTURE_2D = 3553; Constants.TEXTURE_2D_ARRAY = 35866; Constants.TEXTURE_CUBE_MAP = 34067; Constants.TEXTURE_CUBE_MAP_ARRAY = 3735928559; Constants.TEXTURE_3D = 32879; Constants.TEXTURE_NEAREST_SAMPLINGMODE = 1; Constants.TEXTURE_NEAREST_NEAREST = 1; Constants.TEXTURE_BILINEAR_SAMPLINGMODE = 2; Constants.TEXTURE_LINEAR_LINEAR = 2; Constants.TEXTURE_TRILINEAR_SAMPLINGMODE = 3; Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3; Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4; Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5; Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6; Constants.TEXTURE_NEAREST_LINEAR = 7; Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8; Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9; Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10; Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11; Constants.TEXTURE_LINEAR_NEAREST = 12; Constants.TEXTURE_EXPLICIT_MODE = 0; Constants.TEXTURE_SPHERICAL_MODE = 1; Constants.TEXTURE_PLANAR_MODE = 2; Constants.TEXTURE_CUBIC_MODE = 3; Constants.TEXTURE_PROJECTION_MODE = 4; Constants.TEXTURE_SKYBOX_MODE = 5; Constants.TEXTURE_INVCUBIC_MODE = 6; Constants.TEXTURE_EQUIRECTANGULAR_MODE = 7; Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8; Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9; Constants.TEXTURE_FILTERING_QUALITY_OFFLINE = 4096; Constants.TEXTURE_FILTERING_QUALITY_HIGH = 64; Constants.TEXTURE_FILTERING_QUALITY_MEDIUM = 16; Constants.TEXTURE_FILTERING_QUALITY_LOW = 8; Constants.SCALEMODE_FLOOR = 1; Constants.SCALEMODE_NEAREST = 2; Constants.SCALEMODE_CEILING = 3; Constants.MATERIAL_TextureDirtyFlag = 1; Constants.MATERIAL_LightDirtyFlag = 2; Constants.MATERIAL_FresnelDirtyFlag = 4; Constants.MATERIAL_AttributesDirtyFlag = 8; Constants.MATERIAL_MiscDirtyFlag = 16; Constants.MATERIAL_PrePassDirtyFlag = 32; Constants.MATERIAL_ImageProcessingDirtyFlag = 64; Constants.MATERIAL_AllDirtyFlag = 127; Constants.MATERIAL_TriangleFillMode = 0; Constants.MATERIAL_WireFrameFillMode = 1; Constants.MATERIAL_PointFillMode = 2; Constants.MATERIAL_PointListDrawMode = 3; Constants.MATERIAL_LineListDrawMode = 4; Constants.MATERIAL_LineLoopDrawMode = 5; Constants.MATERIAL_LineStripDrawMode = 6; Constants.MATERIAL_TriangleStripDrawMode = 7; Constants.MATERIAL_TriangleFanDrawMode = 8; Constants.MATERIAL_ClockWiseSideOrientation = 0; Constants.MATERIAL_CounterClockWiseSideOrientation = 1; Constants.MATERIAL_DIFFUSE_MODEL_E_OREN_NAYAR = 0; Constants.MATERIAL_DIFFUSE_MODEL_BURLEY = 1; Constants.MATERIAL_DIFFUSE_MODEL_LAMBERT = 2; Constants.MATERIAL_DIFFUSE_MODEL_LEGACY = 3; Constants.MATERIAL_DIELECTRIC_SPECULAR_MODEL_GLTF = 0; Constants.MATERIAL_DIELECTRIC_SPECULAR_MODEL_OPENPBR = 1; Constants.MATERIAL_CONDUCTOR_SPECULAR_MODEL_GLTF = 0; Constants.MATERIAL_CONDUCTOR_SPECULAR_MODEL_OPENPBR = 1; Constants.ACTION_NothingTrigger = 0; Constants.ACTION_OnPickTrigger = 1; Constants.ACTION_OnLeftPickTrigger = 2; Constants.ACTION_OnRightPickTrigger = 3; Constants.ACTION_OnCenterPickTrigger = 4; Constants.ACTION_OnPickDownTrigger = 5; Constants.ACTION_OnDoublePickTrigger = 6; Constants.ACTION_OnPickUpTrigger = 7; Constants.ACTION_OnPickOutTrigger = 16; Constants.ACTION_OnLongPressTrigger = 8; Constants.ACTION_OnPointerOverTrigger = 9; Constants.ACTION_OnPointerOutTrigger = 10; Constants.ACTION_OnEveryFrameTrigger = 11; Constants.ACTION_OnIntersectionEnterTrigger = 12; Constants.ACTION_OnIntersectionExitTrigger = 13; Constants.ACTION_OnKeyDownTrigger = 14; Constants.ACTION_OnKeyUpTrigger = 15; Constants.PARTICLES_BILLBOARDMODE_Y = 2; Constants.PARTICLES_BILLBOARDMODE_ALL = 7; Constants.PARTICLES_BILLBOARDMODE_STRETCHED = 8; Constants.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL = 9; Constants.MESHES_CULLINGSTRATEGY_STANDARD = 0; Constants.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1; Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2; Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3; Constants.SCENELOADER_NO_LOGGING = 0; Constants.SCENELOADER_MINIMAL_LOGGING = 1; Constants.SCENELOADER_SUMMARY_LOGGING = 2; Constants.SCENELOADER_DETAILED_LOGGING = 3; Constants.PREPASS_IRRADIANCE_TEXTURE_TYPE = 0; Constants.PREPASS_POSITION_TEXTURE_TYPE = 1; Constants.PREPASS_VELOCITY_TEXTURE_TYPE = 2; Constants.PREPASS_REFLECTIVITY_TEXTURE_TYPE = 3; Constants.PREPASS_COLOR_TEXTURE_TYPE = 4; Constants.PREPASS_DEPTH_TEXTURE_TYPE = 5; Constants.PREPASS_NORMAL_TEXTURE_TYPE = 6; Constants.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE = 7; Constants.PREPASS_WORLD_NORMAL_TEXTURE_TYPE = 8; Constants.PREPASS_LOCAL_POSITION_TEXTURE_TYPE = 9; Constants.PREPASS_SCREENSPACE_DEPTH_TEXTURE_TYPE = 10; Constants.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE = 11; Constants.PREPASS_ALBEDO_TEXTURE_TYPE = 12; Constants.PREPASS_NORMALIZED_VIEW_DEPTH_TEXTURE_TYPE = 13; Constants.BUFFER_CREATIONFLAG_READ = 1; Constants.BUFFER_CREATIONFLAG_WRITE = 2; Constants.BUFFER_CREATIONFLAG_READWRITE = 3; Constants.BUFFER_CREATIONFLAG_UNIFORM = 4; Constants.BUFFER_CREATIONFLAG_VERTEX = 8; Constants.BUFFER_CREATIONFLAG_INDEX = 16; Constants.BUFFER_CREATIONFLAG_STORAGE = 32; Constants.BUFFER_CREATIONFLAG_INDIRECT = 64; Constants.RENDERPASS_MAIN = 0; Constants.INPUT_ALT_KEY = 18; Constants.INPUT_CTRL_KEY = 17; Constants.INPUT_META_KEY1 = 91; Constants.INPUT_META_KEY2 = 92; Constants.INPUT_META_KEY3 = 93; Constants.INPUT_SHIFT_KEY = 16; Constants.SNAPSHOTRENDERING_STANDARD = 0; Constants.SNAPSHOTRENDERING_FAST = 1; Constants.PERSPECTIVE_CAMERA = 0; Constants.ORTHOGRAPHIC_CAMERA = 1; Constants.FOVMODE_VERTICAL_FIXED = 0; Constants.FOVMODE_HORIZONTAL_FIXED = 1; Constants.RIG_MODE_NONE = 0; Constants.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10; Constants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11; Constants.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12; Constants.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13; Constants.RIG_MODE_STEREOSCOPIC_INTERLACED = 14; Constants.RIG_MODE_VR = 20; Constants.RIG_MODE_CUSTOM = 22; Constants.MAX_SUPPORTED_UV_SETS = 6; Constants.GL_ALPHA_EQUATION_ADD = 32774; Constants.GL_ALPHA_EQUATION_MIN = 32775; Constants.GL_ALPHA_EQUATION_MAX = 32776; Constants.GL_ALPHA_EQUATION_SUBTRACT = 32778; Constants.GL_ALPHA_EQUATION_REVERSE_SUBTRACT = 32779; Constants.GL_ALPHA_FUNCTION_SRC = 768; Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR = 769; Constants.GL_ALPHA_FUNCTION_SRC_ALPHA = 770; Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA = 771; Constants.GL_ALPHA_FUNCTION_DST_ALPHA = 772; Constants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA = 773; Constants.GL_ALPHA_FUNCTION_DST_COLOR = 774; Constants.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR = 775; Constants.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED = 776; Constants.GL_ALPHA_FUNCTION_CONSTANT_COLOR = 32769; Constants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR = 32770; Constants.GL_ALPHA_FUNCTION_CONSTANT_ALPHA = 32771; Constants.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA = 32772; Constants.GL_ALPHA_FUNCTION_SRC1_COLOR = 35065; Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_COLOR = 35066; Constants.GL_ALPHA_FUNCTION_SRC1_ALPHA = 34185; Constants.GL_ALPHA_FUNCTION_ONE_MINUS_SRC1_ALPHA = 35067; Constants.SnippetUrl = "https://snippet.babylonjs.com"; Constants.FOGMODE_NONE = 0; Constants.FOGMODE_EXP = 1; Constants.FOGMODE_EXP2 = 2; Constants.FOGMODE_LINEAR = 3; Constants.BYTE = 5120; Constants.UNSIGNED_BYTE = 5121; Constants.SHORT = 5122; Constants.UNSIGNED_SHORT = 5123; Constants.INT = 5124; Constants.UNSIGNED_INT = 5125; Constants.FLOAT = 5126; Constants.PositionKind = "position"; Constants.NormalKind = "normal"; Constants.TangentKind = "tangent"; Constants.UVKind = "uv"; Constants.UV2Kind = "uv2"; Constants.UV3Kind = "uv3"; Constants.UV4Kind = "uv4"; Constants.UV5Kind = "uv5"; Constants.UV6Kind = "uv6"; Constants.ColorKind = "color"; Constants.ColorInstanceKind = "instanceColor"; Constants.MatricesIndicesKind = "matricesIndices"; Constants.MatricesWeightsKind = "matricesWeights"; Constants.MatricesIndicesExtraKind = "matricesIndicesExtra"; Constants.MatricesWeightsExtraKind = "matricesWeightsExtra"; Constants.ANIMATIONTYPE_FLOAT = 0; Constants.ANIMATIONTYPE_VECTOR3 = 1; Constants.ANIMATIONTYPE_QUATERNION = 2; Constants.ANIMATIONTYPE_MATRIX = 3; Constants.ANIMATIONTYPE_COLOR3 = 4; Constants.ANIMATIONTYPE_COLOR4 = 7; Constants.ANIMATIONTYPE_VECTOR2 = 5; Constants.ANIMATIONTYPE_SIZE = 6; Constants.ShadowMinZ = 0; Constants.ShadowMaxZ = 1e4; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Loading/sceneLoaderFlags.js var SceneLoaderFlags = class _SceneLoaderFlags { static { __name(this, "SceneLoaderFlags"); } /** * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data */ static get ForceFullSceneLoadingForIncremental() { return _SceneLoaderFlags._ForceFullSceneLoadingForIncremental; } static set ForceFullSceneLoadingForIncremental(value) { _SceneLoaderFlags._ForceFullSceneLoadingForIncremental = value; } /** * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene */ static get ShowLoadingScreen() { return _SceneLoaderFlags._ShowLoadingScreen; } static set ShowLoadingScreen(value) { _SceneLoaderFlags._ShowLoadingScreen = value; } /** * Defines the current logging level (while loading the scene) * @ignorenaming */ // eslint-disable-next-line @typescript-eslint/naming-convention static get loggingLevel() { return _SceneLoaderFlags._LoggingLevel; } // eslint-disable-next-line @typescript-eslint/naming-convention static set loggingLevel(value) { _SceneLoaderFlags._LoggingLevel = value; } /** * Gets or set a boolean indicating if matrix weights must be cleaned upon loading */ static get CleanBoneMatrixWeights() { return _SceneLoaderFlags._CleanBoneMatrixWeights; } static set CleanBoneMatrixWeights(value) { _SceneLoaderFlags._CleanBoneMatrixWeights = value; } }; SceneLoaderFlags._ForceFullSceneLoadingForIncremental = false; SceneLoaderFlags._ShowLoadingScreen = true; SceneLoaderFlags._CleanBoneMatrixWeights = false; SceneLoaderFlags._LoggingLevel = 0; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/webRequest.fetch.js init_webRequest(); async function _FetchAsync(url, options) { const method = options.method || "GET"; return await new Promise((resolve, reject) => { const request = new WebRequest(); request.addEventListener("readystatechange", () => { if (request.readyState == 4) { if (request.status == 200) { const headerValues = {}; if (options.responseHeaders) { for (const header of options.responseHeaders) { headerValues[header] = request.getResponseHeader(header) || ""; } } resolve({ response: request.response, headerValues }); } else { reject(`Unable to fetch data from ${url}. Error code: ${request.status}`); } } }); request.open(method, url); request.send(); }); } __name(_FetchAsync, "_FetchAsync"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Loading/sceneLoader.js init_tools(); init_observable(); init_scene(); init_engineStore(); init_logger(); init_fileTools(); init_error(); init_guid(); init_abstractEngine(); var SceneLoaderAnimationGroupLoadingMode; (function(SceneLoaderAnimationGroupLoadingMode2) { SceneLoaderAnimationGroupLoadingMode2[SceneLoaderAnimationGroupLoadingMode2["Clean"] = 0] = "Clean"; SceneLoaderAnimationGroupLoadingMode2[SceneLoaderAnimationGroupLoadingMode2["Stop"] = 1] = "Stop"; SceneLoaderAnimationGroupLoadingMode2[SceneLoaderAnimationGroupLoadingMode2["Sync"] = 2] = "Sync"; SceneLoaderAnimationGroupLoadingMode2[SceneLoaderAnimationGroupLoadingMode2["NoSync"] = 3] = "NoSync"; })(SceneLoaderAnimationGroupLoadingMode || (SceneLoaderAnimationGroupLoadingMode = {})); function IsFactory(pluginOrFactory) { return !!pluginOrFactory.createPlugin; } __name(IsFactory, "IsFactory"); function isFile(value) { return !!value.name; } __name(isFile, "isFile"); var onPluginActivatedObservable = new Observable(); var registeredPlugins = {}; var showingLoadingScreen = false; function getDefaultPlugin() { return registeredPlugins[".babylon"]; } __name(getDefaultPlugin, "getDefaultPlugin"); function getPluginForMimeType(mimeType) { for (const registeredPluginKey in registeredPlugins) { const registeredPlugin = registeredPlugins[registeredPluginKey]; if (registeredPlugin.mimeType === mimeType) { return registeredPlugin; } } return void 0; } __name(getPluginForMimeType, "getPluginForMimeType"); function getPluginForExtension(extension, returnDefault) { const registeredPlugin = registeredPlugins[extension]; if (registeredPlugin) { return registeredPlugin; } 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/features/featuresDeepDive/importers/loadingFileTypes"); return returnDefault ? getDefaultPlugin() : void 0; } __name(getPluginForExtension, "getPluginForExtension"); function isPluginForExtensionAvailable(extension) { return !!registeredPlugins[extension]; } __name(isPluginForExtensionAvailable, "isPluginForExtensionAvailable"); function getPluginForDirectLoad(data) { for (const extension in registeredPlugins) { const plugin = registeredPlugins[extension].plugin; if (plugin.canDirectLoad && plugin.canDirectLoad(data)) { return registeredPlugins[extension]; } } return getDefaultPlugin(); } __name(getPluginForDirectLoad, "getPluginForDirectLoad"); function getFilenameExtension(sceneFilename) { const queryStringPosition = sceneFilename.indexOf("?"); if (queryStringPosition !== -1) { sceneFilename = sceneFilename.substring(0, queryStringPosition); } const dotPosition = sceneFilename.lastIndexOf("."); return sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase(); } __name(getFilenameExtension, "getFilenameExtension"); function getDirectLoad(sceneFilename) { if (sceneFilename.substring(0, 5) === "data:") { return sceneFilename.substring(5); } return null; } __name(getDirectLoad, "getDirectLoad"); function formatErrorMessage(fileInfo, message, exception) { const fromLoad = fileInfo.rawData ? "binary data" : fileInfo.url; let errorMessage = "Unable to load from " + fromLoad; if (message) { errorMessage += `: ${message}`; } else if (exception) { errorMessage += `: ${exception}`; } return errorMessage; } __name(formatErrorMessage, "formatErrorMessage"); async function loadDataAsync(fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension, name260, pluginOptions) { const directLoad = getDirectLoad(fileInfo.url); if (fileInfo.rawData && !pluginExtension) { throw "When using ArrayBufferView to load data the file extension must be provided."; } const fileExtension = !directLoad && !pluginExtension ? getFilenameExtension(fileInfo.url) : ""; let registeredPlugin = pluginExtension ? getPluginForExtension(pluginExtension, true) : directLoad ? getPluginForDirectLoad(fileInfo.url) : getPluginForExtension(fileExtension, false); if (!registeredPlugin && fileExtension) { if (fileInfo.url && !fileInfo.url.startsWith("blob:")) { const response = await _FetchAsync(fileInfo.url, { method: "HEAD", responseHeaders: ["Content-Type"] }); const mimeType = response.headerValues ? response.headerValues["Content-Type"] : ""; if (mimeType) { registeredPlugin = getPluginForMimeType(mimeType); } } if (!registeredPlugin) { registeredPlugin = getDefaultPlugin(); } } if (!registeredPlugin) { throw new Error(`No plugin or fallback for ${pluginExtension ?? fileInfo.url}`); } if (pluginOptions?.[registeredPlugin.plugin.name]?.enabled === false) { throw new Error(`The '${registeredPlugin.plugin.name}' plugin is disabled via the loader options passed to the loading operation.`); } if (fileInfo.rawData && !registeredPlugin.isBinary) { throw "Loading from ArrayBufferView can not be used with plugins that don't support binary loading."; } const getPluginInstance = /* @__PURE__ */ __name((callback) => { if (IsFactory(registeredPlugin.plugin)) { const pluginFactory = registeredPlugin.plugin; const partialPlugin = pluginFactory.createPlugin(pluginOptions ?? {}); if (partialPlugin instanceof Promise) { partialPlugin.then(callback).catch((error) => { onError("Error instantiating plugin.", error); }); return null; } else { callback(partialPlugin); return partialPlugin; } } else { callback(registeredPlugin.plugin); return registeredPlugin.plugin; } }, "getPluginInstance"); return getPluginInstance((plugin) => { if (!plugin) { throw `The loader plugin corresponding to the '${pluginExtension}' file type has not been found. If using es6, please import the plugin you wish to use before.`; } onPluginActivatedObservable.notifyObservers(plugin); if (directLoad && (plugin.canDirectLoad && plugin.canDirectLoad(fileInfo.url) || !IsBase64DataUrl(fileInfo.url))) { if (plugin.directLoad) { const result = plugin.directLoad(scene, directLoad); if (result instanceof Promise) { result.then((data) => { onSuccess(plugin, data); }).catch((error) => { onError("Error in directLoad of _loadData: " + error, error); }); } else { onSuccess(plugin, result); } } else { onSuccess(plugin, directLoad); } return; } const useArrayBuffer = registeredPlugin.isBinary; const dataCallback = /* @__PURE__ */ __name((data, responseURL) => { if (scene.isDisposed) { onError("Scene has been disposed"); return; } onSuccess(plugin, data, responseURL); }, "dataCallback"); let request = null; let pluginDisposed = false; plugin.onDisposeObservable?.add(() => { pluginDisposed = true; if (request) { request.abort(); request = null; } onDispose(); }); const manifestChecked = /* @__PURE__ */ __name(() => { if (pluginDisposed) { return; } const errorCallback = /* @__PURE__ */ __name((request2, exception) => { onError(request2?.statusText, exception); }, "errorCallback"); if (!plugin.loadFile && fileInfo.rawData) { throw "Plugin does not support loading ArrayBufferView."; } request = plugin.loadFile ? plugin.loadFile(scene, fileInfo.rawData || fileInfo.file || fileInfo.url, fileInfo.rootUrl, dataCallback, onProgress, useArrayBuffer, errorCallback, name260) : scene._loadFile(fileInfo.file || fileInfo.url, dataCallback, onProgress, true, useArrayBuffer, errorCallback); }, "manifestChecked"); const engine = scene.getEngine(); let canUseOfflineSupport = engine.enableOfflineSupport; if (canUseOfflineSupport) { let exceptionFound = false; for (const regex of scene.disableOfflineSupportExceptionRules) { if (regex.test(fileInfo.url)) { exceptionFound = true; break; } } canUseOfflineSupport = !exceptionFound; } if (canUseOfflineSupport && AbstractEngine.OfflineProviderFactory) { scene.offlineProvider = AbstractEngine.OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck); } else { manifestChecked(); } }); } __name(loadDataAsync, "loadDataAsync"); function GetFileInfo(rootUrl, sceneSource) { let url; let name260; let file = null; let rawData = null; if (!sceneSource) { url = rootUrl; name260 = Tools.GetFilename(rootUrl); rootUrl = Tools.GetFolderPath(rootUrl); } else if (isFile(sceneSource)) { url = `file:${sceneSource.name}`; name260 = sceneSource.name; file = sceneSource; } else if (ArrayBuffer.isView(sceneSource)) { url = ""; name260 = RandomGUID(); rawData = sceneSource; } else if (sceneSource.startsWith("data:")) { url = sceneSource; name260 = ""; } else if (rootUrl) { const filename = sceneSource; if (filename.substring(0, 1) === "/") { Tools.Error("Wrong sceneFilename parameter"); return null; } url = rootUrl + filename; name260 = filename; } else { url = sceneSource; name260 = Tools.GetFilename(sceneSource); rootUrl = Tools.GetFolderPath(sceneSource); } return { url, rootUrl, name: name260, file, rawData }; } __name(GetFileInfo, "GetFileInfo"); function RegisterSceneLoaderPlugin(plugin) { if (typeof plugin.extensions === "string") { const extension = plugin.extensions; registeredPlugins[extension.toLowerCase()] = { plugin, isBinary: false }; } else { const extensions = plugin.extensions; const keys = Object.keys(extensions); for (const extension of keys) { registeredPlugins[extension.toLowerCase()] = { plugin, isBinary: extensions[extension].isBinary, mimeType: extensions[extension].mimeType }; } } } __name(RegisterSceneLoaderPlugin, "RegisterSceneLoaderPlugin"); function registerSceneLoaderPlugin(plugin) { RegisterSceneLoaderPlugin(plugin); } __name(registerSceneLoaderPlugin, "registerSceneLoaderPlugin"); function GetRegisteredSceneLoaderPluginMetadata() { return Array.from(Object.entries(registeredPlugins).reduce((pluginMap, [extension, extensionRegistration]) => { let pluginMetadata = pluginMap.get(extensionRegistration.plugin.name); if (!pluginMetadata) { pluginMap.set(extensionRegistration.plugin.name, pluginMetadata = []); } pluginMetadata.push({ extension, isBinary: extensionRegistration.isBinary, mimeType: extensionRegistration.mimeType }); return pluginMap; }, /* @__PURE__ */ new Map())).map(([name260, extensions]) => ({ name: name260, extensions })); } __name(GetRegisteredSceneLoaderPluginMetadata, "GetRegisteredSceneLoaderPluginMetadata"); async function ImportMeshAsync(source, scene, options) { const { meshNames, rootUrl = "", onProgress, pluginExtension, name: name260, pluginOptions } = options ?? {}; return await importMeshAsyncCoreAsync(meshNames, rootUrl, source, scene, onProgress, pluginExtension, name260, pluginOptions); } __name(ImportMeshAsync, "ImportMeshAsync"); async function importMeshAsync(meshNames, rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name260 = "", pluginOptions = {}) { if (!scene) { Logger.Error("No scene available to import mesh to"); return null; } const fileInfo = GetFileInfo(rootUrl, sceneFilename); if (!fileInfo) { return null; } const loadingToken = {}; scene.addPendingData(loadingToken); const disposeHandler = /* @__PURE__ */ __name(() => { scene.removePendingData(loadingToken); }, "disposeHandler"); const errorHandler = /* @__PURE__ */ __name((message, exception) => { const errorMessage = formatErrorMessage(fileInfo, message, exception); if (onError) { onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception)); } else { Logger.Error(errorMessage); } disposeHandler(); }, "errorHandler"); const progressHandler = onProgress ? (event) => { try { onProgress(event); } catch (e) { errorHandler("Error in onProgress callback: " + e, e); } } : void 0; const successHandler = /* @__PURE__ */ __name((meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights, spriteManagers) => { scene.importedMeshesFiles.push(fileInfo.url); if (onSuccess) { try { onSuccess(meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights, spriteManagers); } catch (e) { errorHandler("Error in onSuccess callback: " + e, e); } } scene.removePendingData(loadingToken); }, "successHandler"); return await loadDataAsync(fileInfo, scene, (plugin, data, responseURL) => { if (plugin.rewriteRootURL) { fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL); } if (plugin.importMesh) { const syncedPlugin = plugin; const meshes = []; const particleSystems = []; const skeletons = []; if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) { return; } scene.loadingPluginName = plugin.name; successHandler(meshes, particleSystems, skeletons, [], [], [], [], []); } else { const asyncedPlugin = plugin; asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then((result) => { scene.loadingPluginName = plugin.name; successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups, result.transformNodes, result.geometries, result.lights, result.spriteManagers); }).catch((error) => { errorHandler(error.message, error); }); } }, progressHandler, errorHandler, disposeHandler, pluginExtension, name260, pluginOptions); } __name(importMeshAsync, "importMeshAsync"); async function importMeshAsyncCoreAsync(meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension, name260, pluginOptions) { return await new Promise((resolve, reject) => { try { importMeshAsync( meshNames, rootUrl, sceneFilename, scene, (meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights, spriteManagers) => { resolve({ meshes, particleSystems, skeletons, animationGroups, transformNodes, geometries, lights, spriteManagers }); }, onProgress, (scene2, message, exception) => { reject(exception || new Error(message)); }, pluginExtension, name260, pluginOptions // eslint-disable-next-line github/no-then ).catch(reject); } catch (error) { reject(error); } }); } __name(importMeshAsyncCoreAsync, "importMeshAsyncCoreAsync"); async function loadSceneImplAsync(rootUrl, sceneFilename = "", engine = EngineStore.LastCreatedEngine, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name260 = "", pluginOptions = {}) { if (!engine) { Tools.Error("No engine available"); return; } await appendSceneImplAsync(rootUrl, sceneFilename, new Scene(engine), onSuccess, onProgress, onError, pluginExtension, name260, pluginOptions); } __name(loadSceneImplAsync, "loadSceneImplAsync"); async function LoadSceneAsync(source, engine, options) { const { rootUrl = "", onProgress, pluginExtension, name: name260, pluginOptions } = options ?? {}; return await loadSceneSharedAsync(rootUrl, source, engine, onProgress, pluginExtension, name260, pluginOptions); } __name(LoadSceneAsync, "LoadSceneAsync"); async function loadSceneAsync(source, engine, options) { return await LoadSceneAsync(source, engine, options); } __name(loadSceneAsync, "loadSceneAsync"); async function loadSceneSharedAsync(rootUrl, sceneFilename, engine, onProgress, pluginExtension, name260, pluginOptions) { return await new Promise((resolve, reject) => { loadSceneImplAsync(rootUrl, sceneFilename, engine, (scene) => { resolve(scene); }, onProgress, (scene, message, exception) => { reject(exception || new Error(message)); }, pluginExtension, name260, pluginOptions); }); } __name(loadSceneSharedAsync, "loadSceneSharedAsync"); async function appendSceneImplAsync(rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name260 = "", pluginOptions = {}) { if (!scene) { Logger.Error("No scene available to append to"); return null; } const fileInfo = GetFileInfo(rootUrl, sceneFilename); if (!fileInfo) { return null; } const loadingToken = {}; scene.addPendingData(loadingToken); const disposeHandler = /* @__PURE__ */ __name(() => { scene.removePendingData(loadingToken); }, "disposeHandler"); if (SceneLoaderFlags.ShowLoadingScreen && !showingLoadingScreen) { showingLoadingScreen = true; scene.getEngine().displayLoadingUI(); scene.executeWhenReady(() => { scene.getEngine().hideLoadingUI(); showingLoadingScreen = false; }); } const errorHandler = /* @__PURE__ */ __name((message, exception) => { const errorMessage = formatErrorMessage(fileInfo, message, exception); if (onError) { onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception)); } else { Logger.Error(errorMessage); } disposeHandler(); }, "errorHandler"); const progressHandler = onProgress ? (event) => { try { onProgress(event); } catch (e) { errorHandler("Error in onProgress callback", e); } } : void 0; const successHandler = /* @__PURE__ */ __name(() => { if (onSuccess) { try { onSuccess(scene); } catch (e) { errorHandler("Error in onSuccess callback", e); } } scene.removePendingData(loadingToken); }, "successHandler"); return await loadDataAsync(fileInfo, scene, (plugin, data) => { if (plugin.load) { const syncedPlugin = plugin; if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) { return; } scene.loadingPluginName = plugin.name; successHandler(); } else { const asyncedPlugin = plugin; asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(() => { scene.loadingPluginName = plugin.name; successHandler(); }).catch((error) => { errorHandler(error.message, error); }); } }, progressHandler, errorHandler, disposeHandler, pluginExtension, name260, pluginOptions); } __name(appendSceneImplAsync, "appendSceneImplAsync"); async function AppendSceneAsync(source, scene, options) { const { rootUrl = "", onProgress, pluginExtension, name: name260, pluginOptions } = options ?? {}; await appendSceneSharedAsync(rootUrl, source, scene, onProgress, pluginExtension, name260, pluginOptions); } __name(AppendSceneAsync, "AppendSceneAsync"); async function appendSceneAsync(source, scene, options) { return await AppendSceneAsync(source, scene, options); } __name(appendSceneAsync, "appendSceneAsync"); async function appendSceneSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name260, pluginOptions) { return await new Promise((resolve, reject) => { try { appendSceneImplAsync( rootUrl, sceneFilename, scene, (scene2) => { resolve(scene2); }, onProgress, (scene2, message, exception) => { reject(exception || new Error(message)); }, pluginExtension, name260, pluginOptions // eslint-disable-next-line github/no-then ).catch(reject); } catch (error) { reject(error); } }); } __name(appendSceneSharedAsync, "appendSceneSharedAsync"); async function loadAssetContainerImplAsync(rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name260 = "", pluginOptions = {}) { if (!scene) { Logger.Error("No scene available to load asset container to"); return null; } const fileInfo = GetFileInfo(rootUrl, sceneFilename); if (!fileInfo) { return null; } const loadingToken = {}; scene.addPendingData(loadingToken); const disposeHandler = /* @__PURE__ */ __name(() => { scene.removePendingData(loadingToken); }, "disposeHandler"); const errorHandler = /* @__PURE__ */ __name((message, exception) => { const errorMessage = formatErrorMessage(fileInfo, message, exception); if (onError) { onError(scene, errorMessage, new RuntimeError(errorMessage, ErrorCodes.SceneLoaderError, exception)); } else { Logger.Error(errorMessage); } disposeHandler(); }, "errorHandler"); const progressHandler = onProgress ? (event) => { try { onProgress(event); } catch (e) { errorHandler("Error in onProgress callback", e); } } : void 0; const successHandler = /* @__PURE__ */ __name((assets) => { if (onSuccess) { try { onSuccess(assets); } catch (e) { errorHandler("Error in onSuccess callback", e); } } scene.removePendingData(loadingToken); }, "successHandler"); return await loadDataAsync(fileInfo, scene, (plugin, data) => { if (plugin.loadAssetContainer) { const syncedPlugin = plugin; const assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler); if (!assetContainer) { return; } assetContainer.populateRootNodes(); scene.loadingPluginName = plugin.name; successHandler(assetContainer); } else if (plugin.loadAssetContainerAsync) { const asyncedPlugin = plugin; asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then((assetContainer) => { assetContainer.populateRootNodes(); scene.loadingPluginName = plugin.name; successHandler(assetContainer); }).catch((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, name260, pluginOptions); } __name(loadAssetContainerImplAsync, "loadAssetContainerImplAsync"); async function LoadAssetContainerAsync(source, scene, options) { const { rootUrl = "", onProgress, pluginExtension, name: name260, pluginOptions } = options ?? {}; return await loadAssetContainerSharedAsync(rootUrl, source, scene, onProgress, pluginExtension, name260, pluginOptions); } __name(LoadAssetContainerAsync, "LoadAssetContainerAsync"); async function loadAssetContainerAsync(source, scene, options) { return await LoadAssetContainerAsync(source, scene, options); } __name(loadAssetContainerAsync, "loadAssetContainerAsync"); async function loadAssetContainerSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name260, pluginOptions) { return await new Promise((resolve, reject) => { try { loadAssetContainerImplAsync( rootUrl, sceneFilename, scene, (assets) => { resolve(assets); }, onProgress, (scene2, message, exception) => { reject(exception || new Error(message)); }, pluginExtension, name260, pluginOptions // eslint-disable-next-line github/no-then ).catch(reject); } catch (error) { reject(error); } }); } __name(loadAssetContainerSharedAsync, "loadAssetContainerSharedAsync"); async function importAnimationsImplAsync(rootUrl, sceneFilename = "", scene = EngineStore.LastCreatedScene, overwriteAnimations = true, animationGroupLoadingMode = 0, targetConverter = null, onSuccess = null, onProgress = null, onError = null, pluginExtension = null, name260 = "", pluginOptions = {}) { if (!scene) { Logger.Error("No scene available to load animations to"); return; } if (overwriteAnimations) { for (const animatable of scene.animatables) { animatable.reset(); } scene.stopAllAnimations(); const animationGroups = scene.animationGroups.slice(); for (const animationGroup of animationGroups) { animationGroup.dispose(); } const nodes = scene.getNodes(); for (const node of nodes) { if (node.animations) { node.animations = []; } } } else { switch (animationGroupLoadingMode) { case 0: const animationGroups = scene.animationGroups.slice(); for (const animationGroup of animationGroups) { animationGroup.dispose(); } break; case 1: for (const animationGroup of scene.animationGroups) { animationGroup.stop(); } break; case 2: for (const animationGroup of scene.animationGroups) { animationGroup.reset(); animationGroup.restart(); } break; case 3: break; default: Logger.Error("Unknown animation group loading mode value '" + animationGroupLoadingMode + "'"); return; } } const startingIndexForNewAnimatables = scene.animatables.length; const onAssetContainerLoaded = /* @__PURE__ */ __name((container) => { container.mergeAnimationsTo(scene, scene.animatables.slice(startingIndexForNewAnimatables), targetConverter); container.dispose(); scene.onAnimationFileImportedObservable.notifyObservers(scene); if (onSuccess) { onSuccess(scene); } }, "onAssetContainerLoaded"); await loadAssetContainerImplAsync(rootUrl, sceneFilename, scene, onAssetContainerLoaded, onProgress, onError, pluginExtension, name260, pluginOptions); } __name(importAnimationsImplAsync, "importAnimationsImplAsync"); async function ImportAnimationsAsync(source, scene, options) { const { rootUrl = "", overwriteAnimations, animationGroupLoadingMode, targetConverter, onProgress, pluginExtension, name: name260, pluginOptions } = options ?? {}; await importAnimationsSharedAsync(rootUrl, source, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onProgress, pluginExtension, name260, pluginOptions); } __name(ImportAnimationsAsync, "ImportAnimationsAsync"); async function importAnimationsAsync(source, scene, options) { return await ImportAnimationsAsync(source, scene, options); } __name(importAnimationsAsync, "importAnimationsAsync"); async function importAnimationsSharedAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onProgress, pluginExtension, name260, pluginOptions) { return await new Promise((resolve, reject) => { try { importAnimationsImplAsync( rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, (scene2) => { resolve(scene2); }, onProgress, (scene2, message, exception) => { reject(exception || new Error(message)); }, pluginExtension, name260, pluginOptions // eslint-disable-next-line github/no-then ).catch(reject); } catch (error) { reject(error); } }); } __name(importAnimationsSharedAsync, "importAnimationsSharedAsync"); var SceneLoader = class { static { __name(this, "SceneLoader"); } /** * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data */ static get ForceFullSceneLoadingForIncremental() { return SceneLoaderFlags.ForceFullSceneLoadingForIncremental; } static set ForceFullSceneLoadingForIncremental(value) { SceneLoaderFlags.ForceFullSceneLoadingForIncremental = value; } /** * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene */ static get ShowLoadingScreen() { return SceneLoaderFlags.ShowLoadingScreen; } static set ShowLoadingScreen(value) { SceneLoaderFlags.ShowLoadingScreen = value; } /** * Defines the current logging level (while loading the scene) * @ignorenaming */ // eslint-disable-next-line @typescript-eslint/naming-convention static get loggingLevel() { return SceneLoaderFlags.loggingLevel; } // eslint-disable-next-line @typescript-eslint/naming-convention static set loggingLevel(value) { SceneLoaderFlags.loggingLevel = value; } /** * Gets or set a boolean indicating if matrix weights must be cleaned upon loading */ static get CleanBoneMatrixWeights() { return SceneLoaderFlags.CleanBoneMatrixWeights; } static set CleanBoneMatrixWeights(value) { SceneLoaderFlags.CleanBoneMatrixWeights = value; } /** * Gets the default plugin (used to load Babylon files) * @returns the .babylon plugin */ static GetDefaultPlugin() { return getDefaultPlugin(); } // 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 */ static GetPluginForExtension(extension) { return getPluginForExtension(extension, true)?.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 */ static IsPluginForExtensionAvailable(extension) { return isPluginForExtensionAvailable(extension); } /** * Adds a new plugin to the list of registered plugins * @param plugin defines the plugin to add */ static RegisterPlugin(plugin) { RegisterSceneLoaderPlugin(plugin); } /** * 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, skeletons, and animationGroups 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 * @param name defines the name of the file, if the data is binary * @param pluginOptions defines the options to use with the plugin * @deprecated Please use the module level {@link ImportMeshAsync} instead */ static ImportMesh(meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name260, pluginOptions) { importMeshAsync(meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name260, pluginOptions).catch((error) => onError?.(EngineStore.LastCreatedScene, error?.message, error)); } /** * 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 * @param name defines the name of the file * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups * @deprecated Please use the module level {@link ImportMeshAsync} instead */ static async ImportMeshAsync(meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension, name260) { return await importMeshAsyncCoreAsync(meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension, name260); } /** * 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 * @param name defines the filename, if the data is binary * @deprecated Please use the module level {@link LoadSceneAsync} instead */ static Load(rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension, name260) { loadSceneImplAsync(rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension, name260).catch((error) => onError?.(EngineStore.LastCreatedScene, error?.message, error)); } /** * 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 * @param name defines the filename, if the data is binary * @returns The loaded scene * @deprecated Please use the module level {@link LoadSceneAsync} instead */ static async LoadAsync(rootUrl, sceneFilename, engine, onProgress, pluginExtension, name260) { return await loadSceneSharedAsync(rootUrl, sceneFilename, engine, onProgress, pluginExtension, name260); } /** * 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 * @param name defines the name of the file, if the data is binary * @deprecated Please use the module level {@link AppendSceneAsync} instead */ static Append(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name260) { appendSceneImplAsync(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name260).catch((error) => onError?.(scene ?? EngineStore.LastCreatedScene, error?.message, error)); } /** * 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 * @param name defines the name of the file, if the data is binary * @returns The given scene * @deprecated Please use the module level {@link AppendSceneAsync} instead */ static async AppendAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name260) { return await appendSceneSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name260); } /** * 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 * @param name defines the filename, if the data is binary * @deprecated Please use the module level {@link LoadAssetContainerAsync} instead */ static LoadAssetContainer(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name260) { loadAssetContainerImplAsync(rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension, name260).catch((error) => onError?.(scene ?? EngineStore.LastCreatedScene, error?.message, error)); } /** * 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 * @param name defines the filename, if the data is binary * @returns The loaded asset container * @deprecated Please use the module level {@link LoadAssetContainerAsync} instead */ static async LoadAssetContainerAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name260) { return await loadAssetContainerSharedAsync(rootUrl, sceneFilename, scene, onProgress, pluginExtension, name260); } /** * 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 * @param name defines the filename, if the data is binary * @deprecated Please use the module level {@link ImportAnimationsAsync} instead */ static ImportAnimations(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onSuccess, onProgress, onError, pluginExtension, name260) { importAnimationsImplAsync( rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onSuccess, onProgress, onError, pluginExtension, name260 // eslint-disable-next-line github/no-then ).catch((error) => onError?.(scene ?? EngineStore.LastCreatedScene, error?.message, error)); } /** * 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 * @param name defines the filename, if the data is binary * @returns the updated scene with imported animations * @deprecated Please use the module level {@link ImportAnimationsAsync} instead */ static async ImportAnimationsAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onSuccess, onProgress, onError, pluginExtension, name260) { return await importAnimationsSharedAsync(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onProgress, pluginExtension, name260); } }; SceneLoader.NO_LOGGING = 0; SceneLoader.MINIMAL_LOGGING = 1; SceneLoader.SUMMARY_LOGGING = 2; SceneLoader.DETAILED_LOGGING = 3; SceneLoader.OnPluginActivatedObservable = onPluginActivatedObservable; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/tools/guards.js function isAbstractMesh(object) { switch (object.getClassName?.()) { case "Mesh": case "LineMesh": case "GroundMesh": case "InstancedMesh": return true; } return false; } __name(isAbstractMesh, "isAbstractMesh"); function isMesh(object) { switch (object.getClassName?.()) { case "Mesh": case "GroundMesh": return true; } return false; } __name(isMesh, "isMesh"); function isInstancedMesh(object) { return object.getClassName?.() === "InstancedMesh"; } __name(isInstancedMesh, "isInstancedMesh"); function isBone(object) { return object.getClassName?.() === "Bone"; } __name(isBone, "isBone"); function isGroundMesh(object) { return object.getClassName?.() === "GroundMesh"; } __name(isGroundMesh, "isGroundMesh"); function isTransformNode(object) { return object.getClassName?.() === "TransformNode"; } __name(isTransformNode, "isTransformNode"); function isTexture(object) { return object?.getClassName?.() === "Texture"; } __name(isTexture, "isTexture"); function isCamera(object) { switch (object.getClassName?.()) { case "Camera": case "FreeCamera": case "TargetCamera": case "EditorCamera": case "ArcRotateCamera": case "UniversalCamera": return true; } return false; } __name(isCamera, "isCamera"); function isFreeCamera(object) { switch (object.getClassName?.()) { case "FreeCamera": case "UniversalCamera": return true; } return false; } __name(isFreeCamera, "isFreeCamera"); function isArcRotateCamera(object) { return object.getClassName?.() === "ArcRotateCamera"; } __name(isArcRotateCamera, "isArcRotateCamera"); function isPointLight(object) { return object.getClassName?.() === "PointLight"; } __name(isPointLight, "isPointLight"); function isDirectionalLight(object) { return object.getClassName?.() === "DirectionalLight"; } __name(isDirectionalLight, "isDirectionalLight"); function isSpotLight(object) { return object.getClassName?.() === "SpotLight"; } __name(isSpotLight, "isSpotLight"); function isHemisphericLight(object) { return object.getClassName?.() === "HemisphericLight"; } __name(isHemisphericLight, "isHemisphericLight"); function isLight(object) { switch (object.getClassName?.()) { case "Light": case "PointLight": case "SpotLight": case "DirectionalLight": case "HemisphericLight": return true; } return false; } __name(isLight, "isLight"); function isNode(object) { return isAbstractMesh(object) || isTransformNode(object) || isLight(object) || isCamera(object); } __name(isNode, "isNode"); function isScene(object) { return object.getClassName?.() === "Scene"; } __name(isScene, "isScene"); function isParticleSystem(object) { return object.getClassName?.() === "ParticleSystem"; } __name(isParticleSystem, "isParticleSystem"); function isGPUParticleSystem(object) { return object.getClassName?.() === "GPUParticleSystem"; } __name(isGPUParticleSystem, "isGPUParticleSystem"); function isAnyParticleSystem(object) { switch (object.getClassName?.()) { case "ParticleSystem": case "GPUParticleSystem": return true; } return false; } __name(isAnyParticleSystem, "isAnyParticleSystem"); function isSprite(object) { return object.getClassName?.() === "Sprite"; } __name(isSprite, "isSprite"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/tools/light.js init_math_vector(); init_renderTargetTexture(); function configureShadowMapRenderListPredicate(scene) { scene.lights.forEach((light) => { const shadowMap = light.getShadowGenerator()?.getShadowMap(); if (!shadowMap) { return; } shadowMap.renderListPredicate = (mesh) => { const distance = Vector3.Distance(mesh.getAbsolutePosition(), light.getAbsolutePosition()); return distance <= light.range; }; }); } __name(configureShadowMapRenderListPredicate, "configureShadowMapRenderListPredicate"); async function configureShadowMapRefreshRate(scene) { scene.executeWhenReady(() => { scene.lights.forEach((light) => { const shadowMap = light.getShadowGenerator()?.getShadowMap(); if (shadowMap) { shadowMap.refreshRate = light.metadata?.refreshRate ?? RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME; } }); }); } __name(configureShadowMapRefreshRate, "configureShadowMapRefreshRate"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/coroutine.js function inlineScheduler(coroutine, onStep, onError) { try { const step = coroutine.next(); if (step.done) { onStep(step); } else if (!step.value) { onStep(step); } else { step.value.then(() => { step.value = void 0; onStep(step); }, onError); } } catch (error) { onError(error); } } __name(inlineScheduler, "inlineScheduler"); function createYieldingScheduler(yieldAfterMS = 25) { let startTime; return (coroutine, onStep, onError) => { const currentTime = performance.now(); if (startTime === void 0 || currentTime - startTime > yieldAfterMS) { startTime = currentTime; setTimeout(() => { inlineScheduler(coroutine, onStep, onError); }, 0); } else { inlineScheduler(coroutine, onStep, onError); } }; } __name(createYieldingScheduler, "createYieldingScheduler"); function runCoroutine(coroutine, scheduler, onSuccess, onError, abortSignal) { const resume = /* @__PURE__ */ __name(() => { let reschedule; const onStep = /* @__PURE__ */ __name((stepResult) => { if (stepResult.done) { onSuccess(stepResult.value); } else { if (reschedule === void 0) { reschedule = true; } else { resume(); } } }, "onStep"); do { reschedule = void 0; if (!abortSignal || !abortSignal.aborted) { scheduler(coroutine, onStep, onError); } else { onError(new Error("Aborted")); } if (reschedule === void 0) { reschedule = false; } } while (reschedule); }, "resume"); resume(); } __name(runCoroutine, "runCoroutine"); function runCoroutineSync(coroutine, abortSignal) { let result; runCoroutine(coroutine, inlineScheduler, (r) => result = r, (e) => { throw e; }, abortSignal); return result; } __name(runCoroutineSync, "runCoroutineSync"); async function runCoroutineAsync(coroutine, scheduler, abortSignal) { return await new Promise((resolve, reject) => { runCoroutine(coroutine, scheduler, resolve, reject, abortSignal); }); } __name(runCoroutineAsync, "runCoroutineAsync"); function makeSyncFunction(coroutineFactory, abortSignal) { return (...params) => { return runCoroutineSync(coroutineFactory(...params), abortSignal); }; } __name(makeSyncFunction, "makeSyncFunction"); function makeAsyncFunction(coroutineFactory, scheduler, abortSignal) { return (...params) => { return runCoroutineAsync(coroutineFactory(...params), scheduler, abortSignal); }; } __name(makeAsyncFunction, "makeAsyncFunction"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Collisions/intersectionInfo.js var IntersectionInfo = class { static { __name(this, "IntersectionInfo"); } constructor(bu, bv, distance) { this.bu = bu; this.bv = bv; this.distance = distance; this.faceId = 0; this.subMeshId = 0; this._internalSubMeshId = 0; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Maths/math.functions.js init_tslib_es6(); init_math_vector(); init_decorators(); var MathHelpers = class { static { __name(this, "MathHelpers"); } static extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, minimum, maximum) { for (let index = indexStart; index < indexStart + indexCount; index++) { const offset = indices[index] * 3; const x = positions[offset]; const y = positions[offset + 1]; const z = positions[offset + 2]; minimum.minimizeInPlaceFromFloats(x, y, z); maximum.maximizeInPlaceFromFloats(x, y, z); } } static extractMinAndMax(positions, start, count, stride, minimum, maximum) { for (let index = start, offset = start * stride; index < start + count; index++, offset += stride) { const x = positions[offset]; const y = positions[offset + 1]; const z = positions[offset + 2]; minimum.minimizeInPlaceFromFloats(x, y, z); maximum.maximizeInPlaceFromFloats(x, y, z); } } }; __decorate([ nativeOverride.filter((...[positions, indices]) => !Array.isArray(positions) && !Array.isArray(indices)) // eslint-disable-next-line @typescript-eslint/naming-convention ], MathHelpers, "extractMinAndMaxIndexed", null); __decorate([ nativeOverride.filter((...[positions]) => !Array.isArray(positions)) // eslint-disable-next-line @typescript-eslint/naming-convention ], MathHelpers, "extractMinAndMax", null); function extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, bias = null) { const minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); const maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); MathHelpers.extractMinAndMaxIndexed(positions, indices, indexStart, indexCount, minimum, maximum); if (bias) { minimum.x -= minimum.x * bias.x + bias.y; minimum.y -= minimum.y * bias.x + bias.y; minimum.z -= minimum.z * bias.x + bias.y; maximum.x += maximum.x * bias.x + bias.y; maximum.y += maximum.y * bias.x + bias.y; maximum.z += maximum.z * bias.x + bias.y; } return { minimum, maximum }; } __name(extractMinAndMaxIndexed, "extractMinAndMaxIndexed"); function extractMinAndMax(positions, start, count, bias = null, stride) { const minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); const maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); if (!stride) { stride = 3; } MathHelpers.extractMinAndMax(positions, start, count, stride, minimum, maximum); if (bias) { minimum.x -= minimum.x * bias.x + bias.y; minimum.y -= minimum.y * bias.x + bias.y; minimum.z -= minimum.z * bias.x + bias.y; maximum.x += maximum.x * bias.x + bias.y; maximum.y += maximum.y * bias.x + bias.y; maximum.z += maximum.z * bias.x + bias.y; } return { minimum, maximum }; } __name(extractMinAndMax, "extractMinAndMax"); function FixFlippedFaces(positions, indices) { const boundingInfo = extractMinAndMax(positions, 0, positions.length / 3); const inside = boundingInfo.maximum.subtract(boundingInfo.minimum).scale(0.5).add(boundingInfo.minimum); const tmpVectorA = new Vector3(); const tmpVectorB = new Vector3(); const tmpVectorC = new Vector3(); const tmpVectorAB = new Vector3(); const tmpVectorAC = new Vector3(); const tmpVectorNormal = new Vector3(); const tmpVectorAvgNormal = new Vector3(); for (let index = 0; index < indices.length; index += 3) { const a = indices[index]; const b = indices[index + 1]; const c = indices[index + 2]; tmpVectorA.fromArray(positions, a * 3); tmpVectorB.fromArray(positions, b * 3); tmpVectorC.fromArray(positions, c * 3); tmpVectorB.subtractToRef(tmpVectorA, tmpVectorAB); tmpVectorC.subtractToRef(tmpVectorA, tmpVectorAC); Vector3.CrossToRef(tmpVectorAB, tmpVectorAC, tmpVectorNormal); tmpVectorNormal.normalize(); const avgX = tmpVectorA.x + tmpVectorB.x + tmpVectorC.x; const avgY = tmpVectorA.y + tmpVectorB.y + tmpVectorC.y; const avgZ = tmpVectorA.z + tmpVectorB.z + tmpVectorC.z; tmpVectorAvgNormal.set(avgX / 3, avgY / 3, avgZ / 3); tmpVectorAvgNormal.subtractInPlace(inside); tmpVectorAvgNormal.normalize(); if (Vector3.Dot(tmpVectorNormal, tmpVectorAvgNormal) >= 0) { indices[index] = c; indices[index + 2] = a; } } } __name(FixFlippedFaces, "FixFlippedFaces"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/subMesh.js init_buffer(); init_boundingInfo(); init_drawWrapper(); var SubMesh = class _SubMesh { static { __name(this, "SubMesh"); } /** * Gets material defines used by the effect associated to the sub mesh */ get materialDefines() { return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.defines : this._getDrawWrapper()?.defines; } /** * Sets material defines used by the effect associated to the sub mesh */ set materialDefines(defines) { const drawWrapper = this._mainDrawWrapperOverride ?? this._getDrawWrapper(void 0, true); drawWrapper.defines = defines; } /** * @internal */ _getDrawWrapper(passId, createIfNotExisting = false) { passId = passId ?? this._engine.currentRenderPassId; let drawWrapper = this._drawWrappers[passId]; if (!drawWrapper && createIfNotExisting) { this._drawWrappers[passId] = drawWrapper = new DrawWrapper(this._mesh.getScene().getEngine()); } return drawWrapper; } /** * @internal */ _removeDrawWrapper(passId, disposeWrapper = true, immediate = false) { if (disposeWrapper) { this._drawWrappers[passId]?.dispose(immediate); } this._drawWrappers[passId] = void 0; } /** * Gets associated (main) effect (possibly the effect override if defined) */ get effect() { return this._mainDrawWrapperOverride ? this._mainDrawWrapperOverride.effect : this._getDrawWrapper()?.effect ?? null; } /** @internal */ get _drawWrapper() { return this._mainDrawWrapperOverride ?? this._getDrawWrapper(void 0, true); } /** @internal */ get _drawWrapperOverride() { return this._mainDrawWrapperOverride; } /** * @internal */ _setMainDrawWrapperOverride(wrapper) { this._mainDrawWrapperOverride = wrapper; } /** * Sets associated effect (effect used to render this submesh) * @param effect defines the effect to associate with * @param defines defines the set of defines used to compile this effect * @param materialContext material context associated to the effect * @param resetContext true to reset the draw context */ setEffect(effect, defines = null, materialContext, resetContext = true) { const drawWrapper = this._drawWrapper; drawWrapper.setEffect(effect, defines, resetContext); if (materialContext !== void 0) { drawWrapper.materialContext = materialContext; } if (!effect) { drawWrapper.defines = null; drawWrapper.materialContext = void 0; } } /** * Resets the draw wrappers cache * @param passId If provided, releases only the draw wrapper corresponding to this render pass id * @param immediate If true, the draw wrapper will dispose the effect immediately (false by default) */ resetDrawCache(passId, immediate = false) { if (this._drawWrappers) { if (passId !== void 0) { this._removeDrawWrapper(passId, true, immediate); return; } else { for (const drawWrapper of this._drawWrappers) { drawWrapper?.dispose(immediate); } } } this._drawWrappers = []; } /** * Add a new submesh to a mesh * @param materialIndex defines the material index to use * @param verticesStart defines vertex index start * @param verticesCount defines vertices count * @param indexStart defines index start * @param indexCount defines indices count * @param mesh defines the parent mesh * @param renderingMesh defines an optional rendering mesh * @param createBoundingBox defines if bounding box should be created for this submesh * @returns the new submesh */ static AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox = true) { return new _SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox); } /** * Creates a new submesh * @param materialIndex defines the material index to use * @param verticesStart defines vertex index start * @param verticesCount defines vertices count * @param indexStart defines index start * @param indexCount defines indices count * @param mesh defines the parent mesh * @param renderingMesh defines an optional rendering mesh * @param createBoundingBox defines if bounding box should be created for this submesh * @param addToMesh defines a boolean indicating that the submesh must be added to the mesh.subMeshes array (true by default) */ constructor(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox = true, addToMesh = true) { this.materialIndex = materialIndex; this.verticesStart = verticesStart; this.verticesCount = verticesCount; this.indexStart = indexStart; this.indexCount = indexCount; this._mainDrawWrapperOverride = null; this._linesIndexCount = 0; this._linesIndexBuffer = null; this._lastColliderWorldVertices = null; this._lastColliderTransformMatrix = null; this._wasDispatched = false; this._renderId = 0; this._alphaIndex = 0; this._distanceToCamera = 0; this._currentMaterial = null; this._mesh = mesh; this._renderingMesh = renderingMesh || mesh; if (addToMesh) { mesh.subMeshes.push(this); } this._engine = this._mesh.getScene().getEngine(); this.resetDrawCache(); this._trianglePlanes = []; this._id = mesh.subMeshes.length - 1; if (createBoundingBox) { this.refreshBoundingInfo(); mesh.computeWorldMatrix(true); } } /** * Returns true if this submesh covers the entire parent mesh * @ignorenaming */ // eslint-disable-next-line @typescript-eslint/naming-convention get IsGlobal() { return this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices() && this.indexStart === 0 && this.indexCount === this._mesh.getTotalIndices(); } /** * Returns the submesh BoundingInfo object * @returns current bounding info (or mesh's one if the submesh is global) */ getBoundingInfo() { if (this.IsGlobal || this._mesh.hasThinInstances) { return this._mesh.getBoundingInfo(); } return this._boundingInfo; } /** * Sets the submesh BoundingInfo * @param boundingInfo defines the new bounding info to use * @returns the SubMesh */ setBoundingInfo(boundingInfo) { this._boundingInfo = boundingInfo; return this; } /** * Returns the mesh of the current submesh * @returns the parent mesh */ getMesh() { return this._mesh; } /** * Returns the rendering mesh of the submesh * @returns the rendering mesh (could be different from parent mesh) */ getRenderingMesh() { return this._renderingMesh; } /** * Returns the replacement mesh of the submesh * @returns the replacement mesh (could be different from parent mesh) */ getReplacementMesh() { return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null; } /** * Returns the effective mesh of the submesh * @returns the effective mesh (could be different from parent mesh) */ getEffectiveMesh() { const replacementMesh = this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : null; return replacementMesh ? replacementMesh : this._renderingMesh; } /** * Returns the submesh material * @param getDefaultMaterial Defines whether or not to get the default material if nothing has been defined. * @returns null or the current material */ getMaterial(getDefaultMaterial = true) { const rootMaterial = this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId) ?? this._renderingMesh.material; if (!rootMaterial) { return getDefaultMaterial && this._mesh.getScene()._hasDefaultMaterial ? this._mesh.getScene().defaultMaterial : null; } else if (this._isMultiMaterial(rootMaterial)) { const effectiveMaterial = rootMaterial.getSubMaterial(this.materialIndex); if (this._currentMaterial !== effectiveMaterial) { this._currentMaterial = effectiveMaterial; this.resetDrawCache(); } return effectiveMaterial; } return rootMaterial; } _isMultiMaterial(material) { return material.getSubMaterial !== void 0; } // Methods /** * Sets a new updated BoundingInfo object to the submesh * @param data defines an optional position array to use to determine the bounding info * @returns the SubMesh */ refreshBoundingInfo(data = null) { this._lastColliderWorldVertices = null; if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) { return this; } if (!data) { data = this._renderingMesh.getVerticesData(VertexBuffer.PositionKind); } if (!data) { this._boundingInfo = this._mesh.getBoundingInfo(); return this; } const indices = this._renderingMesh.getIndices(); let extend; if (this.indexStart === 0 && this.indexCount === indices.length) { const boundingInfo = this._renderingMesh.getBoundingInfo(); extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() }; } else { extend = extractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias); } if (this._boundingInfo) { this._boundingInfo.reConstruct(extend.minimum, extend.maximum); } else { this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum); } return this; } /** * @internal */ _checkCollision(collider) { const boundingInfo = this.getBoundingInfo(); return boundingInfo._checkCollision(collider); } /** * Updates the submesh BoundingInfo * @param world defines the world matrix to use to update the bounding info * @returns the submesh */ updateBoundingInfo(world) { let boundingInfo = this.getBoundingInfo(); if (!boundingInfo) { this.refreshBoundingInfo(); boundingInfo = this.getBoundingInfo(); } if (boundingInfo) { boundingInfo.update(world); } return this; } /** * True is the submesh bounding box intersects the frustum defined by the passed array of planes. * @param frustumPlanes defines the frustum planes * @returns true if the submesh is intersecting with the frustum */ isInFrustum(frustumPlanes) { const boundingInfo = this.getBoundingInfo(); if (!boundingInfo) { return false; } return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy); } /** * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes * @param frustumPlanes defines the frustum planes * @returns true if the submesh is inside the frustum */ isCompletelyInFrustum(frustumPlanes) { const boundingInfo = this.getBoundingInfo(); if (!boundingInfo) { return false; } return boundingInfo.isCompletelyInFrustum(frustumPlanes); } /** * Renders the submesh * @param enableAlphaMode defines if alpha needs to be used * @returns the submesh */ render(enableAlphaMode) { this._renderingMesh.render(this, enableAlphaMode, this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : void 0); return this; } /** * @internal */ _getLinesIndexBuffer(indices, engine) { if (!this._linesIndexBuffer) { const adjustedIndexCount = Math.floor(this.indexCount / 3) * 6; const shouldUseUint32 = this.verticesStart + this.verticesCount > 65535; const linesIndices = shouldUseUint32 ? new Uint32Array(adjustedIndexCount) : new Uint16Array(adjustedIndexCount); let offset = 0; if (indices.length === 0) { for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) { linesIndices[offset++] = index; linesIndices[offset++] = index + 1; linesIndices[offset++] = index + 1; linesIndices[offset++] = index + 2; linesIndices[offset++] = index + 2; linesIndices[offset++] = index; } } else { for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) { linesIndices[offset++] = indices[index]; linesIndices[offset++] = indices[index + 1]; linesIndices[offset++] = indices[index + 1]; linesIndices[offset++] = indices[index + 2]; linesIndices[offset++] = indices[index + 2]; linesIndices[offset++] = indices[index]; } } this._linesIndexBuffer = engine.createIndexBuffer(linesIndices); this._linesIndexCount = linesIndices.length; } return this._linesIndexBuffer; } /** * Checks if the submesh intersects with a ray * @param ray defines the ray to test * @returns true is the passed ray intersects the submesh bounding box */ canIntersects(ray) { const boundingInfo = this.getBoundingInfo(); if (!boundingInfo) { return false; } return ray.intersectsBox(boundingInfo.boundingBox); } /** * Intersects current submesh with a ray * @param ray defines the ray to test * @param positions defines mesh's positions array * @param indices defines mesh's indices array * @param fastCheck defines if the first intersection will be used (and not the closest) * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected * @returns intersection info or null if no intersection */ intersects(ray, positions, indices, fastCheck, trianglePredicate) { const material = this.getMaterial(); if (!material) { return null; } let step = 3; let checkStopper = false; switch (material.fillMode) { case 3: case 5: case 6: case 8: return null; case 7: step = 1; checkStopper = true; break; default: break; } if (material.fillMode === 4) { if (!indices.length) { return this._intersectUnIndexedLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck); } return this._intersectLines(ray, positions, indices, this._mesh.intersectionThreshold, fastCheck); } else { if (!indices.length && this._mesh._unIndexed) { return this._intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate); } return this._intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate); } } /** * @internal */ _intersectLines(ray, positions, indices, intersectionThreshold, fastCheck) { let intersectInfo = null; for (let index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) { const p0 = positions[indices[index]]; const p1 = positions[indices[index + 1]]; const length = ray.intersectionSegment(p0, p1, intersectionThreshold); if (length < 0) { continue; } if (fastCheck || !intersectInfo || length < intersectInfo.distance) { intersectInfo = new IntersectionInfo(null, null, length); intersectInfo.faceId = index / 2; if (fastCheck) { break; } } } return intersectInfo; } /** * @internal */ _intersectUnIndexedLines(ray, positions, indices, intersectionThreshold, fastCheck) { let intersectInfo = null; for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 2) { const p0 = positions[index]; const p1 = positions[index + 1]; const length = ray.intersectionSegment(p0, p1, intersectionThreshold); if (length < 0) { continue; } if (fastCheck || !intersectInfo || length < intersectInfo.distance) { intersectInfo = new IntersectionInfo(null, null, length); intersectInfo.faceId = index / 2; if (fastCheck) { break; } } } return intersectInfo; } /** * @internal */ _intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate) { let intersectInfo = null; let faceId = -1; for (let index = this.indexStart; index < this.indexStart + this.indexCount - (3 - step); index += step) { faceId++; const indexA = indices[index]; const indexB = indices[index + 1]; const indexC = indices[index + 2]; if (checkStopper && indexC === 4294967295) { index += 2; continue; } const p0 = positions[indexA]; const p1 = positions[indexB]; const p2 = positions[indexC]; if (!p0 || !p1 || !p2) { continue; } if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray, indexA, indexB, indexC)) { continue; } const currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2); if (currentIntersectInfo) { if (currentIntersectInfo.distance < 0) { continue; } if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) { intersectInfo = currentIntersectInfo; intersectInfo.faceId = faceId; if (fastCheck) { break; } } } } return intersectInfo; } /** * @internal */ _intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate) { let intersectInfo = null; for (let index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 3) { const p0 = positions[index]; const p1 = positions[index + 1]; const p2 = positions[index + 2]; if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray, -1, -1, -1)) { continue; } const currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2); if (currentIntersectInfo) { if (currentIntersectInfo.distance < 0) { continue; } if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) { intersectInfo = currentIntersectInfo; intersectInfo.faceId = index / 3; if (fastCheck) { break; } } } } return intersectInfo; } /** @internal */ _rebuild() { if (this._linesIndexBuffer) { this._linesIndexBuffer = null; } } // Clone /** * Creates a new submesh from the passed mesh * @param newMesh defines the new hosting mesh * @param newRenderingMesh defines an optional rendering mesh * @returns the new submesh */ clone(newMesh, newRenderingMesh) { const result = new _SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false); if (!this.IsGlobal) { const boundingInfo = this.getBoundingInfo(); if (!boundingInfo) { return result; } result._boundingInfo = new BoundingInfo(boundingInfo.minimum, boundingInfo.maximum); } return result; } // Dispose /** * Release associated resources * @param immediate If true, the effect will be disposed immediately (false by default) */ dispose(immediate = false) { if (this._linesIndexBuffer) { this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer); this._linesIndexBuffer = null; } const index = this._mesh.subMeshes.indexOf(this); this._mesh.subMeshes.splice(index, 1); this.resetDrawCache(void 0, immediate); } /** * Gets the class name * @returns the string "SubMesh". */ getClassName() { return "SubMesh"; } // Statics /** * Creates a new submesh from indices data * @param materialIndex the index of the main mesh material * @param startIndex the index where to start the copy in the mesh indices array * @param indexCount the number of indices to copy then from the startIndex * @param mesh the main mesh to create the submesh from * @param renderingMesh the optional rendering mesh * @param createBoundingBox defines if bounding box should be created for this submesh * @returns a new submesh */ static CreateFromIndices(materialIndex, startIndex, indexCount, mesh, renderingMesh, createBoundingBox = true) { let minVertexIndex = Number.MAX_VALUE; let maxVertexIndex = -Number.MAX_VALUE; const whatWillRender = renderingMesh || mesh; const indices = whatWillRender.getIndices(); for (let index = startIndex; index < startIndex + indexCount; index++) { const vertexIndex = indices[index]; if (vertexIndex < minVertexIndex) { minVertexIndex = vertexIndex; } if (vertexIndex > maxVertexIndex) { maxVertexIndex = vertexIndex; } } return new _SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh, createBoundingBox); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/mesh.vertexData.js init_tslib_es6(); init_math_vector(); init_buffer(); init_devTools(); init_math_color(); init_logger(); init_decorators(); init_error(); var VertexDataMaterialInfo = class { static { __name(this, "VertexDataMaterialInfo"); } }; var VertexData = class _VertexData { static { __name(this, "VertexData"); } /** * Creates a new VertexData */ constructor() { this.uniqueId = 0; this.metadata = {}; this._applyTo = makeSyncFunction(this._applyToCoroutine.bind(this)); this.uniqueId = _VertexData._UniqueIdGenerator; _VertexData._UniqueIdGenerator++; } /** * Uses the passed data array to set the set the values for the specified kind of data * @param data a linear array of floating numbers * @param kind the type of data that is being set, eg positions, colors etc */ set(data, kind) { if (!data.length) { Logger.Warn(`Setting vertex data kind '${kind}' with an empty array`); } switch (kind) { case VertexBuffer.PositionKind: this.positions = data; break; case VertexBuffer.NormalKind: this.normals = data; break; case VertexBuffer.TangentKind: this.tangents = data; break; case VertexBuffer.UVKind: this.uvs = data; break; case VertexBuffer.UV2Kind: this.uvs2 = data; break; case VertexBuffer.UV3Kind: this.uvs3 = data; break; case VertexBuffer.UV4Kind: this.uvs4 = data; break; case VertexBuffer.UV5Kind: this.uvs5 = data; break; case VertexBuffer.UV6Kind: this.uvs6 = data; break; case VertexBuffer.ColorKind: this.colors = data; break; case VertexBuffer.MatricesIndicesKind: this.matricesIndices = data; break; case VertexBuffer.MatricesWeightsKind: this.matricesWeights = data; break; case VertexBuffer.MatricesIndicesExtraKind: this.matricesIndicesExtra = data; break; case VertexBuffer.MatricesWeightsExtraKind: this.matricesWeightsExtra = data; break; } } /** * Associates the vertexData to the passed Mesh. * Sets it as updatable or not (default `false`) * @param mesh the mesh the vertexData is applied to * @param updatable when used and having the value true allows new data to update the vertexData * @returns the VertexData */ applyToMesh(mesh, updatable) { this._applyTo(mesh, updatable, false); return this; } /** * Associates the vertexData to the passed Geometry. * Sets it as updatable or not (default `false`) * @param geometry the geometry the vertexData is applied to * @param updatable when used and having the value true allows new data to update the vertexData * @returns VertexData */ applyToGeometry(geometry, updatable) { this._applyTo(geometry, updatable, false); return this; } /** * Updates the associated mesh * @param mesh the mesh to be updated * @returns VertexData */ updateMesh(mesh) { this._update(mesh); return this; } /** * Updates the associated geometry * @param geometry the geometry to be updated * @returns VertexData. */ updateGeometry(geometry) { this._update(geometry); return this; } /** * @internal */ *_applyToCoroutine(meshOrGeometry, updatable = false, isAsync) { if (this.positions) { meshOrGeometry.setVerticesData(VertexBuffer.PositionKind, this.positions, updatable); if (isAsync) { yield; } } if (this.normals) { meshOrGeometry.setVerticesData(VertexBuffer.NormalKind, this.normals, updatable); if (isAsync) { yield; } } if (this.tangents) { meshOrGeometry.setVerticesData(VertexBuffer.TangentKind, this.tangents, updatable); if (isAsync) { yield; } } if (this.uvs) { meshOrGeometry.setVerticesData(VertexBuffer.UVKind, this.uvs, updatable); if (isAsync) { yield; } } if (this.uvs2) { meshOrGeometry.setVerticesData(VertexBuffer.UV2Kind, this.uvs2, updatable); if (isAsync) { yield; } } if (this.uvs3) { meshOrGeometry.setVerticesData(VertexBuffer.UV3Kind, this.uvs3, updatable); if (isAsync) { yield; } } if (this.uvs4) { meshOrGeometry.setVerticesData(VertexBuffer.UV4Kind, this.uvs4, updatable); if (isAsync) { yield; } } if (this.uvs5) { meshOrGeometry.setVerticesData(VertexBuffer.UV5Kind, this.uvs5, updatable); if (isAsync) { yield; } } if (this.uvs6) { meshOrGeometry.setVerticesData(VertexBuffer.UV6Kind, this.uvs6, updatable); if (isAsync) { yield; } } if (this.colors) { const stride = this.positions && this.colors.length === this.positions.length ? 3 : 4; meshOrGeometry.setVerticesData(VertexBuffer.ColorKind, this.colors, updatable, stride); if (this.hasVertexAlpha && meshOrGeometry.hasVertexAlpha !== void 0) { meshOrGeometry.hasVertexAlpha = true; } if (isAsync) { yield; } } if (this.matricesIndices) { meshOrGeometry.setVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable); if (isAsync) { yield; } } if (this.matricesWeights) { meshOrGeometry.setVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable); if (isAsync) { yield; } } if (this.matricesIndicesExtra) { meshOrGeometry.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable); if (isAsync) { yield; } } if (this.matricesWeightsExtra) { meshOrGeometry.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable); if (isAsync) { yield; } } if (this.indices) { meshOrGeometry.setIndices(this.indices, null, updatable); if (isAsync) { yield; } } else { meshOrGeometry.setIndices([], null); } if (meshOrGeometry.subMeshes && this.materialInfos && this.materialInfos.length > 1) { const mesh = meshOrGeometry; mesh.subMeshes = []; for (const matInfo of this.materialInfos) { new SubMesh(matInfo.materialIndex, matInfo.verticesStart, matInfo.verticesCount, matInfo.indexStart, matInfo.indexCount, mesh); } } return this; } _update(meshOrGeometry, updateExtends, makeItUnique) { if (this.positions) { meshOrGeometry.updateVerticesData(VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique); } if (this.normals) { meshOrGeometry.updateVerticesData(VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique); } if (this.tangents) { meshOrGeometry.updateVerticesData(VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique); } if (this.uvs) { meshOrGeometry.updateVerticesData(VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique); } if (this.uvs2) { meshOrGeometry.updateVerticesData(VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique); } if (this.uvs3) { meshOrGeometry.updateVerticesData(VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique); } if (this.uvs4) { meshOrGeometry.updateVerticesData(VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique); } if (this.uvs5) { meshOrGeometry.updateVerticesData(VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique); } if (this.uvs6) { meshOrGeometry.updateVerticesData(VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique); } if (this.colors) { meshOrGeometry.updateVerticesData(VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique); } if (this.matricesIndices) { meshOrGeometry.updateVerticesData(VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique); } if (this.matricesWeights) { meshOrGeometry.updateVerticesData(VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique); } if (this.matricesIndicesExtra) { meshOrGeometry.updateVerticesData(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique); } if (this.matricesWeightsExtra) { meshOrGeometry.updateVerticesData(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique); } if (this.indices) { meshOrGeometry.setIndices(this.indices, null); } return this; } static _TransformVector3Coordinates(coordinates, transformation, offset = 0, length = coordinates.length) { const coordinate = TmpVectors.Vector3[0]; const transformedCoordinate = TmpVectors.Vector3[1]; for (let index = offset; index < offset + length; index += 3) { Vector3.FromArrayToRef(coordinates, index, coordinate); Vector3.TransformCoordinatesToRef(coordinate, transformation, transformedCoordinate); coordinates[index] = transformedCoordinate.x; coordinates[index + 1] = transformedCoordinate.y; coordinates[index + 2] = transformedCoordinate.z; } } static _TransformVector3Normals(normals, transformation, offset = 0, length = normals.length) { const normal = TmpVectors.Vector3[0]; const transformedNormal = TmpVectors.Vector3[1]; for (let index = offset; index < offset + length; index += 3) { Vector3.FromArrayToRef(normals, index, normal); Vector3.TransformNormalToRef(normal, transformation, transformedNormal); normals[index] = transformedNormal.x; normals[index + 1] = transformedNormal.y; normals[index + 2] = transformedNormal.z; } } static _TransformVector4Normals(normals, transformation, offset = 0, length = normals.length) { const normal = TmpVectors.Vector4[0]; const transformedNormal = TmpVectors.Vector4[1]; for (let index = offset; index < offset + length; index += 4) { Vector4.FromArrayToRef(normals, index, normal); Vector4.TransformNormalToRef(normal, transformation, transformedNormal); normals[index] = transformedNormal.x; normals[index + 1] = transformedNormal.y; normals[index + 2] = transformedNormal.z; normals[index + 3] = transformedNormal.w; } } static _FlipFaces(indices, offset = 0, length = indices.length) { for (let index = offset; index < offset + length; index += 3) { const tmp = indices[index + 1]; indices[index + 1] = indices[index + 2]; indices[index + 2] = tmp; } } /** * Transforms each position and each normal of the vertexData according to the passed Matrix * @param matrix the transforming matrix * @returns the VertexData */ transform(matrix) { const flip = matrix.determinant() < 0; if (this.positions) { _VertexData._TransformVector3Coordinates(this.positions, matrix); } if (this.normals) { _VertexData._TransformVector3Normals(this.normals, matrix); } if (this.tangents) { _VertexData._TransformVector4Normals(this.tangents, matrix); } if (flip && this.indices) { _VertexData._FlipFaces(this.indices); } return this; } /** * Generates an array of vertex data where each vertex data only has one material info * @returns An array of VertexData */ // eslint-disable-next-line @typescript-eslint/naming-convention splitBasedOnMaterialID() { if (!this.materialInfos || this.materialInfos.length < 2) { return [this]; } const result = []; for (const materialInfo of this.materialInfos) { const vertexData = new _VertexData(); if (this.positions) { vertexData.positions = this.positions.slice(materialInfo.verticesStart * 3, (materialInfo.verticesCount + materialInfo.verticesStart) * 3); } if (this.normals) { vertexData.normals = this.normals.slice(materialInfo.verticesStart * 3, (materialInfo.verticesCount + materialInfo.verticesStart) * 3); } if (this.tangents) { vertexData.tangents = this.tangents.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); } if (this.colors) { vertexData.colors = this.colors.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); } if (this.uvs) { vertexData.uvs = this.uvs.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); } if (this.uvs2) { vertexData.uvs2 = this.uvs2.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); } if (this.uvs3) { vertexData.uvs3 = this.uvs3.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); } if (this.uvs4) { vertexData.uvs4 = this.uvs4.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); } if (this.uvs5) { vertexData.uvs5 = this.uvs5.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); } if (this.uvs6) { vertexData.uvs6 = this.uvs6.slice(materialInfo.verticesStart * 2, (materialInfo.verticesCount + materialInfo.verticesStart) * 2); } if (this.matricesIndices) { vertexData.matricesIndices = this.matricesIndices.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); } if (this.matricesIndicesExtra) { vertexData.matricesIndicesExtra = this.matricesIndicesExtra.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); } if (this.matricesWeights) { vertexData.matricesWeights = this.matricesWeights.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); } if (this.matricesWeightsExtra) { vertexData.matricesWeightsExtra = this.matricesWeightsExtra.slice(materialInfo.verticesStart * 4, (materialInfo.verticesCount + materialInfo.verticesStart) * 4); } if (this.indices) { vertexData.indices = []; for (let index = materialInfo.indexStart; index < materialInfo.indexStart + materialInfo.indexCount; index++) { vertexData.indices.push(this.indices[index] - materialInfo.verticesStart); } } const newMaterialInfo = new VertexDataMaterialInfo(); newMaterialInfo.indexStart = 0; newMaterialInfo.indexCount = vertexData.indices ? vertexData.indices.length : 0; newMaterialInfo.materialIndex = materialInfo.materialIndex; newMaterialInfo.verticesStart = 0; newMaterialInfo.verticesCount = (vertexData.positions ? vertexData.positions.length : 0) / 3; vertexData.materialInfos = [newMaterialInfo]; result.push(vertexData); } return result; } /** * Merges the passed VertexData into the current one * @param others the VertexData to be merged into the current one * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array * @param forceCloneIndices defines a boolean indicating if indices are forced to be cloned * @param mergeMaterialIds defines a boolean indicating if we need to merge the material infos * @param enableCompletion defines a boolean indicating if the vertex data should be completed to be compatible * @returns the modified VertexData */ merge(others, use32BitsIndices = false, forceCloneIndices = false, mergeMaterialIds = false, enableCompletion = false) { const vertexDatas = Array.isArray(others) ? others.map((other) => { return { vertexData: other }; }) : [{ vertexData: others }]; return runCoroutineSync(this._mergeCoroutine(void 0, vertexDatas, use32BitsIndices, false, forceCloneIndices, mergeMaterialIds, enableCompletion)); } /** * @internal */ *_mergeCoroutine(transform, vertexDatas, use32BitsIndices = false, isAsync, forceCloneIndices, mergeMaterialIds = false, enableCompletion = false) { this._validate(); let others = vertexDatas.map((vertexData) => vertexData.vertexData); let root = this; if (enableCompletion) { for (const other of others) { if (!other) { continue; } other._validate(); if (!this.normals && other.normals) { this.normals = new Float32Array(this.positions.length); } if (!this.tangents && other.tangents) { this.tangents = new Float32Array(this.positions.length / 3 * 4); } if (!this.uvs && other.uvs) { this.uvs = new Float32Array(this.positions.length / 3 * 2); } if (!this.uvs2 && other.uvs2) { this.uvs2 = new Float32Array(this.positions.length / 3 * 2); } if (!this.uvs3 && other.uvs3) { this.uvs3 = new Float32Array(this.positions.length / 3 * 2); } if (!this.uvs4 && other.uvs4) { this.uvs4 = new Float32Array(this.positions.length / 3 * 2); } if (!this.uvs5 && other.uvs5) { this.uvs5 = new Float32Array(this.positions.length / 3 * 2); } if (!this.uvs6 && other.uvs6) { this.uvs6 = new Float32Array(this.positions.length / 3 * 2); } if (!this.colors && other.colors) { this.colors = new Float32Array(this.positions.length / 3 * 4); this.colors.fill(1); } if (!this.matricesIndices && other.matricesIndices) { this.matricesIndices = new Float32Array(this.positions.length / 3 * 4); } if (!this.matricesWeights && other.matricesWeights) { this.matricesWeights = new Float32Array(this.positions.length / 3 * 4); } if (!this.matricesIndicesExtra && other.matricesIndicesExtra) { this.matricesIndicesExtra = new Float32Array(this.positions.length / 3 * 4); } if (!this.matricesWeightsExtra && other.matricesWeightsExtra) { this.matricesWeightsExtra = new Float32Array(this.positions.length / 3 * 4); } } } for (const other of others) { if (!other) { continue; } if (!enableCompletion) { other._validate(); if (!this.normals !== !other.normals || !this.tangents !== !other.tangents || !this.uvs !== !other.uvs || !this.uvs2 !== !other.uvs2 || !this.uvs3 !== !other.uvs3 || !this.uvs4 !== !other.uvs4 || !this.uvs5 !== !other.uvs5 || !this.uvs6 !== !other.uvs6 || !this.colors !== !other.colors || !this.matricesIndices !== !other.matricesIndices || !this.matricesWeights !== !other.matricesWeights || !this.matricesIndicesExtra !== !other.matricesIndicesExtra || !this.matricesWeightsExtra !== !other.matricesWeightsExtra) { throw new Error("Cannot merge vertex data that do not have the same set of attributes"); } } else { if (this.normals && !other.normals) { other.normals = new Float32Array(other.positions.length); } if (this.tangents && !other.tangents) { other.tangents = new Float32Array(other.positions.length / 3 * 4); } if (this.uvs && !other.uvs) { other.uvs = new Float32Array(other.positions.length / 3 * 2); } if (this.uvs2 && !other.uvs2) { other.uvs2 = new Float32Array(other.positions.length / 3 * 2); } if (this.uvs3 && !other.uvs3) { other.uvs3 = new Float32Array(other.positions.length / 3 * 2); } if (this.uvs4 && !other.uvs4) { other.uvs4 = new Float32Array(other.positions.length / 3 * 2); } if (this.uvs5 && !other.uvs5) { other.uvs5 = new Float32Array(other.positions.length / 3 * 2); } if (this.uvs6 && !other.uvs6) { other.uvs6 = new Float32Array(other.positions.length / 3 * 2); } if (this.colors && !other.colors) { other.colors = new Float32Array(other.positions.length / 3 * 4); other.colors.fill(1); } if (this.matricesIndices && !other.matricesIndices) { other.matricesIndices = new Float32Array(other.positions.length / 3 * 4); } if (this.matricesWeights && !other.matricesWeights) { other.matricesWeights = new Float32Array(other.positions.length / 3 * 4); } if (this.matricesIndicesExtra && !other.matricesIndicesExtra) { other.matricesIndicesExtra = new Float32Array(other.positions.length / 3 * 4); } if (this.matricesWeightsExtra && !other.matricesWeightsExtra) { other.matricesWeightsExtra = new Float32Array(other.positions.length / 3 * 4); } } } if (mergeMaterialIds) { let materialIndex = 0; let indexOffset = 0; let vertexOffset = 0; const materialInfos = []; let currentMaterialInfo = null; const vertexDataList = []; for (const split of this.splitBasedOnMaterialID()) { vertexDataList.push({ vertexData: split, transform }); } for (const data of vertexDatas) { if (!data.vertexData) { continue; } for (const split of data.vertexData.splitBasedOnMaterialID()) { vertexDataList.push({ vertexData: split, transform: data.transform }); } } vertexDataList.sort((a, b) => { const matInfoA = a.vertexData.materialInfos ? a.vertexData.materialInfos[0].materialIndex : 0; const matInfoB = b.vertexData.materialInfos ? b.vertexData.materialInfos[0].materialIndex : 0; if (matInfoA > matInfoB) { return 1; } if (matInfoA === matInfoB) { return 0; } return -1; }); for (const vertexDataSource of vertexDataList) { const vertexData = vertexDataSource.vertexData; if (vertexData.materialInfos) { materialIndex = vertexData.materialInfos[0].materialIndex; } else { materialIndex = 0; } if (currentMaterialInfo && currentMaterialInfo.materialIndex === materialIndex) { currentMaterialInfo.indexCount += vertexData.indices.length; currentMaterialInfo.verticesCount += vertexData.positions.length / 3; } else { const materialInfo = new VertexDataMaterialInfo(); materialInfo.materialIndex = materialIndex; materialInfo.indexStart = indexOffset; materialInfo.indexCount = vertexData.indices.length; materialInfo.verticesStart = vertexOffset; materialInfo.verticesCount = vertexData.positions.length / 3; materialInfos.push(materialInfo); currentMaterialInfo = materialInfo; } indexOffset += vertexData.indices.length; vertexOffset += vertexData.positions.length / 3; } const first = vertexDataList.splice(0, 1)[0]; root = first.vertexData; transform = first.transform; others = vertexDataList.map((v) => v.vertexData); vertexDatas = vertexDataList; this.materialInfos = materialInfos; } const totalIndices = others.reduce((indexSum, vertexData) => indexSum + (vertexData.indices?.length ?? 0), root.indices?.length ?? 0); const sliceIndices = forceCloneIndices || others.some((vertexData) => vertexData.indices === root.indices); let indices = sliceIndices ? root.indices?.slice() : root.indices; if (totalIndices > 0) { let indicesOffset = indices?.length ?? 0; if (!indices) { indices = new Array(totalIndices); } if (indices.length !== totalIndices) { if (Array.isArray(indices)) { indices.length = totalIndices; } else { const temp = use32BitsIndices || indices instanceof Uint32Array ? new Uint32Array(totalIndices) : new Uint16Array(totalIndices); temp.set(indices); indices = temp; } if (transform && transform.determinant() < 0) { _VertexData._FlipFaces(indices, 0, indicesOffset); } } let positionsOffset = root.positions ? root.positions.length / 3 : 0; for (const { vertexData: other, transform: transform2 } of vertexDatas) { if (other.indices) { for (let index = 0; index < other.indices.length; index++) { indices[indicesOffset + index] = other.indices[index] + positionsOffset; } if (transform2 && transform2.determinant() < 0) { _VertexData._FlipFaces(indices, indicesOffset, other.indices.length); } positionsOffset += other.positions.length / 3; indicesOffset += other.indices.length; if (isAsync) { yield; } } } } this.indices = indices; this.positions = _VertexData._MergeElement(VertexBuffer.PositionKind, root.positions, transform, vertexDatas.map((other) => [other.vertexData.positions, other.transform])); if (isAsync) { yield; } if (root.normals) { this.normals = _VertexData._MergeElement(VertexBuffer.NormalKind, root.normals, transform, vertexDatas.map((other) => [other.vertexData.normals, other.transform])); if (isAsync) { yield; } } if (root.tangents) { this.tangents = _VertexData._MergeElement(VertexBuffer.TangentKind, root.tangents, transform, vertexDatas.map((other) => [other.vertexData.tangents, other.transform])); if (isAsync) { yield; } } if (root.uvs) { this.uvs = _VertexData._MergeElement(VertexBuffer.UVKind, root.uvs, transform, vertexDatas.map((other) => [other.vertexData.uvs, other.transform])); if (isAsync) { yield; } } if (root.uvs2) { this.uvs2 = _VertexData._MergeElement(VertexBuffer.UV2Kind, root.uvs2, transform, vertexDatas.map((other) => [other.vertexData.uvs2, other.transform])); if (isAsync) { yield; } } if (root.uvs3) { this.uvs3 = _VertexData._MergeElement(VertexBuffer.UV3Kind, root.uvs3, transform, vertexDatas.map((other) => [other.vertexData.uvs3, other.transform])); if (isAsync) { yield; } } if (root.uvs4) { this.uvs4 = _VertexData._MergeElement(VertexBuffer.UV4Kind, root.uvs4, transform, vertexDatas.map((other) => [other.vertexData.uvs4, other.transform])); if (isAsync) { yield; } } if (root.uvs5) { this.uvs5 = _VertexData._MergeElement(VertexBuffer.UV5Kind, root.uvs5, transform, vertexDatas.map((other) => [other.vertexData.uvs5, other.transform])); if (isAsync) { yield; } } if (root.uvs6) { this.uvs6 = _VertexData._MergeElement(VertexBuffer.UV6Kind, root.uvs6, transform, vertexDatas.map((other) => [other.vertexData.uvs6, other.transform])); if (isAsync) { yield; } } if (root.colors) { this.colors = _VertexData._MergeElement(VertexBuffer.ColorKind, root.colors, transform, vertexDatas.map((other) => [other.vertexData.colors, other.transform])); if (root.hasVertexAlpha !== void 0 || vertexDatas.some((other) => other.vertexData.hasVertexAlpha !== void 0)) { this.hasVertexAlpha = root.hasVertexAlpha || vertexDatas.some((other) => other.vertexData.hasVertexAlpha); } if (isAsync) { yield; } } if (root.matricesIndices) { this.matricesIndices = _VertexData._MergeElement(VertexBuffer.MatricesIndicesKind, root.matricesIndices, transform, vertexDatas.map((other) => [other.vertexData.matricesIndices, other.transform])); if (isAsync) { yield; } } if (root.matricesWeights) { this.matricesWeights = _VertexData._MergeElement(VertexBuffer.MatricesWeightsKind, root.matricesWeights, transform, vertexDatas.map((other) => [other.vertexData.matricesWeights, other.transform])); if (isAsync) { yield; } } if (root.matricesIndicesExtra) { this.matricesIndicesExtra = _VertexData._MergeElement(VertexBuffer.MatricesIndicesExtraKind, root.matricesIndicesExtra, transform, vertexDatas.map((other) => [other.vertexData.matricesIndicesExtra, other.transform])); if (isAsync) { yield; } } if (root.matricesWeightsExtra) { this.matricesWeightsExtra = _VertexData._MergeElement(VertexBuffer.MatricesWeightsExtraKind, root.matricesWeightsExtra, transform, vertexDatas.map((other) => [other.vertexData.matricesWeightsExtra, other.transform])); } return this; } static _MergeElement(kind, source, transform, others) { const nonNullOthers = others.filter((other) => other[0] !== null && other[0] !== void 0); if (!source && nonNullOthers.length == 0) { return source; } if (!source) { return this._MergeElement(kind, nonNullOthers[0][0], nonNullOthers[0][1], nonNullOthers.slice(1)); } const len = nonNullOthers.reduce((sumLen, elements) => sumLen + elements[0].length, source.length); const transformRange = kind === VertexBuffer.PositionKind ? _VertexData._TransformVector3Coordinates : kind === VertexBuffer.NormalKind ? _VertexData._TransformVector3Normals : kind === VertexBuffer.TangentKind ? _VertexData._TransformVector4Normals : () => { }; if (source instanceof Float32Array) { const ret32 = new Float32Array(len); ret32.set(source); transform && transformRange(ret32, transform, 0, source.length); let offset = source.length; for (const [vertexData, transform2] of nonNullOthers) { ret32.set(vertexData, offset); transform2 && transformRange(ret32, transform2, offset, vertexData.length); offset += vertexData.length; } return ret32; } else { const ret = new Array(len); for (let i = 0; i < source.length; i++) { ret[i] = source[i]; } transform && transformRange(ret, transform, 0, source.length); let offset = source.length; for (const [vertexData, transform2] of nonNullOthers) { for (let i = 0; i < vertexData.length; i++) { ret[offset + i] = vertexData[i]; } transform2 && transformRange(ret, transform2, offset, vertexData.length); offset += vertexData.length; } return ret; } } _validate() { if (!this.positions) { throw new RuntimeError("Positions are required", ErrorCodes.MeshInvalidPositionsError); } const getElementCount = /* @__PURE__ */ __name((kind, values) => { const stride = VertexBuffer.DeduceStride(kind); if (values.length % stride !== 0) { throw new Error("The " + kind + "s array count must be a multiple of " + stride); } return values.length / stride; }, "getElementCount"); const positionsElementCount = getElementCount(VertexBuffer.PositionKind, this.positions); const validateElementCount = /* @__PURE__ */ __name((kind, values) => { const elementCount = getElementCount(kind, values); if (elementCount !== positionsElementCount) { throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")"); } }, "validateElementCount"); if (this.normals) { validateElementCount(VertexBuffer.NormalKind, this.normals); } if (this.tangents) { validateElementCount(VertexBuffer.TangentKind, this.tangents); } if (this.uvs) { validateElementCount(VertexBuffer.UVKind, this.uvs); } if (this.uvs2) { validateElementCount(VertexBuffer.UV2Kind, this.uvs2); } if (this.uvs3) { validateElementCount(VertexBuffer.UV3Kind, this.uvs3); } if (this.uvs4) { validateElementCount(VertexBuffer.UV4Kind, this.uvs4); } if (this.uvs5) { validateElementCount(VertexBuffer.UV5Kind, this.uvs5); } if (this.uvs6) { validateElementCount(VertexBuffer.UV6Kind, this.uvs6); } if (this.colors) { validateElementCount(VertexBuffer.ColorKind, this.colors); } if (this.matricesIndices) { validateElementCount(VertexBuffer.MatricesIndicesKind, this.matricesIndices); } if (this.matricesWeights) { validateElementCount(VertexBuffer.MatricesWeightsKind, this.matricesWeights); } if (this.matricesIndicesExtra) { validateElementCount(VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra); } if (this.matricesWeightsExtra) { validateElementCount(VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra); } } /** * Clone the current vertex data * @returns a copy of the current data */ clone() { const serializationObject = this.serialize(); return _VertexData.Parse(serializationObject); } /** * Serializes the VertexData * @returns a serialized object */ serialize() { const serializationObject = {}; if (this.positions) { serializationObject.positions = Array.from(this.positions); } if (this.normals) { serializationObject.normals = Array.from(this.normals); } if (this.tangents) { serializationObject.tangents = Array.from(this.tangents); } if (this.uvs) { serializationObject.uvs = Array.from(this.uvs); } if (this.uvs2) { serializationObject.uvs2 = Array.from(this.uvs2); } if (this.uvs3) { serializationObject.uvs3 = Array.from(this.uvs3); } if (this.uvs4) { serializationObject.uvs4 = Array.from(this.uvs4); } if (this.uvs5) { serializationObject.uvs5 = Array.from(this.uvs5); } if (this.uvs6) { serializationObject.uvs6 = Array.from(this.uvs6); } if (this.colors) { serializationObject.colors = Array.from(this.colors); serializationObject.hasVertexAlpha = this.hasVertexAlpha; } if (this.matricesIndices) { serializationObject.matricesIndices = Array.from(this.matricesIndices); serializationObject.matricesIndicesExpanded = true; } if (this.matricesWeights) { serializationObject.matricesWeights = Array.from(this.matricesWeights); } if (this.matricesIndicesExtra) { serializationObject.matricesIndicesExtra = Array.from(this.matricesIndicesExtra); serializationObject.matricesIndicesExtraExpanded = true; } if (this.matricesWeightsExtra) { serializationObject.matricesWeightsExtra = Array.from(this.matricesWeightsExtra); } serializationObject.indices = this.indices ? Array.from(this.indices) : []; if (this.materialInfos) { serializationObject.materialInfos = []; for (const materialInfo of this.materialInfos) { const materialInfoSerializationObject = { indexStart: materialInfo.indexStart, indexCount: materialInfo.indexCount, materialIndex: materialInfo.materialIndex, verticesStart: materialInfo.verticesStart, verticesCount: materialInfo.verticesCount }; serializationObject.materialInfos.push(materialInfoSerializationObject); } } return serializationObject; } // Statics /** * Extracts the vertexData from a mesh * @param mesh the mesh from which to extract the VertexData * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false * @param forceCopy indicating that the VertexData must be cloned, optional, default false * @returns the object VertexData associated to the passed mesh */ static ExtractFromMesh(mesh, copyWhenShared, forceCopy) { return _VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy); } /** * Extracts the vertexData from the geometry * @param geometry the geometry from which to extract the VertexData * @param copyWhenShared defines if the VertexData must be cloned when the geometry is shared between multiple meshes, optional, default false * @param forceCopy indicating that the VertexData must be cloned, optional, default false * @returns the object VertexData associated to the passed mesh */ static ExtractFromGeometry(geometry, copyWhenShared, forceCopy) { return _VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy); } static _ExtractFrom(meshOrGeometry, copyWhenShared, forceCopy) { const result = new _VertexData(); if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.PositionKind)) { result.positions = meshOrGeometry.getVerticesData(VertexBuffer.PositionKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.NormalKind)) { result.normals = meshOrGeometry.getVerticesData(VertexBuffer.NormalKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.TangentKind)) { result.tangents = meshOrGeometry.getVerticesData(VertexBuffer.TangentKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UVKind)) { result.uvs = meshOrGeometry.getVerticesData(VertexBuffer.UVKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV2Kind)) { result.uvs2 = meshOrGeometry.getVerticesData(VertexBuffer.UV2Kind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV3Kind)) { result.uvs3 = meshOrGeometry.getVerticesData(VertexBuffer.UV3Kind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV4Kind)) { result.uvs4 = meshOrGeometry.getVerticesData(VertexBuffer.UV4Kind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV5Kind)) { result.uvs5 = meshOrGeometry.getVerticesData(VertexBuffer.UV5Kind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.UV6Kind)) { result.uvs6 = meshOrGeometry.getVerticesData(VertexBuffer.UV6Kind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.ColorKind)) { const geometry = meshOrGeometry.geometry || meshOrGeometry; const vertexBuffer = geometry.getVertexBuffer(VertexBuffer.ColorKind); const colors = geometry.getVerticesData(VertexBuffer.ColorKind, copyWhenShared, forceCopy); if (vertexBuffer.getSize() === 3) { const newColors = new Float32Array(colors.length * 4 / 3); for (let i = 0, j = 0; i < colors.length; i += 3, j += 4) { newColors[j] = colors[i]; newColors[j + 1] = colors[i + 1]; newColors[j + 2] = colors[i + 2]; newColors[j + 3] = 1; } result.colors = newColors; } else if (vertexBuffer.getSize() === 4) { result.colors = colors; } else { throw new Error(`Unexpected number of color components: ${vertexBuffer.getSize()}`); } } if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) { result.matricesIndices = meshOrGeometry.getVerticesData(VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) { result.matricesWeights = meshOrGeometry.getVerticesData(VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesIndicesExtraKind)) { result.matricesIndicesExtra = meshOrGeometry.getVerticesData(VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy); } if (meshOrGeometry.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind)) { result.matricesWeightsExtra = meshOrGeometry.getVerticesData(VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy); } result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy); return result; } /** * Creates the VertexData for a Ribbon * @param options an object used to set the following optional parameters for the ribbon, required but can be empty * * pathArray array of paths, each of which an array of successive Vector3 * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional * * colors a linear array, of length 4 * number of vertices, of custom color values, optional * @returns the VertexData of the ribbon * @deprecated use CreateRibbonVertexData instead */ static CreateRibbon(options) { throw _WarnImport("ribbonBuilder"); } /** * Creates the VertexData for a box * @param options an object used to set the following optional parameters for the box, required but can be empty * * size sets the width, height and depth of the box to the value of size, optional default 1 * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size * * faceUV an array of 6 Vector4 elements used to set different images to each box side * * faceColors an array of 6 Color3 elements used to set different colors to each box side * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the box * @deprecated Please use CreateBoxVertexData from the BoxBuilder file instead */ static CreateBox(options) { throw _WarnImport("boxBuilder"); } /** * Creates the VertexData for a tiled box * @param options an object used to set the following optional parameters for the box, required but can be empty * * faceTiles sets the pattern, tile size and number of tiles for a face * * faceUV an array of 6 Vector4 elements used to set different images to each box side * * faceColors an array of 6 Color3 elements used to set different colors to each box side * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * @param options.pattern * @param options.width * @param options.height * @param options.depth * @param options.tileSize * @param options.tileWidth * @param options.tileHeight * @param options.alignHorizontal * @param options.alignVertical * @param options.faceUV * @param options.faceColors * @param options.sideOrientation * @returns the VertexData of the box * @deprecated Please use CreateTiledBoxVertexData instead */ static CreateTiledBox(options) { throw _WarnImport("tiledBoxBuilder"); } /** * Creates the VertexData for a tiled plane * @param options an object used to set the following optional parameters for the box, required but can be empty * * pattern a limited pattern arrangement depending on the number * * tileSize sets the width, height and depth of the tile to the value of size, optional default 1 * * tileWidth sets the width (x direction) of the tile, overwrites the width set by size, optional, default size * * tileHeight sets the height (y direction) of the tile, overwrites the height set by size, optional, default size * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the tiled plane * @deprecated use CreateTiledPlaneVertexData instead */ static CreateTiledPlane(options) { throw _WarnImport("tiledPlaneBuilder"); } /** * Creates the VertexData for an ellipsoid, defaults to a sphere * @param options an object used to set the following optional parameters for the box, required but can be empty * * segments sets the number of horizontal strips optional, default 32 * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1 * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1 * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1 * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the ellipsoid * @deprecated use CreateSphereVertexData instead */ static CreateSphere(options) { throw _WarnImport("sphereBuilder"); } /** * Creates the VertexData for a cylinder, cone or prism * @param options an object used to set the following optional parameters for the box, required but can be empty * * height sets the height (y direction) of the cylinder, optional, default 2 * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter * * diameter sets the diameter of the top and bottom of the cone, optional default 1 * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 * * subdivisions` the number of rings along the cylinder height, optional, default 1 * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1 * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively * * hasRings when true makes each subdivision independently treated as a face for faceUV and faceColors, optional, default false * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the cylinder, cone or prism * @deprecated please use CreateCylinderVertexData instead */ static CreateCylinder(options) { throw _WarnImport("cylinderBuilder"); } /** * Creates the VertexData for a torus * @param options an object used to set the following optional parameters for the box, required but can be empty * * diameter the diameter of the torus, optional default 1 * * thickness the diameter of the tube forming the torus, optional default 0.5 * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24 * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the torus * @deprecated use CreateTorusVertexData instead */ static CreateTorus(options) { throw _WarnImport("torusBuilder"); } /** * Creates the VertexData of the LineSystem * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty * - lines an array of lines, each line being an array of successive Vector3 * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point * @returns the VertexData of the LineSystem * @deprecated use CreateLineSystemVertexData instead */ static CreateLineSystem(options) { throw _WarnImport("linesBuilder"); } /** * Create the VertexData for a DashedLines * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty * - points an array successive Vector3 * - dashSize the size of the dashes relative to the dash number, optional, default 3 * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1 * - dashNb the intended total number of dashes, optional, default 200 * @returns the VertexData for the DashedLines * @deprecated use CreateDashedLinesVertexData instead */ static CreateDashedLines(options) { throw _WarnImport("linesBuilder"); } /** * Creates the VertexData for a Ground * @param options an object used to set the following optional parameters for the Ground, required but can be empty * - width the width (x direction) of the ground, optional, default 1 * - height the height (z direction) of the ground, optional, default 1 * - subdivisions the number of subdivisions per side, optional, default 1 * @returns the VertexData of the Ground * @deprecated Please use CreateGroundVertexData instead */ static CreateGround(options) { throw _WarnImport("groundBuilder"); } /** * Creates the VertexData for a TiledGround by subdividing the ground into tiles * @param options an object used to set the following optional parameters for the Ground, required but can be empty * * xmin the ground minimum X coordinate, optional, default -1 * * zmin the ground minimum Z coordinate, optional, default -1 * * xmax the ground maximum X coordinate, optional, default 1 * * zmax the ground maximum Z coordinate, optional, default 1 * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6} * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2} * @returns the VertexData of the TiledGround * @deprecated use CreateTiledGroundVertexData instead */ static CreateTiledGround(options) { throw _WarnImport("groundBuilder"); } /** * Creates the VertexData of the Ground designed from a heightmap * @param options an object used to set the following parameters for the Ground, required and provided by CreateGroundFromHeightMap * * width the width (x direction) of the ground * * height the height (z direction) of the ground * * subdivisions the number of subdivisions per side * * minHeight the minimum altitude on the ground, optional, default 0 * * maxHeight the maximum altitude on the ground, optional default 1 * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11) * * buffer the array holding the image color data * * bufferWidth the width of image * * bufferHeight the height of image * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible) * @returns the VertexData of the Ground designed from a heightmap * @deprecated use CreateGroundFromHeightMapVertexData instead */ static CreateGroundFromHeightMap(options) { throw _WarnImport("groundBuilder"); } /** * Creates the VertexData for a Plane * @param options an object used to set the following optional parameters for the plane, required but can be empty * * size sets the width and height of the plane to the value of size, optional default 1 * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the box * @deprecated use CreatePlaneVertexData instead */ static CreatePlane(options) { throw _WarnImport("planeBuilder"); } /** * Creates the VertexData of the Disc or regular Polygon * @param options an object used to set the following optional parameters for the disc, required but can be empty * * radius the radius of the disc, optional default 0.5 * * tessellation the number of polygon sides, optional, default 64 * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1 * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the box * @deprecated use CreateDiscVertexData instead */ static CreateDisc(options) { throw _WarnImport("discBuilder"); } /** * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build() * All parameters are provided by CreatePolygon as needed * @param polygon a mesh built from polygonTriangulation.build() * @param sideOrientation takes the values Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @param wrap a boolean, default false, when true and fUVs used texture is wrapped around all sides, when false texture is applied side * @returns the VertexData of the Polygon * @deprecated use CreatePolygonVertexData instead */ static CreatePolygon(polygon, sideOrientation, fUV, fColors, frontUVs, backUVs, wrap) { throw _WarnImport("polygonBuilder"); } /** * Creates the VertexData of the IcoSphere * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty * * radius the radius of the IcoSphere, optional default 1 * * radiusX allows stretching in the x direction, optional, default radius * * radiusY allows stretching in the y direction, optional, default radius * * radiusZ allows stretching in the z direction, optional, default radius * * flat when true creates a flat shaded mesh, optional, default true * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the IcoSphere * @deprecated use CreateIcoSphereVertexData instead */ static CreateIcoSphere(options) { throw _WarnImport("icoSphereBuilder"); } // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html /** * Creates the VertexData for a Polyhedron * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty * * type provided types are: * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1) * * 9 : Pentagonal Pyramid (J2), 10 : Triangular Dipyramid (J12), 11 : Pentagonal Dipyramid (J13), 12 : Elongated Square Dipyramid (J15), 13 : Elongated Pentagonal Dipyramid (J16), 14 : Elongated Pentagonal Cupola (J20) * * size the size of the IcoSphere, optional default 1 * * sizeX allows stretching in the x direction, optional, default size * * sizeY allows stretching in the y direction, optional, default size * * sizeZ allows stretching in the z direction, optional, default size * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively * * flat when true creates a flat shaded mesh, optional, default true * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4 * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the Polyhedron * @deprecated use CreatePolyhedronVertexData instead */ static CreatePolyhedron(options) { throw _WarnImport("polyhedronBuilder"); } /** * Creates the VertexData for a Capsule, inspired from https://github.com/maximeq/three-js-capsule-geometry/blob/master/src/CapsuleBufferGeometry.js * @param options an object used to set the following optional parameters for the capsule, required but can be empty * @returns the VertexData of the Capsule * @deprecated Please use CreateCapsuleVertexData from the capsuleBuilder file instead */ static CreateCapsule(options = { orientation: Vector3.Up(), subdivisions: 2, tessellation: 16, height: 1, radius: 0.25, capSubdivisions: 6 }) { throw _WarnImport("capsuleBuilder"); } // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473 /** * Creates the VertexData for a TorusKnot * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty * * radius the radius of the torus knot, optional, default 2 * * tube the thickness of the tube, optional, default 0.5 * * radialSegments the number of sides on each tube segments, optional, default 32 * * tubularSegments the number of tubes to decompose the knot into, optional, default 32 * * p the number of windings around the z axis, optional, default 2 * * q the number of windings around the x axis, optional, default 3 * * sideOrientation optional and takes the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1) * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1) * @returns the VertexData of the Torus Knot * @deprecated use CreateTorusKnotVertexData instead */ static CreateTorusKnot(options) { throw _WarnImport("torusKnotBuilder"); } // Tools /** * Compute normals for given positions and indices * @param positions an array of vertex positions, [...., x, y, z, ......] * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......] * @param normals an array of vertex normals, [...., x, y, z, ......] * @param options an object used to set the following optional parameters for the TorusKnot, optional * * facetNormals : optional array of facet normals (vector3) * * facetPositions : optional array of facet positions (vector3) * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation * * bInfo : optional bounding info, required for facetPartitioning computation * * bbSize : optional bounding box size data, required for facetPartitioning computation * * subDiv : optional partitioning data about subdivisions on each axis (int), required for facetPartitioning computation * * useRightHandedSystem: optional boolean to for right handed system computation * * depthSort : optional boolean to enable the facet depth sort computation * * distanceTo : optional Vector3 to compute the facet depth from this location * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location */ static ComputeNormals(positions, indices, normals, options) { let index = 0; let p1p2x = 0; let p1p2y = 0; let p1p2z = 0; let p3p2x = 0; let p3p2y = 0; let p3p2z = 0; let faceNormalx = 0; let faceNormaly = 0; let faceNormalz = 0; let length = 0; let v1x = 0; let v1y = 0; let v1z = 0; let v2x = 0; let v2y = 0; let v2z = 0; let v3x = 0; let v3y = 0; let v3z = 0; let computeFacetNormals = false; let computeFacetPositions = false; let computeFacetPartitioning = false; let computeDepthSort = false; let faceNormalSign = 1; let ratio = 0; let distanceTo = null; if (options) { computeFacetNormals = options.facetNormals ? true : false; computeFacetPositions = options.facetPositions ? true : false; computeFacetPartitioning = options.facetPartitioning ? true : false; faceNormalSign = options.useRightHandedSystem === true ? -1 : 1; ratio = options.ratio || 0; computeDepthSort = options.depthSort ? true : false; distanceTo = options.distanceTo; if (computeDepthSort) { if (distanceTo === void 0) { distanceTo = Vector3.Zero(); } } } let xSubRatio = 0; let ySubRatio = 0; let zSubRatio = 0; let subSq = 0; if (computeFacetPartitioning && options && options.bbSize) { xSubRatio = options.subDiv.X * ratio / options.bbSize.x; ySubRatio = options.subDiv.Y * ratio / options.bbSize.y; zSubRatio = options.subDiv.Z * ratio / options.bbSize.z; subSq = options.subDiv.max * options.subDiv.max; options.facetPartitioning.length = 0; } for (index = 0; index < positions.length; index++) { normals[index] = 0; } const nbFaces = indices.length / 3 | 0; for (index = 0; index < nbFaces; index++) { v1x = indices[index * 3] * 3; v1y = v1x + 1; v1z = v1x + 2; v2x = indices[index * 3 + 1] * 3; v2y = v2x + 1; v2z = v2x + 2; v3x = indices[index * 3 + 2] * 3; v3y = v3x + 1; v3z = v3x + 2; p1p2x = positions[v1x] - positions[v2x]; p1p2y = positions[v1y] - positions[v2y]; p1p2z = positions[v1z] - positions[v2z]; p3p2x = positions[v3x] - positions[v2x]; p3p2y = positions[v3y] - positions[v2y]; p3p2z = positions[v3z] - positions[v2z]; faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y); faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z); faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x); length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz); length = length === 0 ? 1 : length; faceNormalx /= length; faceNormaly /= length; faceNormalz /= length; if (computeFacetNormals && options) { options.facetNormals[index].x = faceNormalx; options.facetNormals[index].y = faceNormaly; options.facetNormals[index].z = faceNormalz; } if (computeFacetPositions && options) { options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3; options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3; options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3; } if (computeFacetPartitioning && options) { const ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio); const oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio); const oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio); const b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio); const b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio); const b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio); const b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio); const b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio); const b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio); const b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio); const b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio); const b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio); const blockIdxV1 = b1x + options.subDiv.max * b1y + subSq * b1z; const blockIdxV2 = b2x + options.subDiv.max * b2y + subSq * b2z; const blockIdxV3 = b3x + options.subDiv.max * b3y + subSq * b3z; const blockIdxV4 = ox + options.subDiv.max * oy + subSq * oz; options.facetPartitioning[blockIdxV4] = options.facetPartitioning[blockIdxV4] ? options.facetPartitioning[blockIdxV4] : []; options.facetPartitioning[blockIdxV1] = options.facetPartitioning[blockIdxV1] ? options.facetPartitioning[blockIdxV1] : []; options.facetPartitioning[blockIdxV2] = options.facetPartitioning[blockIdxV2] ? options.facetPartitioning[blockIdxV2] : []; options.facetPartitioning[blockIdxV3] = options.facetPartitioning[blockIdxV3] ? options.facetPartitioning[blockIdxV3] : []; options.facetPartitioning[blockIdxV1].push(index); if (blockIdxV2 != blockIdxV1) { options.facetPartitioning[blockIdxV2].push(index); } if (!(blockIdxV3 == blockIdxV2 || blockIdxV3 == blockIdxV1)) { options.facetPartitioning[blockIdxV3].push(index); } if (!(blockIdxV4 == blockIdxV1 || blockIdxV4 == blockIdxV2 || blockIdxV4 == blockIdxV3)) { options.facetPartitioning[blockIdxV4].push(index); } } if (computeDepthSort && options && options.facetPositions) { const dsf = options.depthSortedFacets[index]; dsf.ind = index * 3; dsf.sqDistance = Vector3.DistanceSquared(options.facetPositions[index], distanceTo); } normals[v1x] += faceNormalx; normals[v1y] += faceNormaly; normals[v1z] += faceNormalz; normals[v2x] += faceNormalx; normals[v2y] += faceNormaly; normals[v2z] += faceNormalz; normals[v3x] += faceNormalx; normals[v3y] += faceNormaly; normals[v3z] += faceNormalz; } for (index = 0; index < normals.length / 3; index++) { faceNormalx = normals[index * 3]; faceNormaly = normals[index * 3 + 1]; faceNormalz = normals[index * 3 + 2]; length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz); length = length === 0 ? 1 : length; faceNormalx /= length; faceNormaly /= length; faceNormalz /= length; normals[index * 3] = faceNormalx; normals[index * 3 + 1] = faceNormaly; normals[index * 3 + 2] = faceNormalz; } } /** * @internal */ static _ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) { const li = indices.length; const ln = normals.length; let i; let n; sideOrientation = sideOrientation || _VertexData.DEFAULTSIDE; switch (sideOrientation) { case _VertexData.FRONTSIDE: break; case _VertexData.BACKSIDE: for (i = 0; i < li; i += 3) { const tmp = indices[i]; indices[i] = indices[i + 2]; indices[i + 2] = tmp; } for (n = 0; n < ln; n++) { normals[n] = -normals[n]; } break; case _VertexData.DOUBLESIDE: { const lp = positions.length; const l = lp / 3; for (let p = 0; p < lp; p++) { positions[lp + p] = positions[p]; } for (i = 0; i < li; i += 3) { indices[i + li] = indices[i + 2] + l; indices[i + 1 + li] = indices[i + 1] + l; indices[i + 2 + li] = indices[i] + l; } for (n = 0; n < ln; n++) { normals[ln + n] = -normals[n]; } const lu = uvs.length; let u = 0; for (u = 0; u < lu; u++) { uvs[u + lu] = uvs[u]; } frontUVs = frontUVs ? frontUVs : new Vector4(0, 0, 1, 1); backUVs = backUVs ? backUVs : new Vector4(0, 0, 1, 1); u = 0; for (i = 0; i < lu / 2; i++) { uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u]; uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1]; uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu]; uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1]; u += 2; } break; } } } /** * Creates a VertexData from serialized data * @param parsedVertexData the parsed data from an imported file * @returns a VertexData */ static Parse(parsedVertexData) { const vertexData = new _VertexData(); const positions = parsedVertexData.positions; if (positions) { vertexData.set(positions, VertexBuffer.PositionKind); } const normals = parsedVertexData.normals; if (normals) { vertexData.set(normals, VertexBuffer.NormalKind); } const tangents = parsedVertexData.tangents; if (tangents) { vertexData.set(tangents, VertexBuffer.TangentKind); } const uvs = parsedVertexData.uvs; if (uvs) { vertexData.set(uvs, VertexBuffer.UVKind); } const uvs2 = parsedVertexData.uvs2; if (uvs2) { vertexData.set(uvs2, VertexBuffer.UV2Kind); } const uvs3 = parsedVertexData.uvs3; if (uvs3) { vertexData.set(uvs3, VertexBuffer.UV3Kind); } const uvs4 = parsedVertexData.uvs4; if (uvs4) { vertexData.set(uvs4, VertexBuffer.UV4Kind); } const uvs5 = parsedVertexData.uvs5; if (uvs5) { vertexData.set(uvs5, VertexBuffer.UV5Kind); } const uvs6 = parsedVertexData.uvs6; if (uvs6) { vertexData.set(uvs6, VertexBuffer.UV6Kind); } const colors = parsedVertexData.colors; if (colors) { vertexData.set(Color4.CheckColors4(colors, positions.length / 3), VertexBuffer.ColorKind); if (parsedVertexData.hasVertexAlpha !== void 0) { vertexData.hasVertexAlpha = parsedVertexData.hasVertexAlpha; } } const matricesIndices = parsedVertexData.matricesIndices; if (matricesIndices) { vertexData.set(matricesIndices, VertexBuffer.MatricesIndicesKind); } const matricesWeights = parsedVertexData.matricesWeights; if (matricesWeights) { vertexData.set(matricesWeights, VertexBuffer.MatricesWeightsKind); } const indices = parsedVertexData.indices; if (indices) { vertexData.indices = indices; } const materialInfos = parsedVertexData.materialInfos; if (materialInfos) { vertexData.materialInfos = []; for (const materialInfoFromJSON of materialInfos) { const materialInfo = new VertexDataMaterialInfo(); materialInfo.indexCount = materialInfoFromJSON.indexCount; materialInfo.indexStart = materialInfoFromJSON.indexStart; materialInfo.verticesCount = materialInfoFromJSON.verticesCount; materialInfo.verticesStart = materialInfoFromJSON.verticesStart; materialInfo.materialIndex = materialInfoFromJSON.materialIndex; vertexData.materialInfos.push(materialInfo); } } return vertexData; } /** * Applies VertexData created from the imported parameters to the geometry * @param parsedVertexData the parsed data from an imported file * @param geometry the geometry to apply the VertexData to */ static ImportVertexData(parsedVertexData, geometry) { const vertexData = _VertexData.Parse(parsedVertexData); geometry.setAllVerticesData(vertexData, parsedVertexData.updatable); } }; VertexData.FRONTSIDE = 0; VertexData.BACKSIDE = 1; VertexData.DOUBLESIDE = 2; VertexData.DEFAULTSIDE = 0; VertexData._UniqueIdGenerator = 0; __decorate([ nativeOverride.filter((...[coordinates]) => !Array.isArray(coordinates)) ], VertexData, "_TransformVector3Coordinates", null); __decorate([ nativeOverride.filter((...[normals]) => !Array.isArray(normals)) ], VertexData, "_TransformVector3Normals", null); __decorate([ nativeOverride.filter((...[normals]) => !Array.isArray(normals)) ], VertexData, "_TransformVector4Normals", null); __decorate([ nativeOverride.filter((...[indices]) => !Array.isArray(indices)) ], VertexData, "_FlipFaces", null); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/transformNode.js init_tslib_es6(); init_decorators(); init_decorators_serialization(); init_observable(); init_math_vector(); init_node(); init_typeStore(); var TransformNode = class _TransformNode extends Node { static { __name(this, "TransformNode"); } /** * Gets or sets the billboard mode. Default is 0. * * | Value | Type | Description | * | --- | --- | --- | * | 0 | BILLBOARDMODE_NONE | | * | 1 | BILLBOARDMODE_X | | * | 2 | BILLBOARDMODE_Y | | * | 4 | BILLBOARDMODE_Z | | * | 7 | BILLBOARDMODE_ALL | | * */ get billboardMode() { return this._billboardMode; } set billboardMode(value) { if (this._billboardMode === value) { return; } this._billboardMode = value; this._cache.useBillboardPosition = (this._billboardMode & _TransformNode.BILLBOARDMODE_USE_POSITION) !== 0; } /** * Gets or sets the distance of the object to max, often used by skybox */ get infiniteDistance() { return this._infiniteDistance; } set infiniteDistance(value) { if (this._infiniteDistance === value) { return; } this._infiniteDistance = value; } constructor(name260, scene = null, isPure = true) { super(name260, scene, false); this._forward = new Vector3(0, 0, 1); this._up = new Vector3(0, 1, 0); this._right = new Vector3(1, 0, 0); this._position = Vector3.Zero(); this._rotation = Vector3.Zero(); this._rotationQuaternion = null; this._scaling = Vector3.One(); this._transformToBoneReferal = null; this._isAbsoluteSynced = false; this._billboardMode = _TransformNode.BILLBOARDMODE_NONE; this.scalingDeterminant = 1; this._infiniteDistance = false; this.ignoreNonUniformScaling = false; this.reIntegrateRotationIntoRotationQuaternion = false; this._poseMatrix = null; this._localMatrix = Matrix.Zero(); this._usePivotMatrix = false; this._absolutePosition = Vector3.Zero(); this._absoluteScaling = Vector3.Zero(); this._absoluteRotationQuaternion = Quaternion.Identity(); this._pivotMatrix = Matrix.Identity(); this._postMultiplyPivotMatrix = false; this._isWorldMatrixFrozen = false; this._indexInSceneTransformNodesArray = -1; this.onAfterWorldMatrixUpdateObservable = new Observable(); this._nonUniformScaling = false; if (isPure) { this.getScene().addTransformNode(this); } } /** * Gets a string identifying the name of the class * @returns "TransformNode" string */ getClassName() { return "TransformNode"; } /** * Gets or set the node position (default is (0.0, 0.0, 0.0)) */ get position() { return this._position; } set position(newPosition) { this._position = newPosition; this._markAsDirtyInternal(); } /** * return true if a pivot has been set * @returns true if a pivot matrix is used */ isUsingPivotMatrix() { return this._usePivotMatrix; } /** * @returns true if pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect. */ isUsingPostMultiplyPivotMatrix() { return this._postMultiplyPivotMatrix; } /** * Gets or sets the rotation property : a Vector3 defining the rotation value in radians around each local axis X, Y, Z (default is (0.0, 0.0, 0.0)). * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion */ get rotation() { return this._rotation; } set rotation(newRotation) { this._rotation = newRotation; this._rotationQuaternion = null; this._markAsDirtyInternal(); } /** * Gets or sets the scaling property : a Vector3 defining the node scaling along each local axis X, Y, Z (default is (1.0, 1.0, 1.0)). */ get scaling() { return this._scaling; } set scaling(newScaling) { this._scaling = newScaling; this._markAsDirtyInternal(); } /** * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (undefined by default, but can be null). * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored) */ get rotationQuaternion() { return this._rotationQuaternion; } set rotationQuaternion(quaternion) { this._rotationQuaternion = quaternion; if (quaternion) { this._rotation.setAll(0); } this._markAsDirtyInternal(); } _markAsDirtyInternal() { if (this._isDirty) { return; } this._isDirty = true; if (this.customMarkAsDirty) { this.customMarkAsDirty(); } } /** * The forward direction of that transform in world space. */ get forward() { Vector3.TransformNormalFromFloatsToRef(0, 0, this.getScene().useRightHandedSystem ? -1 : 1, this.getWorldMatrix(), this._forward); return this._forward.normalize(); } /** * The up direction of that transform in world space. */ get up() { Vector3.TransformNormalFromFloatsToRef(0, 1, 0, this.getWorldMatrix(), this._up); return this._up.normalize(); } /** * The right direction of that transform in world space. */ get right() { Vector3.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem ? -1 : 1, 0, 0, this.getWorldMatrix(), this._right); return this._right.normalize(); } /** * Copies the parameter passed Matrix into the mesh Pose matrix. * @param matrix the matrix to copy the pose from * @returns this TransformNode. */ updatePoseMatrix(matrix) { if (!this._poseMatrix) { this._poseMatrix = matrix.clone(); return this; } this._poseMatrix.copyFrom(matrix); return this; } /** * Returns the mesh Pose matrix. * @returns the pose matrix */ getPoseMatrix() { if (!this._poseMatrix) { this._poseMatrix = Matrix.Identity(); } return this._poseMatrix; } /** @internal */ _isSynchronized() { const cache = this._cache; if (this._billboardMode !== cache.billboardMode || this._billboardMode !== _TransformNode.BILLBOARDMODE_NONE) { return false; } if (cache.pivotMatrixUpdated) { return false; } if (this._infiniteDistance) { return false; } if (this._position._isDirty) { return false; } if (this._scaling._isDirty) { return false; } if (this._rotationQuaternion && this._rotationQuaternion._isDirty || this._rotation._isDirty) { return false; } return true; } /** @internal */ _initCache() { super._initCache(); const cache = this._cache; cache.localMatrixUpdated = false; cache.billboardMode = -1; cache.infiniteDistance = false; cache.useBillboardPosition = false; } /** * Returns the current mesh absolute position. * Returns a Vector3. */ get absolutePosition() { return this.getAbsolutePosition(); } /** * Returns the current mesh absolute scaling. * Returns a Vector3. */ get absoluteScaling() { this._syncAbsoluteScalingAndRotation(); return this._absoluteScaling; } /** * Returns the current mesh absolute rotation. * Returns a Quaternion. */ get absoluteRotationQuaternion() { this._syncAbsoluteScalingAndRotation(); return this._absoluteRotationQuaternion; } /** * Sets a new matrix to apply before all other transformation * @param matrix defines the transform matrix * @returns the current TransformNode */ setPreTransformMatrix(matrix) { return this.setPivotMatrix(matrix, false); } /** * Sets a new pivot matrix to the current node * @param matrix defines the new pivot matrix to use * @param postMultiplyPivotMatrix defines if the pivot matrix must be cancelled in the world matrix. When this parameter is set to true (default), the inverse of the pivot matrix is also applied at the end to cancel the transformation effect * @returns the current TransformNode */ setPivotMatrix(matrix, postMultiplyPivotMatrix = true) { this._pivotMatrix.copyFrom(matrix); this._usePivotMatrix = !this._pivotMatrix.isIdentity(); this._cache.pivotMatrixUpdated = true; this._postMultiplyPivotMatrix = postMultiplyPivotMatrix; if (this._postMultiplyPivotMatrix) { if (!this._pivotMatrixInverse) { this._pivotMatrixInverse = Matrix.Invert(this._pivotMatrix); } else { this._pivotMatrix.invertToRef(this._pivotMatrixInverse); } } return this; } /** * Returns the mesh pivot matrix. * Default : Identity. * @returns the matrix */ getPivotMatrix() { return this._pivotMatrix; } /** * Instantiate (when possible) or clone that node with its hierarchy * @param newParent defines the new parent to use for the instance (or clone) * @param options defines options to configure how copy is done * @param options.doNotInstantiate defines if the model must be instantiated or just cloned * @param onNewNodeCreated defines an option callback to call when a clone or an instance is created * @returns an instance (or a clone) of the current node with its hierarchy */ instantiateHierarchy(newParent = null, options, onNewNodeCreated) { const clone = this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true); if (clone) { if (onNewNodeCreated) { onNewNodeCreated(this, clone); } } for (const child of this.getChildTransformNodes(true)) { child.instantiateHierarchy(clone, options, onNewNodeCreated); } return clone; } /** * Prevents the World matrix to be computed any longer. * Please note that the "moral" contract is that the world matrix is not going to be updated anymore. It is up to the developer to force updates. * You trade flexibility for performance. If you want to update it, you have to unfreeze it first. * @param newWorldMatrix defines an optional matrix to use as world matrix * @param decompose defines whether to decompose the given newWorldMatrix or directly assign * @returns the TransformNode. */ freezeWorldMatrix(newWorldMatrix = null, decompose = false) { if (newWorldMatrix) { if (decompose) { this._rotation.setAll(0); this._rotationQuaternion = this._rotationQuaternion || Quaternion.Identity(); newWorldMatrix.decompose(this._scaling, this._rotationQuaternion, this._position); this.computeWorldMatrix(true); } else { this._worldMatrix = newWorldMatrix; this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]); this._afterComputeWorldMatrix(); } } else { this._isWorldMatrixFrozen = false; this.computeWorldMatrix(true); } this._isDirty = false; this._isWorldMatrixFrozen = true; return this; } /** * Allows back the World matrix computation. * @returns the TransformNode. */ unfreezeWorldMatrix() { this._isWorldMatrixFrozen = false; this.computeWorldMatrix(true); return this; } /** * True if the World matrix has been frozen. */ get isWorldMatrixFrozen() { return this._isWorldMatrixFrozen; } /** * Returns the mesh absolute position in the World. * @returns a Vector3. */ getAbsolutePosition() { this.computeWorldMatrix(); return this._absolutePosition; } /** * Sets the mesh absolute position in the World from a Vector3 or an Array(3). * @param absolutePosition the absolute position to set * @returns the TransformNode. */ setAbsolutePosition(absolutePosition) { if (!absolutePosition) { return this; } let absolutePositionX; let absolutePositionY; let absolutePositionZ; if (absolutePosition.x === void 0) { if (arguments.length < 3) { return this; } absolutePositionX = arguments[0]; absolutePositionY = arguments[1]; absolutePositionZ = arguments[2]; } else { absolutePositionX = absolutePosition.x; absolutePositionY = absolutePosition.y; absolutePositionZ = absolutePosition.z; } if (this.parent) { const invertParentWorldMatrix = TmpVectors.Matrix[0]; this.parent.getWorldMatrix().invertToRef(invertParentWorldMatrix); Vector3.TransformCoordinatesFromFloatsToRef(absolutePositionX, absolutePositionY, absolutePositionZ, invertParentWorldMatrix, this.position); } else { this.position.x = absolutePositionX; this.position.y = absolutePositionY; this.position.z = absolutePositionZ; } this._absolutePosition.copyFrom(absolutePosition); return this; } /** * Sets the mesh position in its local space. * @param vector3 the position to set in localspace * @returns the TransformNode. */ setPositionWithLocalVector(vector3) { this.computeWorldMatrix(); this.position = Vector3.TransformNormal(vector3, this._localMatrix); return this; } /** * Returns the mesh position in the local space from the current World matrix values. * @returns a new Vector3. */ getPositionExpressedInLocalSpace() { this.computeWorldMatrix(); const invLocalWorldMatrix = TmpVectors.Matrix[0]; this._localMatrix.invertToRef(invLocalWorldMatrix); return Vector3.TransformNormal(this.position, invLocalWorldMatrix); } /** * Translates the mesh along the passed Vector3 in its local space. * @param vector3 the distance to translate in localspace * @returns the TransformNode. */ locallyTranslate(vector3) { this.computeWorldMatrix(true); this.position = Vector3.TransformCoordinates(vector3, this._localMatrix); return this; } /** * Orients a mesh towards a target point. Mesh must be drawn facing user. * @param targetPoint the position (must be in same space as current mesh) to look at * @param yawCor optional yaw (y-axis) correction in radians * @param pitchCor optional pitch (x-axis) correction in radians * @param rollCor optional roll (z-axis) correction in radians * @param space the chosen space of the target * @returns the TransformNode. */ lookAt(targetPoint, yawCor = 0, pitchCor = 0, rollCor = 0, space = 0) { const dv = _TransformNode._LookAtVectorCache; const pos = space === 0 ? this.position : this.getAbsolutePosition(); targetPoint.subtractToRef(pos, dv); this.setDirection(dv, yawCor, pitchCor, rollCor); if (space === 1 && this.parent) { if (this.rotationQuaternion) { const rotationMatrix = TmpVectors.Matrix[0]; this.rotationQuaternion.toRotationMatrix(rotationMatrix); const parentRotationMatrix = TmpVectors.Matrix[1]; this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix); parentRotationMatrix.invert(); rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix); this.rotationQuaternion.fromRotationMatrix(rotationMatrix); } else { const quaternionRotation = TmpVectors.Quaternion[0]; Quaternion.FromEulerVectorToRef(this.rotation, quaternionRotation); const rotationMatrix = TmpVectors.Matrix[0]; quaternionRotation.toRotationMatrix(rotationMatrix); const parentRotationMatrix = TmpVectors.Matrix[1]; this.parent.getWorldMatrix().getRotationMatrixToRef(parentRotationMatrix); parentRotationMatrix.invert(); rotationMatrix.multiplyToRef(parentRotationMatrix, rotationMatrix); quaternionRotation.fromRotationMatrix(rotationMatrix); quaternionRotation.toEulerAnglesToRef(this.rotation); } } return this; } /** * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh. * This Vector3 is expressed in the World space. * @param localAxis axis to rotate * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh. */ getDirection(localAxis) { const result = Vector3.Zero(); this.getDirectionToRef(localAxis, result); return result; } /** * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh. * localAxis is expressed in the mesh local space. * result is computed in the World space from the mesh World matrix. * @param localAxis axis to rotate * @param result the resulting transformnode * @returns this TransformNode. */ getDirectionToRef(localAxis, result) { Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result); return this; } /** * Sets this transform node rotation to the given local axis. * @param localAxis the axis in local space * @param yawCor optional yaw (y-axis) correction in radians * @param pitchCor optional pitch (x-axis) correction in radians * @param rollCor optional roll (z-axis) correction in radians * @returns this TransformNode */ setDirection(localAxis, yawCor = 0, pitchCor = 0, rollCor = 0) { const yaw = -Math.atan2(localAxis.z, localAxis.x) + Math.PI / 2; const len = Math.sqrt(localAxis.x * localAxis.x + localAxis.z * localAxis.z); const pitch = -Math.atan2(localAxis.y, len); if (this.rotationQuaternion) { Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion); } else { this.rotation.x = pitch + pitchCor; this.rotation.y = yaw + yawCor; this.rotation.z = rollCor; } return this; } /** * Sets a new pivot point to the current node * @param point defines the new pivot point to use * @param space defines if the point is in world or local space (local by default) * @returns the current TransformNode */ setPivotPoint(point, space = 0) { if (this.getScene().getRenderId() == 0) { this.computeWorldMatrix(true); } const wm = this.getWorldMatrix(); if (space == 1) { const tmat = TmpVectors.Matrix[0]; wm.invertToRef(tmat); point = Vector3.TransformCoordinates(point, tmat); } return this.setPivotMatrix(Matrix.Translation(-point.x, -point.y, -point.z), true); } /** * Returns a new Vector3 set with the mesh pivot point coordinates in the local space. * @returns the pivot point */ getPivotPoint() { const point = Vector3.Zero(); this.getPivotPointToRef(point); return point; } /** * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space. * @param result the vector3 to store the result * @returns this TransformNode. */ getPivotPointToRef(result) { result.x = -this._pivotMatrix.m[12]; result.y = -this._pivotMatrix.m[13]; result.z = -this._pivotMatrix.m[14]; return this; } /** * Returns a new Vector3 set with the mesh pivot point World coordinates. * @returns a new Vector3 set with the mesh pivot point World coordinates. */ getAbsolutePivotPoint() { const point = Vector3.Zero(); this.getAbsolutePivotPointToRef(point); return point; } /** * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates. * @param result vector3 to store the result * @returns this TransformNode. */ getAbsolutePivotPointToRef(result) { this.getPivotPointToRef(result); Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result); return this; } /** * Flag the transform node as dirty (Forcing it to update everything) * @param property if set to "rotation" the objects rotationQuaternion will be set to null * @returns this node */ markAsDirty(property) { if (this._isDirty) { return this; } if (this._children) { for (const child of this._children) { child.markAsDirty(property); } } return super.markAsDirty(property); } /** * Defines the passed node as the parent of the current node. * The node will remain exactly where it is and its position / rotation will be updated accordingly. * If you don't want to preserve the current rotation / position, assign the parent through parent accessor. * Note that if the mesh has a pivot matrix / point defined it will be applied after the parent was updated. * In that case the node will not remain in the same space as it is, as the pivot will be applied. * To avoid this, you can set updatePivot to true and the pivot will be updated to identity * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/parent_pivot/parent * @param node the node ot set as the parent * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change. * @param updatePivot if true, update the pivot matrix to keep the node in the same space as before * @returns this TransformNode. */ setParent(node, preserveScalingSign = false, updatePivot = false) { if (!node && !this.parent) { return this; } const quatRotation = TmpVectors.Quaternion[0]; const position = TmpVectors.Vector3[0]; const scale = TmpVectors.Vector3[1]; const invParentMatrix = TmpVectors.Matrix[1]; Matrix.IdentityToRef(invParentMatrix); const composedMatrix = TmpVectors.Matrix[0]; this.computeWorldMatrix(true); let currentRotation = this.rotationQuaternion; if (!currentRotation) { currentRotation = _TransformNode._TmpRotation; Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, currentRotation); } Matrix.ComposeToRef(this.scaling, currentRotation, this.position, composedMatrix); if (this.parent) { composedMatrix.multiplyToRef(this.parent.computeWorldMatrix(true), composedMatrix); } if (node) { node.computeWorldMatrix(true).invertToRef(invParentMatrix); composedMatrix.multiplyToRef(invParentMatrix, composedMatrix); } composedMatrix.decompose(scale, quatRotation, position, preserveScalingSign ? this : void 0); if (this.rotationQuaternion) { this.rotationQuaternion.copyFrom(quatRotation); } else { quatRotation.toEulerAnglesToRef(this.rotation); } this.scaling.copyFrom(scale); this.position.copyFrom(position); this.parent = node; if (updatePivot) { this.setPivotMatrix(Matrix.Identity()); } return this; } /** * Adds the passed mesh as a child to the current mesh. * The node will remain exactly where it is and its position / rotation will be updated accordingly. * This method is equivalent to calling setParent(). * @param mesh defines the child mesh * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change. * @returns the current mesh */ addChild(mesh, preserveScalingSign = false) { mesh.setParent(this, preserveScalingSign); return this; } /** * Removes the passed mesh from the current mesh children list * @param mesh defines the child mesh * @param preserveScalingSign if true, keep scaling sign of child. Otherwise, scaling sign might change. * @returns the current mesh */ removeChild(mesh, preserveScalingSign = false) { if (mesh.parent !== this) { return this; } mesh.setParent(null, preserveScalingSign); return this; } /** * True if the scaling property of this object is non uniform eg. (1,2,1) */ get nonUniformScaling() { return this._nonUniformScaling; } /** * @internal */ _updateNonUniformScalingState(value) { if (this._nonUniformScaling === value) { return false; } this._nonUniformScaling = value; return true; } /** * Attach the current TransformNode to another TransformNode associated with a bone * @param bone Bone affecting the TransformNode * @param affectedTransformNode TransformNode associated with the bone * @returns this object */ attachToBone(bone, affectedTransformNode) { this._currentParentWhenAttachingToBone = this.parent; this._transformToBoneReferal = affectedTransformNode; this.parent = bone; bone.getSkeleton().prepare(true); if (bone.getFinalMatrix().determinant() < 0) { this.scalingDeterminant *= -1; } return this; } /** * Detach the transform node if its associated with a bone * @param resetToPreviousParent Indicates if the parent that was in effect when attachToBone was called should be set back or if we should set parent to null instead (defaults to the latter) * @returns this object */ detachFromBone(resetToPreviousParent = false) { if (!this.parent) { if (resetToPreviousParent) { this.parent = this._currentParentWhenAttachingToBone; } return this; } if (this.parent.getWorldMatrix().determinant() < 0) { this.scalingDeterminant *= -1; } this._transformToBoneReferal = null; if (resetToPreviousParent) { this.parent = this._currentParentWhenAttachingToBone; } else { this.parent = null; } return this; } /** * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space. * space (default LOCAL) can be either Space.LOCAL, either Space.WORLD. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. * The passed axis is also normalized. * @param axis the axis to rotate around * @param amount the amount to rotate in radians * @param space Space to rotate in (Default: local) * @returns the TransformNode. */ rotate(axis, amount, space) { axis.normalize(); if (!this.rotationQuaternion) { this.rotationQuaternion = this.rotation.toQuaternion(); this.rotation.setAll(0); } let rotationQuaternion; if (!space || space === 0) { rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, _TransformNode._RotationAxisCache); this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion); } else { if (this.parent) { const parentWorldMatrix = this.parent.getWorldMatrix(); const invertParentWorldMatrix = TmpVectors.Matrix[0]; parentWorldMatrix.invertToRef(invertParentWorldMatrix); axis = Vector3.TransformNormal(axis, invertParentWorldMatrix); if (parentWorldMatrix.determinant() < 0) { amount *= -1; } } rotationQuaternion = Quaternion.RotationAxisToRef(axis, amount, _TransformNode._RotationAxisCache); rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); } return this; } /** * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used. * The passed axis is also normalized. . * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm * @param point the point to rotate around * @param axis the axis to rotate around * @param amount the amount to rotate in radians * @returns the TransformNode */ rotateAround(point, axis, amount) { axis.normalize(); if (!this.rotationQuaternion) { this.rotationQuaternion = Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z); this.rotation.setAll(0); } const tmpVector = TmpVectors.Vector3[0]; const finalScale = TmpVectors.Vector3[1]; const finalTranslation = TmpVectors.Vector3[2]; const finalRotation = TmpVectors.Quaternion[0]; const translationMatrix = TmpVectors.Matrix[0]; const translationMatrixInv = TmpVectors.Matrix[1]; const rotationMatrix = TmpVectors.Matrix[2]; const finalMatrix = TmpVectors.Matrix[3]; point.subtractToRef(this.position, tmpVector); Matrix.TranslationToRef(tmpVector.x, tmpVector.y, tmpVector.z, translationMatrix); Matrix.TranslationToRef(-tmpVector.x, -tmpVector.y, -tmpVector.z, translationMatrixInv); Matrix.RotationAxisToRef(axis, amount, rotationMatrix); translationMatrixInv.multiplyToRef(rotationMatrix, finalMatrix); finalMatrix.multiplyToRef(translationMatrix, finalMatrix); finalMatrix.decompose(finalScale, finalRotation, finalTranslation); this.position.addInPlace(finalTranslation); finalRotation.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion); return this; } /** * Translates the mesh along the axis vector for the passed distance in the given space. * space (default LOCAL) can be either Space.LOCAL, either Space.WORLD. * @param axis the axis to translate in * @param distance the distance to translate * @param space Space to rotate in (Default: local) * @returns the TransformNode. */ translate(axis, distance, space) { const displacementVector = axis.scale(distance); if (!space || space === 0) { const tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector); this.setPositionWithLocalVector(tempV3); } else { this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector)); } return this; } /** * Adds a rotation step to the mesh current rotation. * x, y, z are Euler angles expressed in radians. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set. * This means this rotation is made in the mesh local space only. * It's useful to set a custom rotation order different from the BJS standard one YXZ. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis. * ```javascript * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3); * ``` * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles. * @param x Rotation to add * @param y Rotation to add * @param z Rotation to add * @returns the TransformNode. */ addRotation(x, y, z) { let rotationQuaternion; if (this.rotationQuaternion) { rotationQuaternion = this.rotationQuaternion; } else { rotationQuaternion = TmpVectors.Quaternion[1]; Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion); } const accumulation = TmpVectors.Quaternion[0]; Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation); rotationQuaternion.multiplyInPlace(accumulation); if (!this.rotationQuaternion) { rotationQuaternion.toEulerAnglesToRef(this.rotation); } return this; } /** * @internal */ _getEffectiveParent() { return this.parent; } /** * Returns whether the transform node world matrix computation needs the camera information to be computed. * This is the case when the node is a billboard or has an infinite distance for instance. * @returns true if the world matrix computation needs the camera information to be computed */ isWorldMatrixCameraDependent() { return this._infiniteDistance && !this.parent || this._billboardMode !== _TransformNode.BILLBOARDMODE_NONE; } /** * 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 camera defines the camera used if different from the scene active camera (This is used with modes like Billboard or infinite distance) * @returns the world matrix */ computeWorldMatrix(force = false, camera = null) { if (this._isWorldMatrixFrozen && !this._isDirty) { return this._worldMatrix; } const currentRenderId = this.getScene().getRenderId(); if (!this._isDirty && !force && (this._currentRenderId === currentRenderId || this.isSynchronized())) { this._currentRenderId = currentRenderId; return this._worldMatrix; } camera = camera || this.getScene().activeCamera; this._updateCache(); const cache = this._cache; cache.pivotMatrixUpdated = false; cache.billboardMode = this.billboardMode; cache.infiniteDistance = this.infiniteDistance; cache.parent = this._parentNode; this._currentRenderId = currentRenderId; this._childUpdateId += 1; this._isDirty = false; this._position._isDirty = false; this._rotation._isDirty = false; this._scaling._isDirty = false; const parent = this._getEffectiveParent(); const scaling = _TransformNode._TmpScaling; let translation = this._position; if (this._infiniteDistance) { if (!this.parent && camera) { const cameraWorldMatrix = camera.getWorldMatrix(); const cameraGlobalPosition = new Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]); translation = _TransformNode._TmpTranslation; translation.copyFromFloats(this._position.x + cameraGlobalPosition.x, this._position.y + cameraGlobalPosition.y, this._position.z + cameraGlobalPosition.z); } } scaling.copyFromFloats(this._scaling.x * this.scalingDeterminant, this._scaling.y * this.scalingDeterminant, this._scaling.z * this.scalingDeterminant); let rotation; if (this._rotationQuaternion) { this._rotationQuaternion._isDirty = false; rotation = this._rotationQuaternion; if (this.reIntegrateRotationIntoRotationQuaternion) { const len = this.rotation.lengthSquared(); if (len) { this._rotationQuaternion.multiplyInPlace(Quaternion.RotationYawPitchRoll(this._rotation.y, this._rotation.x, this._rotation.z)); this._rotation.copyFromFloats(0, 0, 0); } } } else { rotation = _TransformNode._TmpRotation; Quaternion.RotationYawPitchRollToRef(this._rotation.y, this._rotation.x, this._rotation.z, rotation); } if (this._usePivotMatrix) { const scaleMatrix = TmpVectors.Matrix[1]; Matrix.ScalingToRef(scaling.x, scaling.y, scaling.z, scaleMatrix); const rotationMatrix = TmpVectors.Matrix[0]; rotation.toRotationMatrix(rotationMatrix); this._pivotMatrix.multiplyToRef(scaleMatrix, TmpVectors.Matrix[4]); TmpVectors.Matrix[4].multiplyToRef(rotationMatrix, this._localMatrix); if (this._postMultiplyPivotMatrix) { this._localMatrix.multiplyToRef(this._pivotMatrixInverse, this._localMatrix); } this._localMatrix.addTranslationFromFloats(translation.x, translation.y, translation.z); } else { Matrix.ComposeToRef(scaling, rotation, translation, this._localMatrix); } if (parent && parent.getWorldMatrix) { if (force) { parent.computeWorldMatrix(force); } if (this.billboardMode) { if (this._transformToBoneReferal) { const bone = this.parent; bone.getSkeleton().prepare(); bone.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), TmpVectors.Matrix[7]); } else { TmpVectors.Matrix[7].copyFrom(parent.getWorldMatrix()); } const translation2 = TmpVectors.Vector3[5]; const scale = TmpVectors.Vector3[6]; const orientation = TmpVectors.Quaternion[0]; TmpVectors.Matrix[7].decompose(scale, orientation, translation2); Matrix.ScalingToRef(scale.x, scale.y, scale.z, TmpVectors.Matrix[7]); TmpVectors.Matrix[7].setTranslation(translation2); if (_TransformNode.BillboardUseParentOrientation) { this._position.applyRotationQuaternionToRef(orientation, translation2); this._localMatrix.setTranslation(translation2); } this._localMatrix.multiplyToRef(TmpVectors.Matrix[7], this._worldMatrix); } else { if (this._transformToBoneReferal) { const bone = this.parent; bone.getSkeleton().prepare(); this._localMatrix.multiplyToRef(bone.getFinalMatrix(), TmpVectors.Matrix[6]); TmpVectors.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix); } else { this._localMatrix.multiplyToRef(parent.getWorldMatrix(), this._worldMatrix); } } this._markSyncedWithParent(); } else { this._worldMatrix.copyFrom(this._localMatrix); } if (camera && this.billboardMode) { if (!cache.useBillboardPosition) { const storedTranslation = TmpVectors.Vector3[0]; this._worldMatrix.getTranslationToRef(storedTranslation); TmpVectors.Matrix[1].copyFrom(camera.getViewMatrix()); const isRH = this.getScene().useRightHandedSystem; if (isRH) { TmpVectors.Matrix[1].multiplyToRef(_TransformNode._TmpRHRestore, TmpVectors.Matrix[1]); } TmpVectors.Matrix[1].setTranslationFromFloats(0, 0, 0); TmpVectors.Matrix[1].invertToRef(TmpVectors.Matrix[0]); if ((this.billboardMode & _TransformNode.BILLBOARDMODE_ALL) !== _TransformNode.BILLBOARDMODE_ALL) { TmpVectors.Matrix[0].decompose(void 0, TmpVectors.Quaternion[0], void 0); const eulerAngles = TmpVectors.Vector3[1]; TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles); if ((this.billboardMode & _TransformNode.BILLBOARDMODE_X) !== _TransformNode.BILLBOARDMODE_X) { eulerAngles.x = 0; } if ((this.billboardMode & _TransformNode.BILLBOARDMODE_Y) !== _TransformNode.BILLBOARDMODE_Y) { eulerAngles.y = 0; } if ((this.billboardMode & _TransformNode.BILLBOARDMODE_Z) !== _TransformNode.BILLBOARDMODE_Z) { eulerAngles.z = 0; } if (isRH) { eulerAngles.y += Math.PI; } Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, TmpVectors.Matrix[0]); } this._worldMatrix.setTranslationFromFloats(0, 0, 0); this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0], this._worldMatrix); this._worldMatrix.setTranslation(TmpVectors.Vector3[0]); } else { const storedTranslation = TmpVectors.Vector3[0]; this._worldMatrix.getTranslationToRef(storedTranslation); const cameraPosition = camera.globalPosition; this._worldMatrix.invertToRef(TmpVectors.Matrix[1]); const camInObjSpace = TmpVectors.Vector3[1]; Vector3.TransformCoordinatesToRef(cameraPosition, TmpVectors.Matrix[1], camInObjSpace); camInObjSpace.normalize(); const yaw = -Math.atan2(camInObjSpace.z, camInObjSpace.x) + Math.PI / 2; const len = Math.sqrt(camInObjSpace.x * camInObjSpace.x + camInObjSpace.z * camInObjSpace.z); const pitch = -Math.atan2(camInObjSpace.y, len); Quaternion.RotationYawPitchRollToRef(yaw, pitch, 0, TmpVectors.Quaternion[0]); if ((this.billboardMode & _TransformNode.BILLBOARDMODE_ALL) !== _TransformNode.BILLBOARDMODE_ALL) { const eulerAngles = TmpVectors.Vector3[1]; TmpVectors.Quaternion[0].toEulerAnglesToRef(eulerAngles); if ((this.billboardMode & _TransformNode.BILLBOARDMODE_X) !== _TransformNode.BILLBOARDMODE_X) { eulerAngles.x = 0; } if ((this.billboardMode & _TransformNode.BILLBOARDMODE_Y) !== _TransformNode.BILLBOARDMODE_Y) { eulerAngles.y = 0; } if ((this.billboardMode & _TransformNode.BILLBOARDMODE_Z) !== _TransformNode.BILLBOARDMODE_Z) { eulerAngles.z = 0; } Matrix.RotationYawPitchRollToRef(eulerAngles.y, eulerAngles.x, eulerAngles.z, TmpVectors.Matrix[0]); } else { Matrix.FromQuaternionToRef(TmpVectors.Quaternion[0], TmpVectors.Matrix[0]); } this._worldMatrix.setTranslationFromFloats(0, 0, 0); this._worldMatrix.multiplyToRef(TmpVectors.Matrix[0], this._worldMatrix); this._worldMatrix.setTranslation(TmpVectors.Vector3[0]); } } if (!this.ignoreNonUniformScaling) { if (this._scaling.isNonUniformWithinEpsilon(1e-6)) { this._updateNonUniformScalingState(true); } else if (parent && parent._nonUniformScaling) { this._updateNonUniformScalingState(parent._nonUniformScaling); } else { this._updateNonUniformScalingState(false); } } else { this._updateNonUniformScalingState(false); } this._afterComputeWorldMatrix(); this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]); this._isAbsoluteSynced = false; this.onAfterWorldMatrixUpdateObservable.notifyObservers(this); if (!this._poseMatrix) { this._poseMatrix = Matrix.Invert(this._worldMatrix); } this._worldMatrixDeterminantIsDirty = true; return this._worldMatrix; } /** * Resets this nodeTransform's local matrix to Matrix.Identity(). * @param independentOfChildren indicates if all child nodeTransform's world-space transform should be preserved. */ resetLocalMatrix(independentOfChildren = true) { this.computeWorldMatrix(); if (independentOfChildren) { const children = this.getChildren(); for (let i = 0; i < children.length; ++i) { const child = children[i]; if (child) { child.computeWorldMatrix(); const bakedMatrix = TmpVectors.Matrix[0]; child._localMatrix.multiplyToRef(this._localMatrix, bakedMatrix); const tmpRotationQuaternion = TmpVectors.Quaternion[0]; bakedMatrix.decompose(child.scaling, tmpRotationQuaternion, child.position); if (child.rotationQuaternion) { child.rotationQuaternion.copyFrom(tmpRotationQuaternion); } else { tmpRotationQuaternion.toEulerAnglesToRef(child.rotation); } } } } this.scaling.copyFromFloats(1, 1, 1); this.position.copyFromFloats(0, 0, 0); this.rotation.copyFromFloats(0, 0, 0); if (this.rotationQuaternion) { this.rotationQuaternion = Quaternion.Identity(); } this._worldMatrix = Matrix.Identity(); } _afterComputeWorldMatrix() { } /** * If you'd like to be called back after the mesh position, rotation or scaling has been updated. * @param func callback function to add * * @returns the TransformNode. */ registerAfterWorldMatrixUpdate(func) { this.onAfterWorldMatrixUpdateObservable.add(func); return this; } /** * Removes a registered callback function. * @param func callback function to remove * @returns the TransformNode. */ unregisterAfterWorldMatrixUpdate(func) { this.onAfterWorldMatrixUpdateObservable.removeCallback(func); return this; } /** * Gets the position of the current mesh in camera space * @param camera defines the camera to use * @returns a position */ getPositionInCameraSpace(camera = null) { if (!camera) { camera = this.getScene().activeCamera; } return Vector3.TransformCoordinates(this.getAbsolutePosition(), camera.getViewMatrix()); } /** * Returns the distance from the mesh to the active camera * @param camera defines the camera to use * @returns the distance */ getDistanceToCamera(camera = null) { if (!camera) { camera = this.getScene().activeCamera; } return this.getAbsolutePosition().subtract(camera.globalPosition).length(); } /** * Clone the current transform node * @param name Name of the new clone * @param newParent New parent for the clone * @param doNotCloneChildren Do not clone children hierarchy * @returns the new transform node */ clone(name260, newParent, doNotCloneChildren) { const result = SerializationHelper.Clone(() => new _TransformNode(name260, this.getScene()), this); result.name = name260; result.id = name260; if (newParent) { result.parent = newParent; } if (!doNotCloneChildren) { const directDescendants = this.getDescendants(true); for (let index = 0; index < directDescendants.length; index++) { const child = directDescendants[index]; if (child.clone) { child.clone(name260 + "." + child.name, result); } } } return result; } /** * Serializes the objects information. * @param currentSerializationObject defines the object to serialize in * @returns the serialized object */ serialize(currentSerializationObject) { const serializationObject = SerializationHelper.Serialize(this, currentSerializationObject); serializationObject.type = this.getClassName(); serializationObject.uniqueId = this.uniqueId; if (this.parent) { this.parent._serializeAsParent(serializationObject); } serializationObject.localMatrix = this.getPivotMatrix().asArray(); serializationObject.isEnabled = this.isEnabled(); SerializationHelper.AppendSerializedAnimations(this, serializationObject); serializationObject.ranges = this.serializeAnimationRanges(); return serializationObject; } // Statics /** * Returns a new TransformNode object parsed from the source provided. * @param parsedTransformNode is the source. * @param scene the scene the object belongs to * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with * @returns a new TransformNode object parsed from the source provided. */ static Parse(parsedTransformNode, scene, rootUrl) { const transformNode = SerializationHelper.Parse(() => new _TransformNode(parsedTransformNode.name, scene), parsedTransformNode, scene, rootUrl); if (parsedTransformNode.localMatrix) { transformNode.setPreTransformMatrix(Matrix.FromArray(parsedTransformNode.localMatrix)); } else if (parsedTransformNode.pivotMatrix) { transformNode.setPivotMatrix(Matrix.FromArray(parsedTransformNode.pivotMatrix)); } transformNode.setEnabled(parsedTransformNode.isEnabled); transformNode._waitingParsedUniqueId = parsedTransformNode.uniqueId; if (parsedTransformNode.parentId !== void 0) { transformNode._waitingParentId = parsedTransformNode.parentId; } if (parsedTransformNode.parentInstanceIndex !== void 0) { transformNode._waitingParentInstanceIndex = parsedTransformNode.parentInstanceIndex; } if (parsedTransformNode.animations) { for (let animationIndex = 0; animationIndex < parsedTransformNode.animations.length; animationIndex++) { const parsedAnimation = parsedTransformNode.animations[animationIndex]; const internalClass = GetClass("BABYLON.Animation"); if (internalClass) { transformNode.animations.push(internalClass.Parse(parsedAnimation)); } } Node.ParseAnimationRanges(transformNode, parsedTransformNode, scene); } if (parsedTransformNode.autoAnimate) { scene.beginAnimation(transformNode, parsedTransformNode.autoAnimateFrom, parsedTransformNode.autoAnimateTo, parsedTransformNode.autoAnimateLoop, parsedTransformNode.autoAnimateSpeed || 1); } return transformNode; } /** * Get all child-transformNodes of this node * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored * @returns an array of TransformNode */ getChildTransformNodes(directDescendantsOnly, predicate) { const results = []; this._getDescendants(results, directDescendantsOnly, (node) => { return (!predicate || predicate(node)) && node instanceof _TransformNode; }); return results; } /** * Releases resources associated with this transform 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) */ dispose(doNotRecurse, disposeMaterialAndTextures = false) { this.getScene().stopAnimation(this); this.getScene().removeTransformNode(this); if (this._parentContainer) { const index = this._parentContainer.transformNodes.indexOf(this); if (index > -1) { this._parentContainer.transformNodes.splice(index, 1); } this._parentContainer = null; } this.onAfterWorldMatrixUpdateObservable.clear(); if (doNotRecurse) { const transformNodes = this.getChildTransformNodes(true); for (const transformNode of transformNodes) { transformNode.parent = null; transformNode.computeWorldMatrix(true); } } super.dispose(doNotRecurse, disposeMaterialAndTextures); } /** * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units) * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box. Default is false * @param ignoreRotation ignore rotation when computing the scale (ie. object will be axis aligned). Default is false * @param predicate predicate that is passed in to getHierarchyBoundingVectors when selecting which object should be included when scaling * @returns the current mesh */ normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate) { let storedRotation = null; let storedRotationQuaternion = null; if (ignoreRotation) { if (this.rotationQuaternion) { storedRotationQuaternion = this.rotationQuaternion.clone(); this.rotationQuaternion.copyFromFloats(0, 0, 0, 1); } else if (this.rotation) { storedRotation = this.rotation.clone(); this.rotation.copyFromFloats(0, 0, 0); } } const boundingVectors = this.getHierarchyBoundingVectors(includeDescendants, predicate); const sizeVec = boundingVectors.max.subtract(boundingVectors.min); const maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z); if (maxDimension === 0) { return this; } const scale = 1 / maxDimension; this.scaling.scaleInPlace(scale); if (ignoreRotation) { if (this.rotationQuaternion && storedRotationQuaternion) { this.rotationQuaternion.copyFrom(storedRotationQuaternion); } else if (this.rotation && storedRotation) { this.rotation.copyFrom(storedRotation); } } return this; } _syncAbsoluteScalingAndRotation() { if (!this._isAbsoluteSynced) { this._worldMatrix.decompose(this._absoluteScaling, this._absoluteRotationQuaternion); this._isAbsoluteSynced = true; } } }; TransformNode.BILLBOARDMODE_NONE = 0; TransformNode.BILLBOARDMODE_X = 1; TransformNode.BILLBOARDMODE_Y = 2; TransformNode.BILLBOARDMODE_Z = 4; TransformNode.BILLBOARDMODE_ALL = 7; TransformNode.BILLBOARDMODE_USE_POSITION = 128; TransformNode.BillboardUseParentOrientation = false; TransformNode._TmpRotation = Quaternion.Zero(); TransformNode._TmpScaling = Vector3.Zero(); TransformNode._TmpTranslation = Vector3.Zero(); TransformNode._TmpRHRestore = Matrix.Scaling(1, 1, -1); TransformNode._LookAtVectorCache = new Vector3(0, 0, 0); TransformNode._RotationAxisCache = new Quaternion(); __decorate([ serializeAsVector3("position") ], TransformNode.prototype, "_position", void 0); __decorate([ serializeAsVector3("rotation") ], TransformNode.prototype, "_rotation", void 0); __decorate([ serializeAsQuaternion("rotationQuaternion") ], TransformNode.prototype, "_rotationQuaternion", void 0); __decorate([ serializeAsVector3("scaling") ], TransformNode.prototype, "_scaling", void 0); __decorate([ serialize("billboardMode") ], TransformNode.prototype, "_billboardMode", void 0); __decorate([ serialize() ], TransformNode.prototype, "scalingDeterminant", void 0); __decorate([ serialize("infiniteDistance") ], TransformNode.prototype, "_infiniteDistance", void 0); __decorate([ serialize() ], TransformNode.prototype, "ignoreNonUniformScaling", void 0); __decorate([ serialize() ], TransformNode.prototype, "reIntegrateRotationIntoRotationQuaternion", void 0); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Collisions/meshCollisionData.js init_math_vector(); var _MeshCollisionData = class { static { __name(this, "_MeshCollisionData"); } constructor() { this._checkCollisions = false; this._collisionMask = -1; this._collisionGroup = -1; this._surroundingMeshes = null; this._collider = null; this._oldPositionForCollisions = new Vector3(0, 0, 0); this._diffPositionForCollisions = new Vector3(0, 0, 0); this._collisionResponse = true; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/abstractMesh.js init_tslib_es6(); init_observable(); init_math_vector(); init_buffer(); init_pickingInfo(); init_boundingInfo(); init_uniformBuffer(); init_devTools(); init_math_color(); init_math_constants(); init_math_axis(); init_typeStore(); init_decorators(); init_abstractEngine(); function ApplyMorph(data, kind, morphTargetManager) { let getTargetData = null; switch (kind) { case VertexBuffer.PositionKind: getTargetData = /* @__PURE__ */ __name((target) => target.getPositions(), "getTargetData"); break; case VertexBuffer.NormalKind: getTargetData = /* @__PURE__ */ __name((target) => target.getNormals(), "getTargetData"); break; case VertexBuffer.TangentKind: getTargetData = /* @__PURE__ */ __name((target) => target.getTangents(), "getTargetData"); break; case VertexBuffer.UVKind: getTargetData = /* @__PURE__ */ __name((target) => target.getUVs(), "getTargetData"); break; case VertexBuffer.UV2Kind: getTargetData = /* @__PURE__ */ __name((target) => target.getUV2s(), "getTargetData"); break; case VertexBuffer.ColorKind: getTargetData = /* @__PURE__ */ __name((target) => target.getColors(), "getTargetData"); break; default: return; } for (let index = 0; index < data.length; index++) { let value = data[index]; for (let targetCount = 0; targetCount < morphTargetManager.numTargets; targetCount++) { const target = morphTargetManager.getTarget(targetCount); const influence = target.influence; if (influence !== 0) { const targetData = getTargetData(target); if (targetData) { value += (targetData[index] - data[index]) * influence; } } } data[index] = value; } } __name(ApplyMorph, "ApplyMorph"); function ApplySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData) { const tempVector = TmpVectors.Vector3[0]; const finalMatrix = TmpVectors.Matrix[0]; const tempMatrix = TmpVectors.Matrix[1]; const transformFromFloatsToRef = kind === VertexBuffer.NormalKind ? Vector3.TransformNormalFromFloatsToRef : Vector3.TransformCoordinatesFromFloatsToRef; for (let index = 0, matWeightIdx = 0; index < data.length; index += 3, matWeightIdx += 4) { finalMatrix.reset(); let inf; let weight; for (inf = 0; inf < 4; inf++) { weight = matricesWeightsData[matWeightIdx + inf]; if (weight > 0) { Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix); finalMatrix.addToSelf(tempMatrix); } } if (matricesIndicesExtraData && matricesWeightsExtraData) { for (inf = 0; inf < 4; inf++) { weight = matricesWeightsExtraData[matWeightIdx + inf]; if (weight > 0) { Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix); finalMatrix.addToSelf(tempMatrix); } } } transformFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector); tempVector.toArray(data, index); } } __name(ApplySkeleton, "ApplySkeleton"); var _FacetDataStorage = class { static { __name(this, "_FacetDataStorage"); } constructor() { this.facetNb = 0; this.partitioningSubdivisions = 10; this.partitioningBBoxRatio = 1.01; this.facetDataEnabled = false; this.facetParameters = {}; this.bbSize = Vector3.Zero(); this.subDiv = { // actual number of subdivisions per axis for ComputeNormals() max: 1, // eslint-disable-next-line @typescript-eslint/naming-convention X: 1, // eslint-disable-next-line @typescript-eslint/naming-convention Y: 1, // eslint-disable-next-line @typescript-eslint/naming-convention Z: 1 }; this.facetDepthSort = false; this.facetDepthSortEnabled = false; } }; var _InternalAbstractMeshDataInfo = class { static { __name(this, "_InternalAbstractMeshDataInfo"); } constructor() { this._hasVertexAlpha = false; this._useVertexColors = true; this._numBoneInfluencers = 4; this._applyFog = true; this._receiveShadows = false; this._facetData = new _FacetDataStorage(); this._visibility = 1; this._skeleton = null; this._layerMask = 268435455; this._computeBonesUsingShaders = true; this._isActive = false; this._onlyForInstances = false; this._isActiveIntermediate = false; this._onlyForInstancesIntermediate = false; this._actAsRegularMesh = false; this._currentLOD = /* @__PURE__ */ new Map(); this._collisionRetryCount = 3; this._morphTargetManager = null; this._renderingGroupId = 0; this._bakedVertexAnimationManager = null; this._material = null; this._positions = null; this._pointerOverDisableMeshTesting = false; this._meshCollisionData = new _MeshCollisionData(); this._enableDistantPicking = false; this._rawBoundingInfo = null; this._sideOrientationHint = false; this._wasActiveLastFrame = false; } }; var AbstractMesh = class _AbstractMesh extends TransformNode { static { __name(this, "AbstractMesh"); } /** * No billboard */ static get BILLBOARDMODE_NONE() { return TransformNode.BILLBOARDMODE_NONE; } /** Billboard on X axis */ static get BILLBOARDMODE_X() { return TransformNode.BILLBOARDMODE_X; } /** Billboard on Y axis */ static get BILLBOARDMODE_Y() { return TransformNode.BILLBOARDMODE_Y; } /** Billboard on Z axis */ static get BILLBOARDMODE_Z() { return TransformNode.BILLBOARDMODE_Z; } /** Billboard on all axes */ static get BILLBOARDMODE_ALL() { return TransformNode.BILLBOARDMODE_ALL; } /** Billboard on using position instead of orientation */ static get BILLBOARDMODE_USE_POSITION() { return TransformNode.BILLBOARDMODE_USE_POSITION; } /** * Gets the number of facets in the mesh * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#what-is-a-mesh-facet */ get facetNb() { return this._internalAbstractMeshDataInfo._facetData.facetNb; } /** * Gets or set the number (integer) of subdivisions per axis in the partitioning space * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#tweaking-the-partitioning */ get partitioningSubdivisions() { return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions; } set partitioningSubdivisions(nb) { this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions = nb; } /** * The ratio (float) to apply to the bounding box size to set to the partitioning space. * Ex : 1.01 (default) the partitioning space is 1% bigger than the bounding box * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#tweaking-the-partitioning */ // eslint-disable-next-line @typescript-eslint/naming-convention get partitioningBBoxRatio() { return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio; } // eslint-disable-next-line @typescript-eslint/naming-convention set partitioningBBoxRatio(ratio) { this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio = ratio; } /** * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`. * Works only for updatable meshes. * Doesn't work with multi-materials * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#facet-depth-sort */ get mustDepthSortFacets() { return this._internalAbstractMeshDataInfo._facetData.facetDepthSort; } set mustDepthSortFacets(sort) { this._internalAbstractMeshDataInfo._facetData.facetDepthSort = sort; } /** * The location (Vector3) where the facet depth sort must be computed from. * By default, the active camera position. * Used only when facet depth sort is enabled * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#facet-depth-sort */ get facetDepthSortFrom() { return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom; } set facetDepthSortFrom(location2) { this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom = location2; } /** number of collision detection tries. Change this value if not all collisions are detected and handled properly */ get collisionRetryCount() { return this._internalAbstractMeshDataInfo._collisionRetryCount; } set collisionRetryCount(retryCount) { this._internalAbstractMeshDataInfo._collisionRetryCount = retryCount; } /** * gets a boolean indicating if facetData is enabled * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData#what-is-a-mesh-facet */ get isFacetDataEnabled() { return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled; } /** * Gets or sets the morph target manager * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/morphTargets */ get morphTargetManager() { return this._internalAbstractMeshDataInfo._morphTargetManager; } set morphTargetManager(value) { if (this._internalAbstractMeshDataInfo._morphTargetManager === value) { return; } this._internalAbstractMeshDataInfo._morphTargetManager = value; this._syncGeometryWithMorphTargetManager(); } /** * Gets or sets the baked vertex animation manager * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/baked_texture_animations */ get bakedVertexAnimationManager() { return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager; } set bakedVertexAnimationManager(value) { if (this._internalAbstractMeshDataInfo._bakedVertexAnimationManager === value) { return; } this._internalAbstractMeshDataInfo._bakedVertexAnimationManager = value; this._markSubMeshesAsAttributesDirty(); } /** @internal */ _syncGeometryWithMorphTargetManager() { } /** * @internal */ _updateNonUniformScalingState(value) { if (!super._updateNonUniformScalingState(value)) { return false; } this._markSubMeshesAsMiscDirty(); return true; } /** @internal */ get rawBoundingInfo() { return this._internalAbstractMeshDataInfo._rawBoundingInfo; } set rawBoundingInfo(boundingInfo) { this._internalAbstractMeshDataInfo._rawBoundingInfo = boundingInfo; } /** Set a function to call when this mesh collides with another one */ set onCollide(callback) { if (this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver) { this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver); } this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver = this.onCollideObservable.add(callback); } /** Set a function to call when the collision's position changes */ set onCollisionPositionChange(callback) { if (this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver) { this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver); } this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback); } /** * Gets or sets mesh visibility between 0 and 1 (default is 1) */ get visibility() { return this._internalAbstractMeshDataInfo._visibility; } /** * Gets or sets mesh visibility between 0 and 1 (default is 1) */ set visibility(value) { if (this._internalAbstractMeshDataInfo._visibility === value) { return; } const oldValue = this._internalAbstractMeshDataInfo._visibility; this._internalAbstractMeshDataInfo._visibility = value; if (oldValue === 1 && value !== 1 || oldValue !== 1 && value === 1) { this._markSubMeshesAsDirty((defines) => { defines.markAsMiscDirty(); defines.markAsPrePassDirty(); }); } } /** * Gets or sets the property which disables the test that is checking that the mesh under the pointer is the same than the previous time we tested for it (default: false). * Set this property to true if you want thin instances picking to be reported accurately when moving over the mesh. * Note that setting this property to true will incur some performance penalties when dealing with pointer events for this mesh so use it sparingly. */ get pointerOverDisableMeshTesting() { return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting; } set pointerOverDisableMeshTesting(disable) { this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting = disable; } /** * Specifies the rendering group id for this mesh (0 by default) * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/transparent_rendering#rendering-groups */ get renderingGroupId() { return this._internalAbstractMeshDataInfo._renderingGroupId; } set renderingGroupId(value) { this._internalAbstractMeshDataInfo._renderingGroupId = value; } /** Gets or sets current material */ get material() { return this._internalAbstractMeshDataInfo._material; } set material(value) { this._setMaterial(value); } /** @internal */ _setMaterial(value) { if (this._internalAbstractMeshDataInfo._material === value) { return; } if (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap) { this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = void 0; } this._internalAbstractMeshDataInfo._material = value; if (value && value.meshMap) { value.meshMap[this.uniqueId] = this; } if (this.onMaterialChangedObservable.hasObservers()) { this.onMaterialChangedObservable.notifyObservers(this); } if (!this.subMeshes) { return; } this.resetDrawCache(void 0, value == null); this._unBindEffect(); } /** * Gets the material used to render the mesh in a specific render pass * @param renderPassId render pass id * @returns material used for the render pass. If no specific material is used for this render pass, undefined is returned (meaning mesh.material is used for this pass) */ getMaterialForRenderPass(renderPassId) { return this._internalAbstractMeshDataInfo._materialForRenderPass?.[renderPassId]; } /** * Sets the material to be used to render the mesh in a specific render pass * @param renderPassId render pass id * @param material material to use for this render pass. If undefined is passed, no specific material will be used for this render pass but the regular material will be used instead (mesh.material) */ setMaterialForRenderPass(renderPassId, material) { this.resetDrawCache(renderPassId); if (!this._internalAbstractMeshDataInfo._materialForRenderPass) { this._internalAbstractMeshDataInfo._materialForRenderPass = []; } const currentMaterial = this._internalAbstractMeshDataInfo._materialForRenderPass[renderPassId]; if (currentMaterial?.meshMap?.[this.uniqueId]) { currentMaterial.meshMap[this.uniqueId] = void 0; } this._internalAbstractMeshDataInfo._materialForRenderPass[renderPassId] = material; if (material && material.meshMap) { material.meshMap[this.uniqueId] = this; } } /** * Gets or sets a boolean indicating that this mesh can receive realtime shadows * @see https://doc.babylonjs.com/features/featuresDeepDive/lights/shadows */ get receiveShadows() { return this._internalAbstractMeshDataInfo._receiveShadows; } set receiveShadows(value) { if (this._internalAbstractMeshDataInfo._receiveShadows === value) { return; } this._internalAbstractMeshDataInfo._receiveShadows = value; this._markSubMeshesAsLightDirty(); } /** * Gets or sets a boolean indicating that this mesh needs to use vertex alpha data to render. * This property is misnamed and should be `useVertexAlpha`. Note that the mesh will be rendered * with alpha blending when this flag is set even if vertex alpha data is missing from the geometry. */ get hasVertexAlpha() { return this._internalAbstractMeshDataInfo._hasVertexAlpha; } set hasVertexAlpha(value) { if (this._internalAbstractMeshDataInfo._hasVertexAlpha === value) { return; } this._internalAbstractMeshDataInfo._hasVertexAlpha = value; this._markSubMeshesAsAttributesDirty(); this._markSubMeshesAsMiscDirty(); } /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */ get useVertexColors() { return this._internalAbstractMeshDataInfo._useVertexColors; } set useVertexColors(value) { if (this._internalAbstractMeshDataInfo._useVertexColors === value) { return; } this._internalAbstractMeshDataInfo._useVertexColors = value; this._markSubMeshesAsAttributesDirty(); } /** * Gets or sets a boolean indicating that bone animations must be computed by the GPU (true by default) */ get computeBonesUsingShaders() { return this._internalAbstractMeshDataInfo._computeBonesUsingShaders; } set computeBonesUsingShaders(value) { if (this._internalAbstractMeshDataInfo._computeBonesUsingShaders === value) { return; } this._internalAbstractMeshDataInfo._computeBonesUsingShaders = value; this._markSubMeshesAsAttributesDirty(); } /** Gets or sets the number of allowed bone influences per vertex (4 by default) */ get numBoneInfluencers() { return this._internalAbstractMeshDataInfo._numBoneInfluencers; } set numBoneInfluencers(value) { if (this._internalAbstractMeshDataInfo._numBoneInfluencers === value) { return; } this._internalAbstractMeshDataInfo._numBoneInfluencers = value; this._markSubMeshesAsAttributesDirty(); } /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */ get applyFog() { return this._internalAbstractMeshDataInfo._applyFog; } set applyFog(value) { if (this._internalAbstractMeshDataInfo._applyFog === value) { return; } this._internalAbstractMeshDataInfo._applyFog = value; this._markSubMeshesAsMiscDirty(); } /** When enabled, decompose picking matrices for better precision with large values for mesh position and scling */ get enableDistantPicking() { return this._internalAbstractMeshDataInfo._enableDistantPicking; } set enableDistantPicking(value) { this._internalAbstractMeshDataInfo._enableDistantPicking = value; } /** * Gets or sets the current layer mask (default is 0x0FFFFFFF) * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/layerMasksAndMultiCam */ get layerMask() { return this._internalAbstractMeshDataInfo._layerMask; } set layerMask(value) { if (value === this._internalAbstractMeshDataInfo._layerMask) { return; } this._internalAbstractMeshDataInfo._layerMask = value; this._resyncLightSources(); } /** * Gets or sets a collision mask used to mask collisions (default is -1). * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 */ get collisionMask() { return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask; } set collisionMask(mask) { this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask = !isNaN(mask) ? mask : -1; } /** * Gets or sets a collision response flag (default is true). * when collisionResponse is false, events are still triggered but colliding entity has no response * This helps creating trigger volume when user wants collision feedback events but not position/velocity * to respond to the collision. */ get collisionResponse() { return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse; } set collisionResponse(response) { this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse = response; } /** * Gets or sets the current collision group mask (-1 by default). * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0 */ get collisionGroup() { return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup; } set collisionGroup(mask) { this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup = !isNaN(mask) ? mask : -1; } /** * Gets or sets current surrounding meshes (null by default). * * By default collision detection is tested against every mesh in the scene. * It is possible to set surroundingMeshes to a defined list of meshes and then only these specified * meshes will be tested for the collision. * * Note: if set to an empty array no collision will happen when this mesh is moved. */ get surroundingMeshes() { return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes; } set surroundingMeshes(meshes) { this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes = meshes; } /** Gets the list of lights affecting that mesh */ get lightSources() { return this._lightSources; } /** * Gets or sets a skeleton to apply skinning transformations * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/bonesSkeletons */ set skeleton(value) { const skeleton = this._internalAbstractMeshDataInfo._skeleton; if (skeleton && skeleton.needInitialSkinMatrix) { skeleton._unregisterMeshWithPoseMatrix(this); } if (value && value.needInitialSkinMatrix) { value._registerMeshWithPoseMatrix(this); } this._internalAbstractMeshDataInfo._skeleton = value; if (!this._internalAbstractMeshDataInfo._skeleton) { this._bonesTransformMatrices = null; } this._markSubMeshesAsAttributesDirty(); } get skeleton() { return this._internalAbstractMeshDataInfo._skeleton; } // Constructor /** * Creates a new AbstractMesh * @param name defines the name of the mesh * @param scene defines the hosting scene */ constructor(name260, scene = null) { super(name260, scene, false); this._internalAbstractMeshDataInfo = new _InternalAbstractMeshDataInfo(); this._waitingMaterialId = null; this._waitingMorphTargetManagerId = null; this.cullingStrategy = _AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY; this.onCollideObservable = new Observable(); this.onCollisionPositionChangeObservable = new Observable(); this.onMaterialChangedObservable = new Observable(); this.definedFacingForward = true; this._occlusionQuery = null; this._renderingGroup = null; this.alphaIndex = Number.MAX_VALUE; this.isPickable = true; this.isNearPickable = false; this.isNearGrabbable = false; this.showSubMeshesBoundingBox = false; this.isBlocker = false; this.enablePointerMoveEvents = false; this.outlineColor = Color3.Red(); this.outlineWidth = 0.02; this.overlayColor = Color3.Red(); this.overlayAlpha = 0.5; this.useOctreeForRenderingSelection = true; this.useOctreeForPicking = true; this.useOctreeForCollisions = true; this.alwaysSelectAsActiveMesh = false; this.doNotSyncBoundingInfo = false; this.actionManager = null; this.ellipsoid = new Vector3(0.5, 1, 0.5); this.ellipsoidOffset = new Vector3(0, 0, 0); this.edgesWidth = 1; this.edgesColor = new Color4(1, 0, 0, 1); this._edgesRenderer = null; this._masterMesh = null; this._boundingInfo = null; this._boundingInfoIsDirty = true; this._renderId = 0; this._intersectionsInProgress = new Array(); this._unIndexed = false; this._lightSources = new Array(); this._waitingData = { lods: null, actions: null, freezeWorldMatrix: null }; this._bonesTransformMatrices = null; this._transformMatrixTexture = null; this.onRebuildObservable = new Observable(); this._onCollisionPositionChange = (collisionId, newPosition, collidedMesh = null) => { newPosition.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions); if (this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length() > AbstractEngine.CollisionsEpsilon) { this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions); } if (collidedMesh) { this.onCollideObservable.notifyObservers(collidedMesh); } this.onCollisionPositionChangeObservable.notifyObservers(this.position); }; scene = this.getScene(); scene.addMesh(this); this._resyncLightSources(); this._uniformBuffer = new UniformBuffer(this.getScene().getEngine(), void 0, void 0, name260, !this.getScene().getEngine().isWebGPU); this._buildUniformLayout(); switch (scene.performancePriority) { case 2: this.doNotSyncBoundingInfo = true; // eslint-disable-next-line no-fallthrough case 1: this.alwaysSelectAsActiveMesh = true; this.isPickable = false; break; } } _buildUniformLayout() { this._uniformBuffer.addUniform("world", 16); this._uniformBuffer.addUniform("visibility", 1); this._uniformBuffer.create(); } /** * Transfer the mesh values to its UBO. * @param world The world matrix associated with the mesh */ transferToEffect(world) { const ubo = this._uniformBuffer; ubo.updateMatrix("world", world); ubo.updateFloat("visibility", this._internalAbstractMeshDataInfo._visibility); ubo.update(); } /** * Gets the mesh uniform buffer. * @returns the uniform buffer of the mesh. */ getMeshUniformBuffer() { return this._uniformBuffer; } /** * Returns the string "AbstractMesh" * @returns "AbstractMesh" */ getClassName() { return "AbstractMesh"; } /** * Gets a string representation of the current mesh * @param fullDetails defines a boolean indicating if full details must be included * @returns a string representation of the current mesh */ toString(fullDetails) { let ret = "Name: " + this.name + ", isInstance: " + (this.getClassName() === "InstancedMesh" ? "YES" : "NO"); ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0); const skeleton = this._internalAbstractMeshDataInfo._skeleton; if (skeleton) { ret += ", skeleton: " + skeleton.name; } if (fullDetails) { ret += ", billboard mode: " + ["NONE", "X", "Y", null, "Z", null, null, "ALL"][this.billboardMode]; ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingData.freezeWorldMatrix ? "YES" : "NO"); } return ret; } /** * @internal */ _getEffectiveParent() { if (this._masterMesh && this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) { return this._masterMesh; } return super._getEffectiveParent(); } /** * @internal */ _getActionManagerForTrigger(trigger, initialCall = true) { if (this.actionManager && (initialCall || this.actionManager.isRecursive)) { if (trigger) { if (this.actionManager.hasSpecificTrigger(trigger)) { return this.actionManager; } } else { return this.actionManager; } } if (!this.parent) { return null; } return this.parent._getActionManagerForTrigger(trigger, false); } /** * @internal */ // eslint-disable-next-line @typescript-eslint/no-unused-vars _rebuild(dispose = false) { this.onRebuildObservable.notifyObservers(this); if (this._occlusionQuery !== null) { this._occlusionQuery = null; } if (!this.subMeshes) { return; } for (const subMesh of this.subMeshes) { subMesh._rebuild(); } this.resetDrawCache(); } /** @internal */ _resyncLightSources() { this._lightSources.length = 0; for (const light of this.getScene().lights) { if (!light.isEnabled()) { continue; } if (light.canAffectMesh(this)) { this._lightSources.push(light); } } this._markSubMeshesAsLightDirty(); } /** * @internal */ _resyncLightSource(light) { const isIn = light.isEnabled() && light.canAffectMesh(this); const index = this._lightSources.indexOf(light); let removed = false; if (index === -1) { if (!isIn) { return; } this._lightSources.push(light); } else { if (isIn) { return; } removed = true; this._lightSources.splice(index, 1); } this._markSubMeshesAsLightDirty(removed); } /** @internal */ _unBindEffect() { for (const subMesh of this.subMeshes) { subMesh.setEffect(null); } } /** * @internal */ _removeLightSource(light, dispose) { const index = this._lightSources.indexOf(light); if (index === -1) { return; } this._lightSources.splice(index, 1); this._markSubMeshesAsLightDirty(dispose); } _markSubMeshesAsDirty(func) { if (!this.subMeshes) { return; } for (const subMesh of this.subMeshes) { for (let i = 0; i < subMesh._drawWrappers.length; ++i) { const drawWrapper = subMesh._drawWrappers[i]; if (!drawWrapper || !drawWrapper.defines || !drawWrapper.defines.markAllAsDirty) { continue; } func(drawWrapper.defines); } } } /** * @internal */ _markSubMeshesAsLightDirty(dispose = false) { this._markSubMeshesAsDirty((defines) => defines.markAsLightDirty(dispose)); } /** @internal */ _markSubMeshesAsAttributesDirty() { this._markSubMeshesAsDirty((defines) => defines.markAsAttributesDirty()); } /** @internal */ _markSubMeshesAsMiscDirty() { this._markSubMeshesAsDirty((defines) => defines.markAsMiscDirty()); } /** * Flag the AbstractMesh as dirty (Forcing it to update everything) * @param property if set to "rotation" the objects rotationQuaternion will be set to null * @returns this AbstractMesh */ // eslint-disable-next-line @typescript-eslint/no-unused-vars markAsDirty(property) { this._currentRenderId = Number.MAX_VALUE; super.markAsDirty(property); this._isDirty = true; return this; } /** * Resets the draw wrappers cache for all submeshes of this abstract mesh * @param passId If provided, releases only the draw wrapper corresponding to this render pass id * @param immediate If true, the effect will be released immediately, otherwise it will be released at the next frame */ resetDrawCache(passId, immediate = false) { if (!this.subMeshes) { return; } for (const subMesh of this.subMeshes) { subMesh.resetDrawCache(passId, immediate); } } // Methods /** * Returns true if the mesh is blocked. Implemented by child classes */ get isBlocked() { return false; } /** * Returns the mesh itself by default. Implemented by child classes * @param camera defines the camera to use to pick the right LOD level * @returns the currentAbstractMesh */ // eslint-disable-next-line @typescript-eslint/no-unused-vars getLOD(camera) { return this; } /** * Returns 0 by default. Implemented by child classes * @returns an integer */ getTotalVertices() { return 0; } /** * Returns a positive integer : the total number of indices in this mesh geometry. * @returns the number of indices or zero if the mesh has no geometry. */ getTotalIndices() { return 0; } /** * Returns null by default. Implemented by child classes * @returns null */ getIndices() { return null; } /** * Returns the array of the requested vertex data kind. Implemented by child classes * @param kind defines the vertex data kind to use * @returns null */ // eslint-disable-next-line @typescript-eslint/no-unused-vars getVerticesData(kind) { return null; } /** * Sets the vertex data of the mesh geometry for the requested `kind`. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data. * Note that a new underlying VertexBuffer object is created each call. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed. * @param kind defines vertex data kind: * * VertexBuffer.PositionKind * * VertexBuffer.UVKind * * VertexBuffer.UV2Kind * * VertexBuffer.UV3Kind * * VertexBuffer.UV4Kind * * VertexBuffer.UV5Kind * * VertexBuffer.UV6Kind * * VertexBuffer.ColorKind * * VertexBuffer.MatricesIndicesKind * * VertexBuffer.MatricesIndicesExtraKind * * VertexBuffer.MatricesWeightsKind * * VertexBuffer.MatricesWeightsExtraKind * @param data defines the data source * @param updatable defines if the data must be flagged as updatable (or static) * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind * @returns the current mesh */ // eslint-disable-next-line @typescript-eslint/no-unused-vars setVerticesData(kind, data, updatable, stride) { return this; } /** * Updates the existing vertex data of the mesh geometry for the requested `kind`. * If the mesh has no geometry, it is simply returned as it is. * @param kind defines vertex data kind: * * VertexBuffer.PositionKind * * VertexBuffer.UVKind * * VertexBuffer.UV2Kind * * VertexBuffer.UV3Kind * * VertexBuffer.UV4Kind * * VertexBuffer.UV5Kind * * VertexBuffer.UV6Kind * * VertexBuffer.ColorKind * * VertexBuffer.MatricesIndicesKind * * VertexBuffer.MatricesIndicesExtraKind * * VertexBuffer.MatricesWeightsKind * * VertexBuffer.MatricesWeightsExtraKind * @param data defines the data source * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh * @returns the current mesh */ // eslint-disable-next-line @typescript-eslint/no-unused-vars updateVerticesData(kind, data, updateExtends, makeItUnique) { return this; } /** * Sets the mesh indices, * If the mesh has no geometry, a new Geometry object is created and set to the mesh. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array) * @param totalVertices Defines the total number of vertices * @returns the current mesh */ // eslint-disable-next-line @typescript-eslint/no-unused-vars setIndices(indices, totalVertices) { return this; } /** * Gets a boolean indicating if specific vertex data is present * @param kind defines the vertex data kind to use * @returns true is data kind is present */ // eslint-disable-next-line @typescript-eslint/no-unused-vars isVerticesDataPresent(kind) { return false; } /** * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined. * Note that it returns a shallow bounding of the mesh (i.e. it does not include children). * However, if the mesh contains thin instances, it will be expanded to include them. If you want the "raw" bounding data instead, then use `getRawBoundingInfo()`. * To get the full bounding of all children, call `getHierarchyBoundingVectors` instead. * @returns a BoundingInfo */ getBoundingInfo() { if (this._masterMesh) { return this._masterMesh.getBoundingInfo(); } if (this._boundingInfoIsDirty) { this._boundingInfoIsDirty = false; this._updateBoundingInfo(); } return this._boundingInfo; } /** * Returns the bounding info unnafected by instance data. * @returns the bounding info of the mesh unaffected by instance data. */ getRawBoundingInfo() { return this.rawBoundingInfo ?? this.getBoundingInfo(); } /** * Overwrite the current bounding info * @param boundingInfo defines the new bounding info * @returns the current mesh */ setBoundingInfo(boundingInfo) { this._boundingInfo = boundingInfo; return this; } /** * Returns true if there is already a bounding info */ get hasBoundingInfo() { return this._boundingInfo !== null; } /** * Creates a new bounding info for the mesh * @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 * @returns the new bounding info */ buildBoundingInfo(minimum, maximum, worldMatrix) { this._boundingInfo = new BoundingInfo(minimum, maximum, worldMatrix); return this._boundingInfo; } /** * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units) * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box. Default is false * @param ignoreRotation ignore rotation when computing the scale (ie. object will be axis aligned). Default is false * @param predicate predicate that is passed in to getHierarchyBoundingVectors when selecting which object should be included when scaling * @returns the current mesh */ normalizeToUnitCube(includeDescendants = true, ignoreRotation = false, predicate) { return super.normalizeToUnitCube(includeDescendants, ignoreRotation, predicate); } /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */ get useBones() { return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind); } /** @internal */ _preActivate() { } /** * @internal */ // eslint-disable-next-line @typescript-eslint/no-unused-vars _preActivateForIntermediateRendering(renderId) { } /** * @internal */ // eslint-disable-next-line @typescript-eslint/no-unused-vars _activate(renderId, intermediateRendering) { this._renderId = renderId; return true; } /** @internal */ _postActivate() { } /** @internal */ _freeze() { } /** @internal */ _unFreeze() { } /** * Gets the current world matrix * @returns a Matrix */ getWorldMatrix() { if (this._masterMesh && this.billboardMode === TransformNode.BILLBOARDMODE_NONE) { return this._masterMesh.getWorldMatrix(); } return super.getWorldMatrix(); } /** @internal */ _getWorldMatrixDeterminant() { if (this._masterMesh) { return this._masterMesh._getWorldMatrixDeterminant(); } return super._getWorldMatrixDeterminant(); } /** * Gets a boolean indicating if this mesh is an instance or a regular mesh */ get isAnInstance() { return false; } /** * Gets a boolean indicating if this mesh has instances */ get hasInstances() { return false; } /** * Gets a boolean indicating if this mesh has thin instances */ get hasThinInstances() { return false; } // ================================== Point of View Movement ================================= /** * Perform relative position change from the point of view of behind the front of the mesh. * This is performed taking into account the meshes current rotation, so you do not have to care. * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }. * @param amountRight defines the distance on the right axis * @param amountUp defines the distance on the up axis * @param amountForward defines the distance on the forward axis * @returns the current mesh */ movePOV(amountRight, amountUp, amountForward) { this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward)); return this; } /** * Calculate relative position change from the point of view of behind the front of the mesh. * This is performed taking into account the meshes current rotation, so you do not have to care. * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }. * @param amountRight defines the distance on the right axis * @param amountUp defines the distance on the up axis * @param amountForward defines the distance on the forward axis * @returns the new displacement vector */ calcMovePOV(amountRight, amountUp, amountForward) { const rotMatrix = new Matrix(); const rotQuaternion = this.rotationQuaternion ? this.rotationQuaternion : Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z); rotQuaternion.toRotationMatrix(rotMatrix); const translationDelta = Vector3.Zero(); const defForwardMult = this.definedFacingForward ? -1 : 1; Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta); return translationDelta; } // ================================== Point of View Rotation ================================= /** * Perform relative rotation change from the point of view of behind the front of the mesh. * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }. * @param flipBack defines the flip * @param twirlClockwise defines the twirl * @param tiltRight defines the tilt * @returns the current mesh */ rotatePOV(flipBack, twirlClockwise, tiltRight) { this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight)); return this; } /** * Calculate relative rotation change from the point of view of behind the front of the mesh. * Supports definition of mesh facing forward or backward {@link definedFacingForwardSearch | See definedFacingForwardSearch }. * @param flipBack defines the flip * @param twirlClockwise defines the twirl * @param tiltRight defines the tilt * @returns the new rotation vector */ calcRotatePOV(flipBack, twirlClockwise, tiltRight) { const defForwardMult = this.definedFacingForward ? 1 : -1; return new Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult); } /** * @internal */ _refreshBoundingInfo(data, bias) { if (data) { const extend = extractMinAndMax(data, 0, this.getTotalVertices(), bias); if (this._boundingInfo) { this._boundingInfo.reConstruct(extend.minimum, extend.maximum); } else { this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum); } } if (this.subMeshes) { for (let index = 0; index < this.subMeshes.length; index++) { this.subMeshes[index].refreshBoundingInfo(data); } } this._updateBoundingInfo(); } /** * @internal */ _refreshBoundingInfoDirect(extend) { if (this._boundingInfo) { this._boundingInfo.reConstruct(extend.minimum, extend.maximum); } else { this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum); } if (this.subMeshes) { for (let index = 0; index < this.subMeshes.length; index++) { this.subMeshes[index].refreshBoundingInfo(null); } } this._updateBoundingInfo(); } // This function is only here so we can apply the nativeOverride decorator. static _ApplySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData) { ApplySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData); } /** @internal */ _getData(options, data, kind = VertexBuffer.PositionKind) { const cache = options.cache; const getVertexData = /* @__PURE__ */ __name((kind2) => { if (cache) { const vertexData = cache._vertexData || (cache._vertexData = {}); if (!vertexData[kind2]) { this.copyVerticesData(kind2, vertexData); } return vertexData[kind2]; } return this.getVerticesData(kind2); }, "getVertexData"); data || (data = getVertexData(kind)); if (!data) { return null; } if (cache) { if (cache._outputData) { cache._outputData.set(data); } else { cache._outputData = new Float32Array(data); } data = cache._outputData; } else if (options.applyMorph && this.morphTargetManager || options.applySkeleton && this.skeleton) { data = data.slice(); } if (options.applyMorph && this.morphTargetManager) { ApplyMorph(data, kind, this.morphTargetManager); } if (options.applySkeleton && this.skeleton) { const matricesIndicesData = getVertexData(VertexBuffer.MatricesIndicesKind); const matricesWeightsData = getVertexData(VertexBuffer.MatricesWeightsKind); if (matricesWeightsData && matricesIndicesData) { const needExtras = this.numBoneInfluencers > 4; const matricesIndicesExtraData = needExtras ? getVertexData(VertexBuffer.MatricesIndicesExtraKind) : null; const matricesWeightsExtraData = needExtras ? getVertexData(VertexBuffer.MatricesWeightsExtraKind) : null; const skeletonMatrices = this.skeleton.getTransformMatrices(this); _AbstractMesh._ApplySkeleton(data, kind, skeletonMatrices, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData); } } if (options.updatePositionsArray !== false && kind === VertexBuffer.PositionKind) { const positions = this._internalAbstractMeshDataInfo._positions || []; const previousLength = positions.length; positions.length = data.length / 3; if (previousLength < positions.length) { for (let positionIndex = previousLength; positionIndex < positions.length; positionIndex++) { positions[positionIndex] = new Vector3(); } } for (let positionIndex = 0, dataIndex = 0; positionIndex < positions.length; positionIndex++, dataIndex += 3) { positions[positionIndex].copyFromFloats(data[dataIndex], data[dataIndex + 1], data[dataIndex + 2]); } this._internalAbstractMeshDataInfo._positions = positions; } return data; } /** * Get the normals vertex data and optionally apply skeleton and morphing. * @param applySkeleton defines whether to apply the skeleton * @param applyMorph defines whether to apply the morph target * @returns the normals data */ getNormalsData(applySkeleton = false, applyMorph = false) { return this._getData({ applySkeleton, applyMorph, updatePositionsArray: false }, null, VertexBuffer.NormalKind); } /** * Get the position vertex data and optionally apply skeleton and morphing. * @param applySkeleton defines whether to apply the skeleton * @param applyMorph defines whether to apply the morph target * @param data defines the position data to apply the skeleton and morph to * @returns the position data */ getPositionData(applySkeleton = false, applyMorph = false, data = null) { return this._getData({ applySkeleton, applyMorph, updatePositionsArray: false }, data, VertexBuffer.PositionKind); } /** @internal */ _updateBoundingInfo() { if (this._boundingInfo) { this._boundingInfo.update(this.worldMatrixFromCache); } else { this._boundingInfo = new BoundingInfo(Vector3.Zero(), Vector3.Zero(), this.worldMatrixFromCache); } this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache); return this; } /** * @internal */ _updateSubMeshesBoundingInfo(matrix) { if (!this.subMeshes) { return this; } const count = this.subMeshes.length; for (let subIndex = 0; subIndex < count; subIndex++) { const subMesh = this.subMeshes[subIndex]; if (count > 1 || !subMesh.IsGlobal) { subMesh.updateBoundingInfo(matrix); } } return this; } /** @internal */ _afterComputeWorldMatrix() { if (this.doNotSyncBoundingInfo) { return; } this._boundingInfoIsDirty = true; } /** * Returns `true` if the mesh is within the frustum defined by the passed array of planes. * A mesh is in the frustum if its bounding box intersects the frustum * @param frustumPlanes defines the frustum to test * @returns true if the mesh is in the frustum planes */ isInFrustum(frustumPlanes) { return this.getBoundingInfo().isInFrustum(frustumPlanes, this.cullingStrategy); } /** * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes. * A mesh is completely in the frustum if its bounding box it completely inside the frustum. * @param frustumPlanes defines the frustum to test * @returns true if the mesh is completely in the frustum planes */ isCompletelyInFrustum(frustumPlanes) { return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes); } /** * True if the mesh intersects another mesh or a SolidParticle object * @param mesh defines a target mesh or SolidParticle to test * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes) * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes * @returns true if there is an intersection */ intersectsMesh(mesh, precise = false, includeDescendants) { const boundingInfo = this.getBoundingInfo(); const otherBoundingInfo = mesh.getBoundingInfo(); if (boundingInfo.intersects(otherBoundingInfo, precise)) { return true; } if (includeDescendants) { for (const child of this.getChildMeshes()) { if (child.intersectsMesh(mesh, precise, true)) { return true; } } } return false; } /** * Returns true if the passed point (Vector3) is inside the mesh bounding box * @param point defines the point to test * @returns true if there is an intersection */ intersectsPoint(point) { return this.getBoundingInfo().intersectsPoint(point); } // Collisions /** * Gets or sets a boolean indicating that this mesh can be used in the collision engine * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions */ get checkCollisions() { return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions; } set checkCollisions(collisionEnabled) { this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions = collisionEnabled; } /** * Gets Collider object used to compute collisions (not physics) * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions */ get collider() { return this._internalAbstractMeshDataInfo._meshCollisionData._collider; } /** * Move the mesh using collision engine * @see https://doc.babylonjs.com/features/featuresDeepDive/cameras/camera_collisions * @param displacement defines the requested displacement vector * @param slideOnCollide If true, the mesh will slide along a collider's surface. If false, it will stop moving at the first collision. (true by default) * @returns the current mesh */ moveWithCollisions(displacement, slideOnCollide = true) { const globalPosition = this.getAbsolutePosition(); globalPosition.addToRef(this.ellipsoidOffset, this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions); const coordinator = this.getScene().collisionCoordinator; if (!this._internalAbstractMeshDataInfo._meshCollisionData._collider) { this._internalAbstractMeshDataInfo._meshCollisionData._collider = coordinator.createCollider(); } this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius = this.ellipsoid; coordinator.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions, displacement, this._internalAbstractMeshDataInfo._meshCollisionData._collider, this.collisionRetryCount, this, this._onCollisionPositionChange, this.uniqueId, slideOnCollide); return this; } // Collisions /** * @internal */ _collideForSubMesh(subMesh, transformMatrix, collider) { this._generatePointsArray(); if (!this._positions) { return this; } if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) { subMesh._lastColliderTransformMatrix = transformMatrix.clone(); subMesh._lastColliderWorldVertices = []; subMesh._trianglePlanes = []; const start = subMesh.verticesStart; const end = subMesh.verticesStart + subMesh.verticesCount; for (let i = start; i < end; i++) { subMesh._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[i], transformMatrix)); } } collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial(), this, this._shouldConvertRHS(), subMesh.getMaterial()?.fillMode === 7); return this; } /** * @internal */ _processCollisionsForSubMeshes(collider, transformMatrix) { const subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider); const len = subMeshes.length; for (let index = 0; index < len; index++) { const subMesh = subMeshes.data[index]; if (len > 1 && !subMesh._checkCollision(collider)) { continue; } this._collideForSubMesh(subMesh, transformMatrix, collider); } return this; } /** @internal */ _shouldConvertRHS() { return false; } /** * @internal */ _checkCollision(collider) { if (!this.getBoundingInfo()._checkCollision(collider)) { return this; } const collisionsScalingMatrix = TmpVectors.Matrix[0]; const collisionsTransformMatrix = TmpVectors.Matrix[1]; Matrix.ScalingToRef(1 / collider._radius.x, 1 / collider._radius.y, 1 / collider._radius.z, collisionsScalingMatrix); this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix); this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix); return this; } // Picking /** @internal */ _generatePointsArray() { return false; } /** * Checks if the passed Ray intersects with the mesh. A mesh triangle can be picked both from its front and back sides, * irrespective of orientation. * @param ray defines the ray to use. It should be in the mesh's LOCAL coordinate space. * @param fastCheck defines if fast mode (but less precise) must be used (false by default) * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default) * @param worldToUse defines the world matrix to use to get the world coordinate of the intersection point * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check * @returns the picking info * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/interactions/mesh_intersect */ intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) { const pickingInfo = new PickingInfo(); const className2 = this.getClassName(); const intersectionThreshold = className2 === "InstancedLinesMesh" || className2 === "LinesMesh" || className2 === "GreasedLineMesh" ? this.intersectionThreshold : 0; const boundingInfo = this.getBoundingInfo(); if (!this.subMeshes) { return pickingInfo; } if (!skipBoundingInfo && (!ray.intersectsSphere(boundingInfo.boundingSphere, intersectionThreshold) || !ray.intersectsBox(boundingInfo.boundingBox, intersectionThreshold))) { return pickingInfo; } if (onlyBoundingInfo) { pickingInfo.hit = skipBoundingInfo ? false : true; pickingInfo.pickedMesh = skipBoundingInfo ? null : this; pickingInfo.distance = skipBoundingInfo ? 0 : Vector3.Distance(ray.origin, boundingInfo.boundingSphere.center); pickingInfo.subMeshId = 0; return pickingInfo; } if (!this._generatePointsArray()) { return pickingInfo; } let intersectInfo = null; const subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray); const len = subMeshes.length; let anySubmeshSupportIntersect = false; for (let index = 0; index < len; index++) { const subMesh = subMeshes.data[index]; const material = subMesh.getMaterial(); if (!material) { continue; } if (material.fillMode == 7 || material.fillMode == 0 || material.fillMode == 1 || material.fillMode == 2 || material.fillMode == 4) { anySubmeshSupportIntersect = true; break; } } if (!anySubmeshSupportIntersect) { pickingInfo.hit = true; pickingInfo.pickedMesh = this; pickingInfo.distance = Vector3.Distance(ray.origin, boundingInfo.boundingSphere.center); pickingInfo.subMeshId = -1; return pickingInfo; } for (let index = 0; index < len; index++) { const subMesh = subMeshes.data[index]; if (len > 1 && !skipBoundingInfo && !subMesh.canIntersects(ray)) { continue; } const currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck, trianglePredicate); if (currentIntersectInfo) { if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) { intersectInfo = currentIntersectInfo; intersectInfo.subMeshId = subMesh._id; intersectInfo._internalSubMeshId = index; if (fastCheck) { break; } } } } if (intersectInfo) { const world = worldToUse ?? this.getWorldMatrix(); const worldOrigin = TmpVectors.Vector3[0]; const direction = TmpVectors.Vector3[1]; Vector3.TransformCoordinatesToRef(ray.origin, world, worldOrigin); ray.direction.scaleToRef(intersectInfo.distance, direction); const worldDirection = Vector3.TransformNormal(direction, world); const pickedPoint = worldDirection.addInPlace(worldOrigin); pickingInfo.hit = true; pickingInfo.distance = Vector3.Distance(worldOrigin, pickedPoint); pickingInfo.pickedPoint = pickedPoint; pickingInfo.pickedMesh = this; pickingInfo.bu = intersectInfo.bu || 0; pickingInfo.bv = intersectInfo.bv || 0; pickingInfo.subMeshFaceId = intersectInfo.faceId; pickingInfo.faceId = intersectInfo.faceId + subMeshes.data[intersectInfo._internalSubMeshId].indexStart / (this.getClassName().indexOf("LinesMesh") !== -1 ? 2 : 3); pickingInfo.subMeshId = intersectInfo.subMeshId; return pickingInfo; } return pickingInfo; } /** * Clones the current mesh * @param name defines the mesh name * @param newParent defines the new mesh parent * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default) * @returns the new mesh */ // eslint-disable-next-line @typescript-eslint/no-unused-vars clone(name260, newParent, doNotCloneChildren) { return null; } /** * Disposes all the submeshes of the current mesh * @param immediate should dispose the effects immediately or not * @returns the current mesh */ releaseSubMeshes(immediate = false) { if (this.subMeshes) { while (this.subMeshes.length) { this.subMeshes[0].dispose(immediate); } } else { this.subMeshes = []; } return this; } /** * Releases resources associated with this abstract mesh. * @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) */ dispose(doNotRecurse, disposeMaterialAndTextures = false) { let index; const scene = this.getScene(); if (this._scene.useMaterialMeshMap) { if (this._internalAbstractMeshDataInfo._material && this._internalAbstractMeshDataInfo._material.meshMap) { this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId] = void 0; } } scene.freeActiveMeshes(); scene.freeRenderingGroups(); if (scene.renderingManager.maintainStateBetweenFrames) { scene.renderingManager.restoreDispachedFlags(); } if (this.actionManager !== void 0 && this.actionManager !== null) { if (this.actionManager.disposeWhenUnowned && !this._scene.meshes.some((m) => m !== this && m.actionManager === this.actionManager)) { this.actionManager.dispose(); } this.actionManager = null; } this._internalAbstractMeshDataInfo._skeleton = null; if (this._transformMatrixTexture) { this._transformMatrixTexture.dispose(); this._transformMatrixTexture = null; } for (index = 0; index < this._intersectionsInProgress.length; index++) { const other = this._intersectionsInProgress[index]; const pos = other._intersectionsInProgress.indexOf(this); other._intersectionsInProgress.splice(pos, 1); } this._intersectionsInProgress.length = 0; const lights = scene.lights; for (const light of lights) { let meshIndex = light.includedOnlyMeshes.indexOf(this); if (meshIndex !== -1) { light.includedOnlyMeshes.splice(meshIndex, 1); } meshIndex = light.excludedMeshes.indexOf(this); if (meshIndex !== -1) { light.excludedMeshes.splice(meshIndex, 1); } const generators = light.getShadowGenerators(); if (generators) { const iterator = generators.values(); for (let key = iterator.next(); key.done !== true; key = iterator.next()) { const generator = key.value; const shadowMap = generator.getShadowMap(); if (shadowMap && shadowMap.renderList) { meshIndex = shadowMap.renderList.indexOf(this); if (meshIndex !== -1) { shadowMap.renderList.splice(meshIndex, 1); } } } } } if (this.getClassName() !== "InstancedMesh" || this.getClassName() !== "InstancedLinesMesh") { this.releaseSubMeshes(true); } const engine = scene.getEngine(); if (this._occlusionQuery !== null) { this.isOcclusionQueryInProgress = false; engine.deleteQuery(this._occlusionQuery); this._occlusionQuery = null; } engine.wipeCaches(); scene.removeMesh(this); if (this._parentContainer) { const index2 = this._parentContainer.meshes.indexOf(this); if (index2 > -1) { this._parentContainer.meshes.splice(index2, 1); } this._parentContainer = null; } if (disposeMaterialAndTextures) { if (this.material) { if (this.material.getClassName() === "MultiMaterial") { this.material.dispose(false, true, true); } else { this.material.dispose(false, true); } } } if (!doNotRecurse) { for (index = 0; index < scene.particleSystems.length; index++) { if (scene.particleSystems[index].emitter === this) { scene.particleSystems[index].dispose(); index--; } } } if (this._internalAbstractMeshDataInfo._facetData.facetDataEnabled) { this.disableFacetData(); } this._uniformBuffer.dispose(); this.onAfterWorldMatrixUpdateObservable.clear(); this.onCollideObservable.clear(); this.onCollisionPositionChangeObservable.clear(); this.onRebuildObservable.clear(); super.dispose(doNotRecurse, disposeMaterialAndTextures); } // Facet data /** @internal */ _initFacetData() { const data = this._internalAbstractMeshDataInfo._facetData; if (!data.facetNormals) { data.facetNormals = []; } if (!data.facetPositions) { data.facetPositions = []; } if (!data.facetPartitioning) { data.facetPartitioning = new Array(); } data.facetNb = this.getIndices().length / 3 | 0; data.partitioningSubdivisions = data.partitioningSubdivisions ? data.partitioningSubdivisions : 10; data.partitioningBBoxRatio = data.partitioningBBoxRatio ? data.partitioningBBoxRatio : 1.01; for (let f = 0; f < data.facetNb; f++) { data.facetNormals[f] = Vector3.Zero(); data.facetPositions[f] = Vector3.Zero(); } data.facetDataEnabled = true; return this; } /** * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated. * This method can be called within the render loop. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation * @returns the current mesh * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData */ updateFacetData() { const data = this._internalAbstractMeshDataInfo._facetData; if (!data.facetDataEnabled) { this._initFacetData(); } const positions = this.getVerticesData(VertexBuffer.PositionKind); const indices = this.getIndices(); const normals = this.getVerticesData(VertexBuffer.NormalKind); const bInfo = this.getBoundingInfo(); if (data.facetDepthSort && !data.facetDepthSortEnabled) { data.facetDepthSortEnabled = true; if (indices instanceof Uint16Array) { data.depthSortedIndices = new Uint16Array(indices); } else if (indices instanceof Uint32Array) { data.depthSortedIndices = new Uint32Array(indices); } else { let needs32bits = false; for (let i = 0; i < indices.length; i++) { if (indices[i] > 65535) { needs32bits = true; break; } } if (needs32bits) { data.depthSortedIndices = new Uint32Array(indices); } else { data.depthSortedIndices = new Uint16Array(indices); } } data.facetDepthSortFunction = function(f1, f2) { return f2.sqDistance - f1.sqDistance; }; if (!data.facetDepthSortFrom) { const camera = this.getScene().activeCamera; data.facetDepthSortFrom = camera ? camera.position : Vector3.Zero(); } data.depthSortedFacets = []; for (let f = 0; f < data.facetNb; f++) { const depthSortedFacet = { ind: f * 3, sqDistance: 0 }; data.depthSortedFacets.push(depthSortedFacet); } data.invertedMatrix = Matrix.Identity(); data.facetDepthSortOrigin = Vector3.Zero(); } data.bbSize.x = bInfo.maximum.x - bInfo.minimum.x > Epsilon ? bInfo.maximum.x - bInfo.minimum.x : Epsilon; data.bbSize.y = bInfo.maximum.y - bInfo.minimum.y > Epsilon ? bInfo.maximum.y - bInfo.minimum.y : Epsilon; data.bbSize.z = bInfo.maximum.z - bInfo.minimum.z > Epsilon ? bInfo.maximum.z - bInfo.minimum.z : Epsilon; let bbSizeMax = data.bbSize.x > data.bbSize.y ? data.bbSize.x : data.bbSize.y; bbSizeMax = bbSizeMax > data.bbSize.z ? bbSizeMax : data.bbSize.z; data.subDiv.max = data.partitioningSubdivisions; data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax); data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y; data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z; data.facetParameters.facetNormals = this.getFacetLocalNormals(); data.facetParameters.facetPositions = this.getFacetLocalPositions(); data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning(); data.facetParameters.bInfo = bInfo; data.facetParameters.bbSize = data.bbSize; data.facetParameters.subDiv = data.subDiv; data.facetParameters.ratio = this.partitioningBBoxRatio; data.facetParameters.depthSort = data.facetDepthSort; if (data.facetDepthSort && data.facetDepthSortEnabled) { this.computeWorldMatrix(true); this._worldMatrix.invertToRef(data.invertedMatrix); Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin); data.facetParameters.distanceTo = data.facetDepthSortOrigin; } data.facetParameters.depthSortedFacets = data.depthSortedFacets; if (normals) { VertexData.ComputeNormals(positions, indices, normals, data.facetParameters); } if (data.facetDepthSort && data.facetDepthSortEnabled) { data.depthSortedFacets.sort(data.facetDepthSortFunction); const l = data.depthSortedIndices.length / 3 | 0; for (let f = 0; f < l; f++) { const sind = data.depthSortedFacets[f].ind; data.depthSortedIndices[f * 3] = indices[sind]; data.depthSortedIndices[f * 3 + 1] = indices[sind + 1]; data.depthSortedIndices[f * 3 + 2] = indices[sind + 2]; } this.updateIndices(data.depthSortedIndices, void 0, true); } return this; } /** * Returns the facetLocalNormals array. * The normals are expressed in the mesh local spac * @returns an array of Vector3 * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData */ getFacetLocalNormals() { const facetData = this._internalAbstractMeshDataInfo._facetData; if (!facetData.facetNormals) { this.updateFacetData(); } return facetData.facetNormals; } /** * Returns the facetLocalPositions array. * The facet positions are expressed in the mesh local space * @returns an array of Vector3 * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData */ getFacetLocalPositions() { const facetData = this._internalAbstractMeshDataInfo._facetData; if (!facetData.facetPositions) { this.updateFacetData(); } return facetData.facetPositions; } /** * Returns the facetLocalPartitioning array * @returns an array of array of numbers * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData */ getFacetLocalPartitioning() { const facetData = this._internalAbstractMeshDataInfo._facetData; if (!facetData.facetPartitioning) { this.updateFacetData(); } return facetData.facetPartitioning; } /** * Returns the i-th facet position in the world system. * This method allocates a new Vector3 per call * @param i defines the facet index * @returns a new Vector3 * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData */ getFacetPosition(i) { const pos = Vector3.Zero(); this.getFacetPositionToRef(i, pos); return pos; } /** * Sets the reference Vector3 with the i-th facet position in the world system * @param i defines the facet index * @param ref defines the target vector * @returns the current mesh * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData */ getFacetPositionToRef(i, ref) { const localPos = this.getFacetLocalPositions()[i]; const world = this.getWorldMatrix(); Vector3.TransformCoordinatesToRef(localPos, world, ref); return this; } /** * Returns the i-th facet normal in the world system. * This method allocates a new Vector3 per call * @param i defines the facet index * @returns a new Vector3 * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData */ getFacetNormal(i) { const norm = Vector3.Zero(); this.getFacetNormalToRef(i, norm); return norm; } /** * Sets the reference Vector3 with the i-th facet normal in the world system * @param i defines the facet index * @param ref defines the target vector * @returns the current mesh * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData */ getFacetNormalToRef(i, ref) { const localNorm = this.getFacetLocalNormals()[i]; Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref); return this; } /** * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system) * @param x defines x coordinate * @param y defines y coordinate * @param z defines z coordinate * @returns the array of facet indexes * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData */ getFacetsAtLocalCoordinates(x, y, z) { const bInfo = this.getBoundingInfo(); const data = this._internalAbstractMeshDataInfo._facetData; const ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x); const oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y); const oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z); if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) { return null; } return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz]; } /** * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found * @param x defines x coordinate * @param y defines y coordinate * @param z defines z coordinate * @param projected sets as the (x,y,z) world projection on the facet * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position * @returns the face index if found (or null instead) * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData */ getClosestFacetAtCoordinates(x, y, z, projected, checkFace = false, facing = true) { const world = this.getWorldMatrix(); const invMat = TmpVectors.Matrix[5]; world.invertToRef(invMat); const invVect = TmpVectors.Vector3[8]; Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); const closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing); if (projected) { Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected); } return closest; } /** * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found * @param x defines x coordinate * @param y defines y coordinate * @param z defines z coordinate * @param projected sets as the (x,y,z) local projection on the facet * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position * @returns the face index if found (or null instead) * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData */ getClosestFacetAtLocalCoordinates(x, y, z, projected, checkFace = false, facing = true) { let closest = null; let tmpx = 0; let tmpy = 0; let tmpz = 0; let d = 0; let t0 = 0; let projx = 0; let projy = 0; let projz = 0; const facetPositions = this.getFacetLocalPositions(); const facetNormals = this.getFacetLocalNormals(); const facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z); if (!facetsInBlock) { return null; } let shortest = Number.MAX_VALUE; let tmpDistance = shortest; let fib; let norm; let p0; for (let idx = 0; idx < facetsInBlock.length; idx++) { fib = facetsInBlock[idx]; norm = facetNormals[fib]; p0 = facetPositions[fib]; d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z; if (!checkFace || checkFace && facing && d >= 0 || checkFace && !facing && d <= 0) { d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z; t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z); projx = x + norm.x * t0; projy = y + norm.y * t0; projz = z + norm.z * t0; tmpx = projx - x; tmpy = projy - y; tmpz = projz - z; tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; if (tmpDistance < shortest) { shortest = tmpDistance; closest = fib; if (projected) { projected.x = projx; projected.y = projy; projected.z = projz; } } } } return closest; } /** * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals() * @returns the parameters * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData */ getFacetDataParameters() { return this._internalAbstractMeshDataInfo._facetData.facetParameters; } /** * Disables the feature FacetData and frees the related memory * @returns the current mesh * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/facetData */ disableFacetData() { const facetData = this._internalAbstractMeshDataInfo._facetData; if (facetData.facetDataEnabled) { facetData.facetDataEnabled = false; facetData.facetPositions = []; facetData.facetNormals = []; facetData.facetPartitioning = new Array(); facetData.facetParameters = {}; facetData.depthSortedIndices = new Uint32Array(0); } return this; } /** * Updates the AbstractMesh indices array * @param indices defines the data source * @param offset defines the offset in the index buffer where to store the new data (can be null) * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default) * @returns the current mesh */ // eslint-disable-next-line @typescript-eslint/no-unused-vars updateIndices(indices, offset, gpuMemoryOnly = false) { return this; } /** * Creates new normals data for the mesh * @param updatable defines if the normal vertex buffer must be flagged as updatable * @returns the current mesh */ createNormals(updatable) { const positions = this.getVerticesData(VertexBuffer.PositionKind); const indices = this.getIndices(); let normals; if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) { normals = this.getVerticesData(VertexBuffer.NormalKind); } else { normals = []; } VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem }); this.setVerticesData(VertexBuffer.NormalKind, normals, updatable); return this; } /** * Optimize the indices order so that we keep the faces with similar indices together * @returns the current mesh */ async optimizeIndicesAsync() { const indices = this.getIndices(); if (!indices) { return this; } const { OptimizeIndices: OptimizeIndices2 } = await Promise.resolve().then(() => (init_mesh_vertexData_functions(), mesh_vertexData_functions_exports)); OptimizeIndices2(indices); this.setIndices(indices, this.getTotalVertices()); return this; } /** * Align the mesh with a normal * @param normal defines the normal to use * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default) * @returns the current mesh */ alignWithNormal(normal, upDirection) { if (!upDirection) { upDirection = Axis.Y; } const axisX = TmpVectors.Vector3[0]; const axisZ = TmpVectors.Vector3[1]; Vector3.CrossToRef(upDirection, normal, axisZ); Vector3.CrossToRef(normal, axisZ, axisX); if (this.rotationQuaternion) { Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion); } else { Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation); } return this; } /** @internal */ _checkOcclusionQuery() { return false; } // eslint-disable-next-line jsdoc/require-returns-check /** * Disables the mesh edge rendering mode * @returns the currentAbstractMesh */ disableEdgesRendering() { throw _WarnImport("EdgesRenderer"); } // eslint-disable-next-line jsdoc/require-returns-check /** * Enables the edge rendering mode on the mesh. * This mode makes the mesh edges visible * @param epsilon defines the maximal distance between two angles to detect a face * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces * @param options options to the edge renderer * @returns the currentAbstractMesh * @see https://www.babylonjs-playground.com/#19O9TU#0 */ // eslint-disable-next-line @typescript-eslint/no-unused-vars enableEdgesRendering(epsilon, checkVerticesInsteadOfIndices, options) { throw _WarnImport("EdgesRenderer"); } /** * This function returns all of the particle systems in the scene that use the mesh as an emitter. * @returns an array of particle systems in the scene that use the mesh as an emitter */ getConnectedParticleSystems() { return this._scene.particleSystems.filter((particleSystem) => particleSystem.emitter === this); } }; AbstractMesh.OCCLUSION_TYPE_NONE = 0; AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1; AbstractMesh.OCCLUSION_TYPE_STRICT = 2; AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0; AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1; AbstractMesh.CULLINGSTRATEGY_STANDARD = 0; AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1; AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2; AbstractMesh.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3; __decorate([ nativeOverride.filter((...[data, matricesIndicesData, matricesWeightsData, matricesIndicesExtraData, matricesWeightsExtraData]) => !Array.isArray(data) && !Array.isArray(matricesIndicesData) && !Array.isArray(matricesWeightsData) && !Array.isArray(matricesIndicesExtraData) && !Array.isArray(matricesWeightsExtraData)) ], AbstractMesh, "_ApplySkeleton", null); RegisterClass("BABYLON.AbstractMesh", AbstractMesh); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialStencilState.js init_tslib_es6(); init_decorators_serialization(); init_decorators(); var MaterialStencilState = class { static { __name(this, "MaterialStencilState"); } /** * Creates a material stencil state instance */ constructor() { this.reset(); } /** * Resets all the stencil states to default values */ reset() { this.enabled = false; this.mask = 255; this.funcRef = 1; this.funcMask = 255; this.func = 519; this.opStencilFail = 7680; this.opDepthFail = 7680; this.opStencilDepthPass = 7681; this.backFunc = 519; this.backOpStencilFail = 7680; this.backOpDepthFail = 7680; this.backOpStencilDepthPass = 7681; } /** * Gets or sets the stencil function */ get func() { return this._func; } set func(value) { this._func = value; } /** * Gets or sets the stencil back function */ get backFunc() { return this._backFunc; } set backFunc(value) { this._backFunc = value; } /** * Gets or sets the stencil function reference */ get funcRef() { return this._funcRef; } set funcRef(value) { this._funcRef = value; } /** * Gets or sets the stencil function mask */ get funcMask() { return this._funcMask; } set funcMask(value) { this._funcMask = value; } /** * Gets or sets the operation when the stencil test fails */ get opStencilFail() { return this._opStencilFail; } set opStencilFail(value) { this._opStencilFail = value; } /** * Gets or sets the operation when the depth test fails */ get opDepthFail() { return this._opDepthFail; } set opDepthFail(value) { this._opDepthFail = value; } /** * Gets or sets the operation when the stencil+depth test succeeds */ get opStencilDepthPass() { return this._opStencilDepthPass; } set opStencilDepthPass(value) { this._opStencilDepthPass = value; } /** * Gets or sets the operation when the back stencil test fails */ get backOpStencilFail() { return this._backOpStencilFail; } set backOpStencilFail(value) { this._backOpStencilFail = value; } /** * Gets or sets the operation when the back depth test fails */ get backOpDepthFail() { return this._backOpDepthFail; } set backOpDepthFail(value) { this._backOpDepthFail = value; } /** * Gets or sets the operation when the back stencil+depth test succeeds */ get backOpStencilDepthPass() { return this._backOpStencilDepthPass; } set backOpStencilDepthPass(value) { this._backOpStencilDepthPass = value; } /** * Gets or sets the stencil mask */ get mask() { return this._mask; } set mask(value) { this._mask = value; } /** * Enables or disables the stencil test */ get enabled() { return this._enabled; } set enabled(value) { this._enabled = value; } /** * Get the current class name, useful for serialization or dynamic coding. * @returns "MaterialStencilState" */ getClassName() { return "MaterialStencilState"; } /** * Makes a duplicate of the current configuration into another one. * @param stencilState defines stencil state where to copy the info */ copyTo(stencilState) { SerializationHelper.Clone(() => stencilState, this); } /** * Serializes this stencil configuration. * @returns - An object with the serialized config. */ serialize() { return SerializationHelper.Serialize(this); } /** * Parses a stencil state 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 */ parse(source, scene, rootUrl) { SerializationHelper.Parse(() => this, source, scene, rootUrl); } }; __decorate([ serialize() ], MaterialStencilState.prototype, "func", null); __decorate([ serialize() ], MaterialStencilState.prototype, "backFunc", null); __decorate([ serialize() ], MaterialStencilState.prototype, "funcRef", null); __decorate([ serialize() ], MaterialStencilState.prototype, "funcMask", null); __decorate([ serialize() ], MaterialStencilState.prototype, "opStencilFail", null); __decorate([ serialize() ], MaterialStencilState.prototype, "opDepthFail", null); __decorate([ serialize() ], MaterialStencilState.prototype, "opStencilDepthPass", null); __decorate([ serialize() ], MaterialStencilState.prototype, "backOpStencilFail", null); __decorate([ serialize() ], MaterialStencilState.prototype, "backOpDepthFail", null); __decorate([ serialize() ], MaterialStencilState.prototype, "backOpStencilDepthPass", null); __decorate([ serialize() ], MaterialStencilState.prototype, "mask", null); __decorate([ serialize() ], MaterialStencilState.prototype, "enabled", null); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/material.js init_tslib_es6(); init_decorators(); init_tools(); init_observable(); init_engineStore(); init_uniformBuffer(); init_logger(); init_math_plane(); init_drawWrapper(); init_materialHelper_functions(); init_decorators_serialization(); init_drawWrapper_functions(); var Material = class _Material { static { __name(this, "Material"); } /** * Tells the engine to draw geometry using vertex pulling instead of index drawing. This will automatically * set the vertex buffers as storage buffers and make them accessible to the vertex shader (WebGPU only). */ get useVertexPulling() { return this._useVertexPulling; } set useVertexPulling(value) { if (this._useVertexPulling === value) { return; } this._useVertexPulling = value; this.markAsDirty(_Material.MiscDirtyFlag); } /** @internal */ get _supportGlowLayer() { return false; } /** @internal */ set _glowModeEnabled(value) { } /** * Gets the shader language used in this material. */ get shaderLanguage() { return this._shaderLanguage; } /** * If the material can be rendered to several textures with MRT extension */ get canRenderToMRT() { return false; } /** * Sets the alpha value of the material */ set alpha(value) { if (this._alpha === value) { return; } const oldValue = this._alpha; this._alpha = value; if (oldValue === 1 || value === 1) { this.markAsDirty(_Material.MiscDirtyFlag + _Material.PrePassDirtyFlag); } } /** * Gets the alpha value of the material */ get alpha() { return this._alpha; } /** * Sets the culling state (true to enable culling, false to disable) */ set backFaceCulling(value) { if (this._backFaceCulling === value) { return; } this._backFaceCulling = value; this.markAsDirty(_Material.TextureDirtyFlag); } /** * Gets the culling state */ get backFaceCulling() { return this._backFaceCulling; } /** * Sets the type of faces that should be culled (true for back faces, false for front faces) */ set cullBackFaces(value) { if (this._cullBackFaces === value) { return; } this._cullBackFaces = value; this.markAsDirty(_Material.TextureDirtyFlag); } /** * Gets the type of faces that should be culled */ get cullBackFaces() { return this._cullBackFaces; } /** * Block the dirty-mechanism for this specific material * When set to false after being true the material will be marked as dirty. */ get blockDirtyMechanism() { return this._blockDirtyMechanism; } set blockDirtyMechanism(value) { if (this._blockDirtyMechanism === value) { return; } this._blockDirtyMechanism = value; if (!value) { this.markDirty(); } } /** * This allows you to modify the material without marking it as dirty after every change. * This function should be used if you need to make more than one dirty-enabling change to the material - adding a texture, setting a new fill mode and so on. * The callback will pass the material as an argument, so you can make your changes to it. * @param callback the callback to be executed that will update the material */ atomicMaterialsUpdate(callback) { this.blockDirtyMechanism = true; try { callback(this); } finally { this.blockDirtyMechanism = false; } } /** * Gets a boolean indicating that current material needs to register RTT */ get hasRenderTargetTextures() { this._eventInfo.hasRenderTargetTextures = false; this._callbackPluginEventHasRenderTargetTextures(this._eventInfo); return this._eventInfo.hasRenderTargetTextures; } /** * Called during a dispose event */ set onDispose(callback) { if (this._onDisposeObserver) { this.onDisposeObservable.remove(this._onDisposeObserver); } this._onDisposeObserver = this.onDisposeObservable.add(callback); } /** * An event triggered when the material is bound */ get onBindObservable() { if (!this._onBindObservable) { this._onBindObservable = new Observable(); } return this._onBindObservable; } /** * Called during a bind event */ set onBind(callback) { if (this._onBindObserver) { this.onBindObservable.remove(this._onBindObserver); } this._onBindObserver = this.onBindObservable.add(callback); } /** * An event triggered when the material is unbound */ get onUnBindObservable() { if (!this._onUnBindObservable) { this._onUnBindObservable = new Observable(); } return this._onUnBindObservable; } /** * An event triggered when the effect is (re)created */ get onEffectCreatedObservable() { if (!this._onEffectCreatedObservable) { this._onEffectCreatedObservable = new Observable(); } return this._onEffectCreatedObservable; } /** * Sets the value of the alpha mode. * * | Value | Type | Description | * | --- | --- | --- | * | 0 | ALPHA_DISABLE | | * | 1 | ALPHA_ADD | Defines that alpha blending is COLOR=SRC_ALPHA * SRC + DEST, ALPHA=DEST_ALPHA | * | 2 | ALPHA_COMBINE | Defines that alpha blending is COLOR=SRC_ALPHA * SRC + (1 - SRC_ALPHA) * DEST, ALPHA=SRC_ALPHA + DEST_ALPHA | * | 3 | ALPHA_SUBTRACT | Defines that alpha blending is COLOR=(1 - SRC) * DEST, ALPHA=SRC_ALPHA - DEST_ALPHA | * | 4 | ALPHA_MULTIPLY | Defines that alpha blending is COLOR=DEST * SRC, ALPHA=SRC_ALPHA + DEST_ALPHA | * | 5 | ALPHA_MAXIMIZED | Defines that alpha blending is COLOR=SRC_ALPHA * SRC + (1 - SRC) * DEST, ALPHA=SRC_ALPHA + DEST_ALPHA | * | 6 | ALPHA_ONEONE | Defines that alpha blending is COLOR=SRC + DEST, ALPHA=DEST_ALPHA | * | 7 | ALPHA_PREMULTIPLIED | Defines that alpha blending is COLOR=SRC + (1 - SRC_ALPHA) * DEST, ALPHA=SRC_ALPHA + DEST_ALPHA | * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | Defines that alpha blending is COLOR=SRC + (1 - SRC_ALPHA) * DEST, ALPHA=SRC_ALPHA + (1 - SRC_ALPHA) * DEST_ALPHA | * | 9 | ALPHA_INTERPOLATE | Defines that alpha blending is COLOR=CST * SRC + (1 - CST) * DEST, ALPHA=CST_ALPHA * SRC + (1 - CST_ALPHA) * DEST_ALPHA | * | 10 | ALPHA_SCREENMODE | Defines that alpha blending is COLOR=SRC + (1 - SRC) * DEST, ALPHA=SRC_ALPHA + (1 - SRC_ALPHA) * DEST_ALPHA | * | 11 | ALPHA_ONEONE_ONEONE | Defines that alpha blending is COLOR=SRC + DST, ALPHA=SRC_ALPHA + DEST_ALPHA | * | 12 | ALPHA_ALPHATOCOLOR | Defines that alpha blending is COLOR=DEST_ALPHA * SRC + DST, ALPHA=0 | * | 13 | ALPHA_REVERSEONEMINUS | Defines that alpha blending is COLOR=(1 - DEST) * SRC + (1 - SRC) * DEST, ALPHA=(1 - DEST_ALPHA) * SRC_ALPHA + (1 - SRC_ALPHA) * DEST_ALPHA | * | 14 | ALPHA_SRC_DSTONEMINUSSRCALPHA | Defines that alpha blending is ALPHA=SRC + (1 - SRC ALPHA) * DEST, ALPHA=SRC_ALPHA + (1 - SRC ALPHA) * DEST_ALPHA | * | 15 | ALPHA_ONEONE_ONEZERO | Defines that alpha blending is COLOR=SRC + DST, ALPHA=SRC_ALPHA | * | 16 | ALPHA_EXCLUSION | Defines that alpha blending is COLOR=(1 - DEST) * SRC + (1 - SRC) * DEST, ALPHA=DEST_ALPHA | * | 17 | ALPHA_LAYER_ACCUMULATE | Defines that alpha blending is COLOR=SRC_ALPHA * SRC + (1 - SRC ALPHA) * DEST, ALPHA=SRC_ALPHA + (1 - SRC_ALPHA) * DEST_ALPHA | * | 18 | ALPHA_MIN | Defines that alpha blending is COLOR=MIN(SRC, DEST), ALPHA=MIN(SRC_ALPHA, DEST_ALPHA) | * | 19 | ALPHA_MAX | Defines that alpha blending is COLOR=MAX(SRC, DEST), ALPHA=MAX(SRC_ALPHA, DEST_ALPHA) | * | 20 | ALPHA_DUAL_SRC0_ADD_SRC1xDST | Defines that alpha blending uses dual source blending and is COLOR=SRC + SRC1 * DEST, ALPHA=DST_ALPHA | * */ set alphaMode(value) { if (this._alphaMode[0] === value) { return; } this._alphaMode[0] = value; this.markAsDirty(_Material.TextureDirtyFlag); } /** * Gets the value of the alpha mode */ get alphaMode() { return this._alphaMode[0]; } /** * Gets the list of alpha modes (length greater than 1 for multi-targets) */ get alphaModes() { return this._alphaMode; } /** * Sets the value of the alpha mode for a specific target index. * @param value The alpha mode value to set. * @param targetIndex The index of the target to set the alpha mode for. Defaults to 0. */ setAlphaMode(value, targetIndex = 0) { if (this._alphaMode[targetIndex] === value) { return; } this._alphaMode[targetIndex] = value; this.markAsDirty(_Material.TextureDirtyFlag); } /** * Sets the need depth pre-pass value */ set needDepthPrePass(value) { if (this._needDepthPrePass === value) { return; } this._needDepthPrePass = value; if (this._needDepthPrePass) { this.checkReadyOnEveryCall = true; } } /** * Gets the depth pre-pass value */ get needDepthPrePass() { return this._needDepthPrePass; } /** * Can this material render to prepass */ get isPrePassCapable() { return false; } /** * Sets the state for enabling fog */ set fogEnabled(value) { if (this._fogEnabled === value) { return; } this._fogEnabled = value; this.markAsDirty(_Material.MiscDirtyFlag); } /** * Gets the value of the fog enabled state */ get fogEnabled() { return this._fogEnabled; } get wireframe() { switch (this._fillMode) { case _Material.WireFrameFillMode: case _Material.LineListDrawMode: case _Material.LineLoopDrawMode: case _Material.LineStripDrawMode: return true; } return this._scene.forceWireframe; } /** * Sets the state of wireframe mode */ set wireframe(value) { this.fillMode = value ? _Material.WireFrameFillMode : _Material.TriangleFillMode; } /** * Gets the value specifying if point clouds are enabled */ get pointsCloud() { switch (this._fillMode) { case _Material.PointFillMode: case _Material.PointListDrawMode: return true; } return this._scene.forcePointsCloud; } /** * Sets the state of point cloud mode */ set pointsCloud(value) { this.fillMode = value ? _Material.PointFillMode : _Material.TriangleFillMode; } /** * Gets the material fill mode */ get fillMode() { return this._fillMode; } /** * Sets the material fill mode */ set fillMode(value) { if (this._fillMode === value) { return; } this._fillMode = value; this.markAsDirty(_Material.MiscDirtyFlag); } /** * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes) * You can try switching to logarithmic depth. * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/logarithmicDepthBuffer */ get useLogarithmicDepth() { return this._useLogarithmicDepth; } set useLogarithmicDepth(value) { const fragmentDepthSupported = this.getScene().getEngine().getCaps().fragmentDepthSupported; if (value && !fragmentDepthSupported) { Logger.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."); } this._useLogarithmicDepth = value && fragmentDepthSupported; this._markAllSubMeshesAsMiscDirty(); } /** * Gets or sets the vertex output invariant state * Setting this property to true will force the shader compiler to disable some optimization to make sure the vertex output is always calculated * the same way across different compilation units. * You may need to enable this option if you are seeing some depth artifacts when using a depth pre-pass, for e.g. * Note that this may have an impact on performance, so leave this option disabled if not needed. */ get isVertexOutputInvariant() { return this._isVertexOutputInvariant; } set isVertexOutputInvariant(value) { if (this._isVertexOutputInvariant === value) { return; } this._isVertexOutputInvariant = value; this._markAllSubMeshesAsMiscDirty(); } /** @internal */ _getDrawWrapper() { return this._drawWrapper; } /** * @internal */ _setDrawWrapper(drawWrapper) { this._drawWrapper = drawWrapper; } /** * Creates a material instance * @param name defines the name of the material * @param scene defines the scene to reference * @param doNotAdd specifies if the material should be added to the scene * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false */ constructor(name260, scene, doNotAdd, forceGLSL = false) { this.shadowDepthWrapper = null; this.allowShaderHotSwapping = true; this._shaderLanguage = 0; this._forceGLSL = false; this._useVertexPulling = false; this.metadata = null; this.reservedDataStore = null; this.checkReadyOnEveryCall = false; this.checkReadyOnlyOnce = false; this.state = ""; this._alpha = 1; this._backFaceCulling = true; this._cullBackFaces = true; this._blockDirtyMechanism = false; this.sideOrientation = null; this.onCompiled = null; this.onError = null; this.getRenderTargetTextures = null; this.doNotSerialize = false; this._storeEffectOnSubMeshes = false; this.animations = null; this.onDisposeObservable = new Observable(); this._onDisposeObserver = null; this._onUnBindObservable = null; this._onBindObserver = null; this._alphaMode = [2]; this._needDepthPrePass = false; this.disableDepthWrite = false; this.disableColorWrite = false; this.forceDepthWrite = false; this.depthFunction = 0; this.separateCullingPass = false; this._fogEnabled = true; this.pointSize = 1; this.zOffset = 0; this.zOffsetUnits = 0; this.stencil = new MaterialStencilState(); this._isVertexOutputInvariant = _Material.ForceVertexOutputInvariant; this._useUBO = false; this._fillMode = _Material.TriangleFillMode; this._cachedDepthWriteState = false; this._cachedColorWriteState = false; this._cachedDepthFunctionState = 0; this._indexInSceneMaterialArray = -1; this.meshMap = null; this._parentContainer = null; this._uniformBufferLayoutBuilt = false; this._eventInfo = {}; this._callbackPluginEventGeneric = () => void 0; this._callbackPluginEventIsReadyForSubMesh = () => void 0; this._callbackPluginEventPrepareDefines = () => void 0; this._callbackPluginEventPrepareDefinesBeforeAttributes = () => void 0; this._callbackPluginEventHardBindForSubMesh = () => void 0; this._callbackPluginEventBindForSubMesh = () => void 0; this._callbackPluginEventHasRenderTargetTextures = () => void 0; this._callbackPluginEventFillRenderTargetTextures = () => void 0; this._transparencyMode = null; this.name = name260; const setScene = scene || EngineStore.LastCreatedScene; if (!setScene) { return; } this._scene = setScene; this._dirtyCallbacks = {}; this._forceGLSL = forceGLSL; this._dirtyCallbacks[1] = this._markAllSubMeshesAsTexturesDirty.bind(this); this._dirtyCallbacks[2] = this._markAllSubMeshesAsLightsDirty.bind(this); this._dirtyCallbacks[4] = this._markAllSubMeshesAsFresnelDirty.bind(this); this._dirtyCallbacks[8] = this._markAllSubMeshesAsAttributesDirty.bind(this); this._dirtyCallbacks[16] = this._markAllSubMeshesAsMiscDirty.bind(this); this._dirtyCallbacks[32] = this._markAllSubMeshesAsPrePassDirty.bind(this); this._dirtyCallbacks[127] = this._markAllSubMeshesAsAllDirty.bind(this); this.id = name260 || Tools.RandomId(); this.uniqueId = this._scene.getUniqueId(); this._materialContext = this._scene.getEngine().createMaterialContext(); this._drawWrapper = new DrawWrapper(this._scene.getEngine(), false); this._drawWrapper.materialContext = this._materialContext; this._uniformBuffer = new UniformBuffer(this._scene.getEngine(), void 0, void 0, name260); this._useUBO = this.getScene().getEngine().supportsUniformBuffers; this._createUniformBuffer(); if (!doNotAdd) { this._scene.addMaterial(this); } if (this._scene.useMaterialMeshMap) { this.meshMap = {}; } _Material.OnEventObservable.notifyObservers( this, 1 /* MaterialPluginEvent.Created */ ); } /** @internal */ _createUniformBuffer() { const engine = this.getScene().getEngine(); this._uniformBuffer?.dispose(); if (engine.isWebGPU && !this._forceGLSL) { this._uniformBuffer = new UniformBuffer(engine, void 0, void 0, this.name, true); this._shaderLanguage = 1; } else { this._uniformBuffer = new UniformBuffer(this._scene.getEngine(), void 0, void 0, this.name); } this._uniformBufferLayoutBuilt = false; } /** * Returns a string representation of the current material * @param fullDetails defines a boolean indicating which levels of logging is desired * @returns a string with material information */ // eslint-disable-next-line @typescript-eslint/no-unused-vars toString(fullDetails) { const ret = "Name: " + this.name; return ret; } /** * Gets the class name of the material * @returns a string with the class name of the material */ getClassName() { return "Material"; } /** @internal */ get _isMaterial() { return true; } /** * Specifies if updates for the material been locked */ get isFrozen() { return this.checkReadyOnlyOnce; } /** * Locks updates for the material */ freeze() { this.markDirty(); this.checkReadyOnlyOnce = true; } /** * Unlocks updates for the material */ unfreeze() { this.markDirty(); this.checkReadyOnlyOnce = false; } /** * Specifies if the material is ready to be used * @param mesh defines the mesh to check * @param useInstances specifies if instances should be used * @returns a boolean indicating if the material is ready to be used */ // eslint-disable-next-line @typescript-eslint/no-unused-vars isReady(mesh, useInstances) { return true; } /** * Specifies that the submesh is ready to be used * @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 */ // eslint-disable-next-line @typescript-eslint/no-unused-vars isReadyForSubMesh(mesh, subMesh, useInstances) { const defines = subMesh.materialDefines; if (!defines) { return false; } this._eventInfo.isReadyForSubMesh = true; this._eventInfo.defines = defines; this._callbackPluginEventIsReadyForSubMesh(this._eventInfo); return this._eventInfo.isReadyForSubMesh; } /** * Returns the material effect * @returns the effect associated with the material */ getEffect() { return this._drawWrapper.effect; } /** * Returns the current scene * @returns a Scene */ getScene() { return this._scene; } /** @internal */ _getEffectiveOrientation(mesh) { return this.sideOrientation !== null ? this.sideOrientation : mesh.sideOrientation; } /** * Gets the current transparency mode. */ get transparencyMode() { return this._transparencyMode; } /** * Sets the transparency mode of the material. * * | Value | Type | Description | * | ----- | ----------------------------------- | ----------- | * | 0 | OPAQUE | | * | 1 | ALPHATEST | | * | 2 | ALPHABLEND | | * | 3 | ALPHATESTANDBLEND | | * */ set transparencyMode(value) { if (this._transparencyMode === value) { return; } this._transparencyMode = value; this._markAllSubMeshesAsTexturesAndMiscDirty(); } get _hasTransparencyMode() { return this._transparencyMode != null; } get _transparencyModeIsBlend() { return this._transparencyMode === _Material.MATERIAL_ALPHABLEND || this._transparencyMode === _Material.MATERIAL_ALPHATESTANDBLEND; } get _transparencyModeIsTest() { return this._transparencyMode === _Material.MATERIAL_ALPHATEST || this._transparencyMode === _Material.MATERIAL_ALPHATESTANDBLEND; } /** * Returns true if alpha blending should be disabled. */ get _disableAlphaBlending() { return this._transparencyMode === _Material.MATERIAL_OPAQUE || this._transparencyMode === _Material.MATERIAL_ALPHATEST; } /** * Specifies whether or not this material should be rendered in alpha blend mode. * @returns a boolean specifying if alpha blending is needed * @deprecated Please use needAlphaBlendingForMesh instead */ needAlphaBlending() { if (this._hasTransparencyMode) { return this._transparencyModeIsBlend; } if (this._disableAlphaBlending) { return false; } return this.alpha < 1; } /** * Specifies if the mesh will require alpha blending * @param mesh defines the mesh to check * @returns a boolean specifying if alpha blending is needed for the mesh */ needAlphaBlendingForMesh(mesh) { if (this._hasTransparencyMode) { return this._transparencyModeIsBlend; } if (mesh.visibility < 1) { return true; } if (this._disableAlphaBlending) { return false; } return mesh.hasVertexAlpha || this.needAlphaBlending(); } /** * Specifies whether or not this material should be rendered in alpha test mode. * @returns a boolean specifying if an alpha test is needed. * @deprecated Please use needAlphaTestingForMesh instead */ needAlphaTesting() { if (this._hasTransparencyMode) { return this._transparencyModeIsTest; } return false; } /** * Specifies if material alpha testing should be turned on for the mesh * @param mesh defines the mesh to check * @returns a boolean specifying if alpha testing should be turned on for the mesh */ needAlphaTestingForMesh(mesh) { if (this._hasTransparencyMode) { return this._transparencyModeIsTest; } return !this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting(); } /** * Gets the texture used for the alpha test * @returns the texture to use for alpha testing */ getAlphaTestTexture() { return null; } /** * Marks the material to indicate that it needs to be re-calculated * @param forceMaterialDirty - Forces the material to be marked as dirty for all components (same as this.markAsDirty(Material.AllDirtyFlag)). You should use this flag if the material is frozen and you want to force a recompilation. */ markDirty(forceMaterialDirty = false) { const meshes = this.getScene().meshes; for (const mesh of meshes) { if (!mesh.subMeshes) { continue; } for (const subMesh of mesh.subMeshes) { if (subMesh.getMaterial() !== this) { continue; } for (const drawWrapper of subMesh._drawWrappers) { if (!drawWrapper) { continue; } if (this._materialContext === drawWrapper.materialContext) { drawWrapper._wasPreviouslyReady = false; drawWrapper._wasPreviouslyUsingInstances = null; drawWrapper._forceRebindOnNextCall = forceMaterialDirty; } } } } if (forceMaterialDirty) { this.markAsDirty(_Material.AllDirtyFlag); } } /** * @internal */ _preBind(effect, overrideOrientation = null) { const engine = this._scene.getEngine(); const orientation = overrideOrientation == null ? this.sideOrientation : overrideOrientation; const reverse = orientation === _Material.ClockWiseSideOrientation; const effectiveDrawWrapper = effect ? effect : this._getDrawWrapper(); if (IsWrapper(effectiveDrawWrapper) && effectiveDrawWrapper.materialContext) { effectiveDrawWrapper.materialContext.useVertexPulling = this.useVertexPulling; } engine.enableEffect(effectiveDrawWrapper); engine.setState(this.backFaceCulling, this.zOffset, false, reverse, this._scene._mirroredCameraPosition ? !this.cullBackFaces : this.cullBackFaces, this.stencil, this.zOffsetUnits); return reverse; } /** * Binds the material to the mesh * @param world defines the world transformation matrix * @param mesh defines the mesh to bind the material to */ // eslint-disable-next-line @typescript-eslint/no-unused-vars bind(world, mesh) { } /** * Initializes the uniform buffer layout for the shader. */ buildUniformLayout() { const ubo = this._uniformBuffer; this._eventInfo.ubo = ubo; this._callbackPluginEventGeneric(8, this._eventInfo); ubo.create(); this._uniformBufferLayoutBuilt = true; } /** * Binds the submesh to the material * @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 */ bindForSubMesh(world, mesh, subMesh) { const drawWrapper = subMesh._drawWrapper; this._eventInfo.subMesh = subMesh; this._callbackPluginEventBindForSubMesh(this._eventInfo); drawWrapper._forceRebindOnNextCall = false; } /** * Binds the world matrix to the material * @param world defines the world transformation matrix */ // eslint-disable-next-line @typescript-eslint/no-unused-vars bindOnlyWorldMatrix(world) { } /** * Binds the view matrix to the effect * @param effect defines the effect to bind the view matrix to */ bindView(effect) { if (!this._useUBO) { effect.setMatrix("view", this.getScene().getViewMatrix()); } else { this._needToBindSceneUbo = true; } } /** * Binds the view projection and projection matrices to the effect * @param effect defines the effect to bind the view projection and projection matrices to */ bindViewProjection(effect) { if (!this._useUBO) { effect.setMatrix("viewProjection", this.getScene().getTransformMatrix()); effect.setMatrix("projection", this.getScene().getProjectionMatrix()); } else { this._needToBindSceneUbo = true; } } /** * Binds the view matrix to the effect * @param effect defines the effect to bind the view matrix to * @param variableName name of the shader variable that will hold the eye position */ bindEyePosition(effect, variableName) { if (!this._useUBO) { this._scene.bindEyePosition(effect, variableName); } else { this._needToBindSceneUbo = true; } } /** * Processes to execute after binding the material to a mesh * @param mesh defines the rendered mesh * @param effect defines the effect used to bind the material * @param _subMesh defines the subMesh that the material has been bound for */ _afterBind(mesh, effect = null, _subMesh) { this._scene._cachedMaterial = this; if (this._needToBindSceneUbo) { if (effect) { this._needToBindSceneUbo = false; BindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer()); this._scene.finalizeSceneUbo(); } } if (mesh) { this._scene._cachedVisibility = mesh.visibility; } else { this._scene._cachedVisibility = 1; } if (this._onBindObservable && mesh) { this._onBindObservable.notifyObservers(mesh); } if (this.disableDepthWrite) { const engine = this._scene.getEngine(); this._cachedDepthWriteState = engine.getDepthWrite(); engine.setDepthWrite(false); } if (this.disableColorWrite) { const engine = this._scene.getEngine(); this._cachedColorWriteState = engine.getColorWrite(); engine.setColorWrite(false); } if (this.depthFunction !== 0) { const engine = this._scene.getEngine(); this._cachedDepthFunctionState = engine.getDepthFunction() || 0; engine.setDepthFunction(this.depthFunction); } } /** * Unbinds the material from the mesh */ unbind() { this._scene.getSceneUniformBuffer().unbindEffect(); if (this._onUnBindObservable) { this._onUnBindObservable.notifyObservers(this); } if (this.depthFunction !== 0) { const engine = this._scene.getEngine(); engine.setDepthFunction(this._cachedDepthFunctionState); } if (this.disableDepthWrite) { const engine = this._scene.getEngine(); engine.setDepthWrite(this._cachedDepthWriteState); } if (this.disableColorWrite) { const engine = this._scene.getEngine(); engine.setColorWrite(this._cachedColorWriteState); } } /** * Returns the animatable textures. * @returns - Array of animatable textures. */ getAnimatables() { this._eventInfo.animatables = []; this._callbackPluginEventGeneric(256, this._eventInfo); return this._eventInfo.animatables; } /** * Gets the active textures from the material * @returns an array of textures */ getActiveTextures() { this._eventInfo.activeTextures = []; this._callbackPluginEventGeneric(512, this._eventInfo); return this._eventInfo.activeTextures; } /** * 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 */ hasTexture(texture) { this._eventInfo.hasTexture = false; this._eventInfo.texture = texture; this._callbackPluginEventGeneric(1024, this._eventInfo); return this._eventInfo.hasTexture; } /** * Makes a duplicate of the material, and gives it a new name * @param name defines the new name for the duplicated material * @returns the cloned material */ // eslint-disable-next-line @typescript-eslint/no-unused-vars clone(name260) { return null; } _clonePlugins(targetMaterial, rootUrl) { const serializationObject = {}; this._serializePlugins(serializationObject); _Material._ParsePlugins(serializationObject, targetMaterial, this._scene, rootUrl); if (this.pluginManager) { for (const plugin of this.pluginManager._plugins) { const targetPlugin = targetMaterial.pluginManager.getPlugin(plugin.name); if (targetPlugin) { plugin.copyTo(targetPlugin); } } } } /** * Gets the meshes bound to the material * @returns an array of meshes bound to the material */ getBindedMeshes() { if (this.meshMap) { const result = []; for (const meshId in this.meshMap) { const mesh = this.meshMap[meshId]; if (mesh) { result.push(mesh); } } return result; } else { const meshes = this._scene.meshes; return meshes.filter((mesh) => mesh.material === this); } } /** * Force shader compilation * @param mesh defines the mesh associated with this material * @param onCompiled defines a function to execute once the material is compiled * @param options defines the options to configure the compilation * @param onError defines a function to execute if the material fails compiling */ forceCompilation(mesh, onCompiled, options, onError) { const localOptions = { clipPlane: false, useInstances: false, ...options }; const scene = this.getScene(); const currentHotSwapingState = this.allowShaderHotSwapping; this.allowShaderHotSwapping = false; const checkReady = /* @__PURE__ */ __name(() => { if (!this._scene || !this._scene.getEngine()) { return; } const clipPlaneState = scene.clipPlane; if (localOptions.clipPlane) { scene.clipPlane = new Plane(0, 0, 0, 1); } if (this._storeEffectOnSubMeshes) { let allDone = true, lastError = null; if (mesh.subMeshes) { const tempSubMesh = new SubMesh(0, 0, 0, 0, 0, mesh, void 0, false, false); if (tempSubMesh.materialDefines) { tempSubMesh.materialDefines._renderId = -1; } if (!this.isReadyForSubMesh(mesh, tempSubMesh, localOptions.useInstances)) { if (tempSubMesh.effect && tempSubMesh.effect.getCompilationError() && tempSubMesh.effect.allFallbacksProcessed()) { lastError = tempSubMesh.effect.getCompilationError(); } else { allDone = false; setTimeout(checkReady, 16); } } } if (allDone) { this.allowShaderHotSwapping = currentHotSwapingState; if (lastError) { if (onError) { onError(lastError); } } if (onCompiled) { onCompiled(this); } } } else { if (this.isReady()) { this.allowShaderHotSwapping = currentHotSwapingState; if (onCompiled) { onCompiled(this); } } else { setTimeout(checkReady, 16); } } if (localOptions.clipPlane) { scene.clipPlane = clipPlaneState; } }, "checkReady"); checkReady(); } /** * Force shader compilation * @param mesh defines the mesh that will use this material * @param options defines additional options for compiling the shaders * @returns a promise that resolves when the compilation completes */ async forceCompilationAsync(mesh, options) { return await new Promise((resolve, reject) => { this.forceCompilation(mesh, () => { resolve(); }, options, (reason) => { reject(reason); }); }); } /** * Marks a define in the material to indicate that it needs to be re-computed * @param flag defines a flag used to determine which parts of the material have to be marked as dirty */ markAsDirty(flag) { if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) { return; } _Material._DirtyCallbackArray.length = 0; if (flag & _Material.ImageProcessingDirtyFlag) { _Material._DirtyCallbackArray.push(_Material._ImageProcessingDirtyCallBack); } if (flag & _Material.TextureDirtyFlag) { _Material._DirtyCallbackArray.push(_Material._TextureDirtyCallBack); } if (flag & _Material.LightDirtyFlag) { _Material._DirtyCallbackArray.push(_Material._LightsDirtyCallBack); } if (flag & _Material.FresnelDirtyFlag) { _Material._DirtyCallbackArray.push(_Material._FresnelDirtyCallBack); } if (flag & _Material.AttributesDirtyFlag) { _Material._DirtyCallbackArray.push(_Material._AttributeDirtyCallBack); } if (flag & _Material.MiscDirtyFlag) { _Material._DirtyCallbackArray.push(_Material._MiscDirtyCallBack); } if (flag & _Material.PrePassDirtyFlag) { _Material._DirtyCallbackArray.push(_Material._PrePassDirtyCallBack); } if (_Material._DirtyCallbackArray.length) { this._markAllSubMeshesAsDirty(_Material._RunDirtyCallBacks); } this.getScene().resetCachedMaterial(); } /** * Resets the draw wrappers cache for all submeshes that are using this material */ resetDrawCache() { const meshes = this.getScene().meshes; for (const mesh of meshes) { if (!mesh.subMeshes) { continue; } for (const subMesh of mesh.subMeshes) { if (subMesh.getMaterial() !== this) { continue; } subMesh.resetDrawCache(); } } } /** * Marks all submeshes of a material to indicate that their material defines need to be re-calculated * @param func defines a function which checks material defines against the submeshes */ _markAllSubMeshesAsDirty(func) { const scene = this.getScene(); if (scene.blockMaterialDirtyMechanism || this._blockDirtyMechanism) { return; } const meshes = scene.meshes; for (const mesh of meshes) { if (!mesh.subMeshes) { continue; } for (const subMesh of mesh.subMeshes) { const material = subMesh.getMaterial() || (scene._hasDefaultMaterial ? scene.defaultMaterial : null); if (material !== this) { continue; } for (const drawWrapper of subMesh._drawWrappers) { if (!drawWrapper || !drawWrapper.defines || !drawWrapper.defines.markAllAsDirty) { continue; } if (this._materialContext === drawWrapper.materialContext) { func(drawWrapper.defines); } } } } } /** * Indicates that the scene should check if the rendering now needs a prepass */ _markScenePrePassDirty() { if (this.getScene().blockMaterialDirtyMechanism || this._blockDirtyMechanism) { return; } const prePassRenderer = this.getScene().enablePrePassRenderer(); if (prePassRenderer) { prePassRenderer.markAsDirty(); } } /** * Indicates that we need to re-calculated for all submeshes */ _markAllSubMeshesAsAllDirty() { this._markAllSubMeshesAsDirty(_Material._AllDirtyCallBack); } /** * Indicates that image processing needs to be re-calculated for all submeshes */ _markAllSubMeshesAsImageProcessingDirty() { this._markAllSubMeshesAsDirty(_Material._ImageProcessingDirtyCallBack); } /** * Indicates that textures need to be re-calculated for all submeshes */ _markAllSubMeshesAsTexturesDirty() { this._markAllSubMeshesAsDirty(_Material._TextureDirtyCallBack); } /** * Indicates that fresnel needs to be re-calculated for all submeshes */ _markAllSubMeshesAsFresnelDirty() { this._markAllSubMeshesAsDirty(_Material._FresnelDirtyCallBack); } /** * Indicates that fresnel and misc need to be re-calculated for all submeshes */ _markAllSubMeshesAsFresnelAndMiscDirty() { this._markAllSubMeshesAsDirty(_Material._FresnelAndMiscDirtyCallBack); } /** * Indicates that lights need to be re-calculated for all submeshes */ _markAllSubMeshesAsLightsDirty() { this._markAllSubMeshesAsDirty(_Material._LightsDirtyCallBack); } /** * Indicates that attributes need to be re-calculated for all submeshes */ _markAllSubMeshesAsAttributesDirty() { this._markAllSubMeshesAsDirty(_Material._AttributeDirtyCallBack); } /** * Indicates that misc needs to be re-calculated for all submeshes */ _markAllSubMeshesAsMiscDirty() { this._markAllSubMeshesAsDirty(_Material._MiscDirtyCallBack); } /** * Indicates that prepass needs to be re-calculated for all submeshes */ _markAllSubMeshesAsPrePassDirty() { this._markAllSubMeshesAsDirty(_Material._PrePassDirtyCallBack); } /** * Indicates that textures and misc need to be re-calculated for all submeshes */ _markAllSubMeshesAsTexturesAndMiscDirty() { this._markAllSubMeshesAsDirty(_Material._TextureAndMiscDirtyCallBack); } _checkScenePerformancePriority() { if (this._scene.performancePriority !== 0) { this.checkReadyOnlyOnce = true; const observer = this._scene.onScenePerformancePriorityChangedObservable.addOnce(() => { this.checkReadyOnlyOnce = false; }); this.onDisposeObservable.add(() => { this._scene.onScenePerformancePriorityChangedObservable.remove(observer); }); } } /** * Sets the required values to the prepass renderer. * @param prePassRenderer defines the prepass renderer to setup. * @returns true if the pre pass is needed. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars setPrePassRenderer(prePassRenderer) { return false; } /** * Disposes the material * @param _forceDisposeEffect kept for backward compat. We reference count the effect now. * @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 */ dispose(_forceDisposeEffect, forceDisposeTextures, notBoundToMesh) { const scene = this.getScene(); scene.stopAnimation(this); scene.freeProcessedMaterials(); scene.removeMaterial(this); this._eventInfo.forceDisposeTextures = forceDisposeTextures; this._callbackPluginEventGeneric(2, this._eventInfo); if (this._parentContainer) { const index = this._parentContainer.materials.indexOf(this); if (index > -1) { this._parentContainer.materials.splice(index, 1); } this._parentContainer = null; } if (notBoundToMesh !== true) { if (this.meshMap) { for (const meshId in this.meshMap) { const mesh = this.meshMap[meshId]; this._disposeMeshResources(mesh); } } else { const meshes = scene.meshes; for (const mesh of meshes) { this._disposeMeshResources(mesh); } } } this._uniformBuffer.dispose(); if (this._drawWrapper.effect) { if (!this._storeEffectOnSubMeshes) { this._drawWrapper.effect.dispose(); } this._drawWrapper.effect = null; } this.metadata = null; this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); if (this._onBindObservable) { this._onBindObservable.clear(); } if (this._onUnBindObservable) { this._onUnBindObservable.clear(); } if (this._onEffectCreatedObservable) { this._onEffectCreatedObservable.clear(); } if (this._eventInfo) { this._eventInfo = {}; } } _disposeMeshResources(mesh) { if (!mesh) { return; } const geometry = mesh.geometry; const materialForRenderPass = mesh._internalAbstractMeshDataInfo._materialForRenderPass; if (this._storeEffectOnSubMeshes) { if (mesh.subMeshes && materialForRenderPass) { for (const subMesh of mesh.subMeshes) { const drawWrappers = subMesh._drawWrappers; for (let renderPassIndex = 0; renderPassIndex < drawWrappers.length; renderPassIndex++) { const effect = drawWrappers[renderPassIndex]?.effect; if (!effect) { continue; } const material = materialForRenderPass[renderPassIndex]; if (material === this) { geometry?._releaseVertexArrayObject(effect); subMesh._removeDrawWrapper(renderPassIndex, true, true); } } } } } else { geometry?._releaseVertexArrayObject(this._drawWrapper.effect); } if (mesh.material === this && !mesh.sourceMesh) { mesh.material = null; } } /** * Serializes this material * @returns the serialized material object */ serialize() { const serializationObject = SerializationHelper.Serialize(this); serializationObject.stencil = this.stencil.serialize(); serializationObject.uniqueId = this.uniqueId; this._serializePlugins(serializationObject); return serializationObject; } _serializePlugins(serializationObject) { serializationObject.plugins = {}; if (this.pluginManager) { for (const plugin of this.pluginManager._plugins) { if (!plugin.doNotSerialize) { serializationObject.plugins[plugin.getClassName()] = plugin.serialize(); } } } } /** * Parses the alpha mode from the material data to parse * @param parsedMaterial defines the material data to parse * @param material defines the material to update */ static ParseAlphaMode(parsedMaterial, material) { if (parsedMaterial._alphaMode !== void 0) { material._alphaMode = Array.isArray(parsedMaterial._alphaMode) ? parsedMaterial._alphaMode : [parsedMaterial._alphaMode]; } else if (parsedMaterial.alphaMode !== void 0) { material._alphaMode = Array.isArray(parsedMaterial.alphaMode) ? parsedMaterial.alphaMode : [parsedMaterial.alphaMode]; } else { material._alphaMode = [2]; } } /** * Creates a material from parsed material data * @param parsedMaterial defines parsed material data * @param scene defines the hosting scene * @param rootUrl defines the root URL to use to load textures * @returns a new material */ static Parse(parsedMaterial, scene, rootUrl) { if (!parsedMaterial.customType) { parsedMaterial.customType = "BABYLON.StandardMaterial"; } else if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) { parsedMaterial.customType = "BABYLON.LegacyPBRMaterial"; if (!BABYLON.LegacyPBRMaterial) { Logger.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."); return null; } } const materialType = Tools.Instantiate(parsedMaterial.customType); const material = materialType.Parse(parsedMaterial, scene, rootUrl); material._loadedUniqueId = parsedMaterial.uniqueId; _Material.ParseAlphaMode(parsedMaterial, material); return material; } static _ParsePlugins(serializationObject, material, scene, rootUrl) { if (!serializationObject.plugins) { return; } for (const pluginClassName in serializationObject.plugins) { const pluginData = serializationObject.plugins[pluginClassName]; let plugin = material.pluginManager?.getPlugin(pluginData.name); if (!plugin) { const pluginClassType = Tools.Instantiate("BABYLON." + pluginClassName); if (pluginClassType) { plugin = new pluginClassType(material); } } plugin?.parse(pluginData, scene, rootUrl); } } }; Material.TriangleFillMode = 0; Material.WireFrameFillMode = 1; Material.PointFillMode = 2; Material.PointListDrawMode = 3; Material.LineListDrawMode = 4; Material.LineLoopDrawMode = 5; Material.LineStripDrawMode = 6; Material.TriangleStripDrawMode = 7; Material.TriangleFanDrawMode = 8; Material.ClockWiseSideOrientation = 0; Material.CounterClockWiseSideOrientation = 1; Material.ImageProcessingDirtyFlag = 64; Material.TextureDirtyFlag = 1; Material.LightDirtyFlag = 2; Material.FresnelDirtyFlag = 4; Material.AttributesDirtyFlag = 8; Material.MiscDirtyFlag = 16; Material.PrePassDirtyFlag = 32; Material.AllDirtyFlag = 127; Material.MATERIAL_OPAQUE = 0; Material.MATERIAL_ALPHATEST = 1; Material.MATERIAL_ALPHABLEND = 2; Material.MATERIAL_ALPHATESTANDBLEND = 3; Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT = 0; Material.MATERIAL_NORMALBLENDMETHOD_RNM = 1; Material.LIGHTFALLOFF_PHYSICAL = 0; Material.LIGHTFALLOFF_GLTF = 1; Material.LIGHTFALLOFF_STANDARD = 2; Material.OnEventObservable = new Observable(); Material.ForceVertexOutputInvariant = false; Material._AllDirtyCallBack = (defines) => defines.markAllAsDirty(); Material._ImageProcessingDirtyCallBack = (defines) => defines.markAsImageProcessingDirty(); Material._TextureDirtyCallBack = (defines) => defines.markAsTexturesDirty(); Material._FresnelDirtyCallBack = (defines) => defines.markAsFresnelDirty(); Material._MiscDirtyCallBack = (defines) => defines.markAsMiscDirty(); Material._PrePassDirtyCallBack = (defines) => defines.markAsPrePassDirty(); Material._LightsDirtyCallBack = (defines) => defines.markAsLightDirty(); Material._AttributeDirtyCallBack = (defines) => defines.markAsAttributesDirty(); Material._FresnelAndMiscDirtyCallBack = (defines) => { Material._FresnelDirtyCallBack(defines); Material._MiscDirtyCallBack(defines); }; Material._TextureAndMiscDirtyCallBack = (defines) => { Material._TextureDirtyCallBack(defines); Material._MiscDirtyCallBack(defines); }; Material._DirtyCallbackArray = []; Material._RunDirtyCallBacks = (defines) => { for (const cb of Material._DirtyCallbackArray) { cb(defines); } }; __decorate([ serialize() ], Material.prototype, "id", void 0); __decorate([ serialize() ], Material.prototype, "uniqueId", void 0); __decorate([ serialize() ], Material.prototype, "name", void 0); __decorate([ serialize() ], Material.prototype, "metadata", void 0); __decorate([ serialize() ], Material.prototype, "checkReadyOnEveryCall", void 0); __decorate([ serialize() ], Material.prototype, "checkReadyOnlyOnce", void 0); __decorate([ serialize() ], Material.prototype, "state", void 0); __decorate([ serialize("alpha") ], Material.prototype, "_alpha", void 0); __decorate([ serialize("backFaceCulling") ], Material.prototype, "_backFaceCulling", void 0); __decorate([ serialize("cullBackFaces") ], Material.prototype, "_cullBackFaces", void 0); __decorate([ serialize() ], Material.prototype, "sideOrientation", void 0); __decorate([ serialize() ], Material.prototype, "_alphaMode", void 0); __decorate([ serialize() ], Material.prototype, "_needDepthPrePass", void 0); __decorate([ serialize() ], Material.prototype, "disableDepthWrite", void 0); __decorate([ serialize() ], Material.prototype, "disableColorWrite", void 0); __decorate([ serialize() ], Material.prototype, "forceDepthWrite", void 0); __decorate([ serialize() ], Material.prototype, "depthFunction", void 0); __decorate([ serialize() ], Material.prototype, "separateCullingPass", void 0); __decorate([ serialize("fogEnabled") ], Material.prototype, "_fogEnabled", void 0); __decorate([ serialize() ], Material.prototype, "pointSize", void 0); __decorate([ serialize() ], Material.prototype, "zOffset", void 0); __decorate([ serialize() ], Material.prototype, "zOffsetUnits", void 0); __decorate([ serialize() ], Material.prototype, "pointsCloud", null); __decorate([ serialize() ], Material.prototype, "fillMode", null); __decorate([ serialize() ], Material.prototype, "useLogarithmicDepth", null); __decorate([ serialize() ], Material.prototype, "_isVertexOutputInvariant", void 0); __decorate([ serialize() ], Material.prototype, "transparencyMode", null); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/prePassConfiguration.js var PrePassConfiguration = class { static { __name(this, "PrePassConfiguration"); } constructor() { this.previousWorldMatrices = {}; this.previousBones = {}; } /** * Add the required uniforms to the current list. * @param uniforms defines the current uniform list. */ static AddUniforms(uniforms) { uniforms.push("previousWorld", "previousViewProjection", "mPreviousBones"); } /** * Add the required samplers to the current list. * @param samplers defines the current sampler list. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars static AddSamplers(samplers) { } /** * Binds the material data. * @param effect defines the effect to update * @param scene defines the scene the material belongs to. * @param mesh The mesh * @param world World matrix of this mesh * @param isFrozen Is the material frozen */ // eslint-disable-next-line @typescript-eslint/no-unused-vars bindForSubMesh(effect, scene, mesh, world, isFrozen) { if (scene.prePassRenderer && scene.prePassRenderer.enabled && scene.prePassRenderer.currentRTisSceneRT) { if (scene.prePassRenderer.getIndex(2) !== -1 || scene.prePassRenderer.getIndex(11) !== -1) { if (!this.previousWorldMatrices[mesh.uniqueId]) { this.previousWorldMatrices[mesh.uniqueId] = world.clone(); } if (!this.previousViewProjection) { this.previousViewProjection = scene.getTransformMatrix().clone(); this.currentViewProjection = scene.getTransformMatrix().clone(); } const engine = scene.getEngine(); if (this.currentViewProjection.updateFlag !== scene.getTransformMatrix().updateFlag) { this._lastUpdateFrameId = engine.frameId; this.previousViewProjection.copyFrom(this.currentViewProjection); this.currentViewProjection.copyFrom(scene.getTransformMatrix()); } else if (this._lastUpdateFrameId !== engine.frameId) { this._lastUpdateFrameId = engine.frameId; this.previousViewProjection.copyFrom(this.currentViewProjection); } effect.setMatrix("previousWorld", this.previousWorldMatrices[mesh.uniqueId]); effect.setMatrix("previousViewProjection", this.previousViewProjection); this.previousWorldMatrices[mesh.uniqueId] = world.clone(); } } } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialDefines.js var MaterialDefines = class { static { __name(this, "MaterialDefines"); } /** * Creates a new instance * @param externalProperties list of external properties to inject into the object */ constructor(externalProperties) { this.VERTEXOUTPUT_INVARIANT = false; this._keys = []; this._isDirty = true; this._areLightsDirty = true; this._areLightsDisposed = false; this._areAttributesDirty = true; this._areTexturesDirty = true; this._areFresnelDirty = true; this._areMiscDirty = true; this._arePrePassDirty = true; this._areImageProcessingDirty = true; this._normals = false; this._uvs = false; this._needNormals = false; this._needUVs = false; this._externalProperties = externalProperties; if (externalProperties) { for (const prop in externalProperties) { if (Object.prototype.hasOwnProperty.call(externalProperties, prop)) { this._setDefaultValue(prop); } } } } /** * Specifies if the material needs to be re-calculated */ get isDirty() { return this._isDirty; } /** * Marks the material to indicate that it has been re-calculated */ markAsProcessed() { this._isDirty = false; this._areAttributesDirty = false; this._areTexturesDirty = false; this._areFresnelDirty = false; this._areLightsDirty = false; this._areLightsDisposed = false; this._areMiscDirty = false; this._arePrePassDirty = false; this._areImageProcessingDirty = false; } /** * Marks the material to indicate that it needs to be re-calculated */ markAsUnprocessed() { this._isDirty = true; } /** * Marks the material to indicate all of its defines need to be re-calculated */ markAllAsDirty() { this._areTexturesDirty = true; this._areAttributesDirty = true; this._areLightsDirty = true; this._areFresnelDirty = true; this._areMiscDirty = true; this._arePrePassDirty = true; this._areImageProcessingDirty = true; this._isDirty = true; } /** * Marks the material to indicate that image processing needs to be re-calculated */ markAsImageProcessingDirty() { this._areImageProcessingDirty = true; this._isDirty = true; } /** * Marks the material to indicate the lights need to be re-calculated * @param disposed Defines whether the light is dirty due to dispose or not */ markAsLightDirty(disposed = false) { this._areLightsDirty = true; this._areLightsDisposed = this._areLightsDisposed || disposed; this._isDirty = true; } /** * Marks the attribute state as changed */ markAsAttributesDirty() { this._areAttributesDirty = true; this._isDirty = true; } /** * Marks the texture state as changed */ markAsTexturesDirty() { this._areTexturesDirty = true; this._isDirty = true; } /** * Marks the fresnel state as changed */ markAsFresnelDirty() { this._areFresnelDirty = true; this._isDirty = true; } /** * Marks the misc state as changed */ markAsMiscDirty() { this._areMiscDirty = true; this._isDirty = true; } /** * Marks the prepass state as changed */ markAsPrePassDirty() { this._arePrePassDirty = true; this._isDirty = true; } /** * Rebuilds the material defines */ rebuild() { this._keys.length = 0; for (const key of Object.keys(this)) { if (key[0] === "_") { continue; } this._keys.push(key); } if (this._externalProperties) { for (const name260 in this._externalProperties) { if (this._keys.indexOf(name260) === -1) { this._keys.push(name260); } } } } /** * Specifies if two material defines are equal * @param other - A material define instance to compare to * @returns - Boolean indicating if the material defines are equal (true) or not (false) */ isEqual(other) { if (this._keys.length !== other._keys.length) { return false; } for (let index = 0; index < this._keys.length; index++) { const prop = this._keys[index]; if (this[prop] !== other[prop]) { return false; } } return true; } /** * Clones this instance's defines to another instance * @param other - material defines to clone values to */ cloneTo(other) { if (this._keys.length !== other._keys.length) { other._keys = this._keys.slice(0); } for (let index = 0; index < this._keys.length; index++) { const prop = this._keys[index]; other[prop] = this[prop]; } } /** * Resets the material define values */ reset() { for (const prop of this._keys) { this._setDefaultValue(prop); } } _setDefaultValue(prop) { const type = this._externalProperties?.[prop]?.type ?? typeof this[prop]; const defValue = this._externalProperties?.[prop]?.default; switch (type) { case "number": this[prop] = defValue ?? 0; break; case "string": this[prop] = defValue ?? ""; break; default: this[prop] = defValue ?? false; break; } } /** * Converts the material define values to a string * @returns - String of material define information */ toString() { let result = ""; for (let index = 0; index < this._keys.length; index++) { const prop = this._keys[index]; const value = this[prop]; const type = typeof value; switch (type) { case "number": case "string": result += "#define " + prop + " " + value + "\n"; break; default: if (value) { result += "#define " + prop + "\n"; } break; } } return result; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/imageProcessingConfiguration.defines.js function ImageProcessingDefinesMixin(base) { return class extends base { constructor() { super(...arguments); this.IMAGEPROCESSING = false; this.VIGNETTE = false; this.VIGNETTEBLENDMODEMULTIPLY = false; this.VIGNETTEBLENDMODEOPAQUE = false; this.TONEMAPPING = 0; this.CONTRAST = false; this.COLORCURVES = false; this.COLORGRADING = false; this.COLORGRADING3D = false; this.SAMPLER3DGREENDEPTH = false; this.SAMPLER3DBGRMAP = false; this.DITHER = false; this.IMAGEPROCESSINGPOSTPROCESS = false; this.SKIPFINALCOLORCLAMP = false; this.EXPOSURE = false; } }; } __name(ImageProcessingDefinesMixin, "ImageProcessingDefinesMixin"); var ImageProcessingConfigurationDefines = class extends MaterialDefines { static { __name(this, "ImageProcessingConfigurationDefines"); } constructor() { super(); this.IMAGEPROCESSING = false; this.VIGNETTE = false; this.VIGNETTEBLENDMODEMULTIPLY = false; this.VIGNETTEBLENDMODEOPAQUE = false; this.TONEMAPPING = 0; this.CONTRAST = false; this.COLORCURVES = false; this.COLORGRADING = false; this.COLORGRADING3D = false; this.SAMPLER3DGREENDEPTH = false; this.SAMPLER3DBGRMAP = false; this.DITHER = false; this.IMAGEPROCESSINGPOSTPROCESS = false; this.EXPOSURE = false; this.SKIPFINALCOLORCLAMP = false; this.rebuild(); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/pushMaterial.js init_math_vector(); var PushMaterial = class extends Material { static { __name(this, "PushMaterial"); } constructor(name260, scene, storeEffectOnSubMeshes = true, forceGLSL = false) { super(name260, scene, void 0, forceGLSL); this._normalMatrix = new Matrix(); this._storeEffectOnSubMeshes = storeEffectOnSubMeshes; } getEffect() { return this._storeEffectOnSubMeshes ? this._activeEffect : super.getEffect(); } isReady(mesh, useInstances) { if (!mesh) { return false; } if (!this._storeEffectOnSubMeshes) { return true; } if (!mesh.subMeshes || mesh.subMeshes.length === 0) { return true; } return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances); } _isReadyForSubMesh(subMesh) { const defines = subMesh.materialDefines; if (!this.checkReadyOnEveryCall && subMesh.effect && defines) { if (defines._renderId === this.getScene().getRenderId()) { return true; } } return false; } /** * Binds the given world matrix to the active effect * * @param world the matrix to bind */ bindOnlyWorldMatrix(world) { this._activeEffect.setMatrix("world", world); } /** * Binds the given normal matrix to the active effect * * @param normalMatrix the matrix to bind */ bindOnlyNormalMatrix(normalMatrix) { this._activeEffect.setMatrix("normalMatrix", normalMatrix); } bind(world, mesh) { if (!mesh) { return; } this.bindForSubMesh(world, mesh, mesh.subMeshes[0]); } _afterBind(mesh, effect = null, subMesh) { super._afterBind(mesh, effect, subMesh); this.getScene()._cachedEffect = effect; if (subMesh) { subMesh._drawWrapper._forceRebindOnNextCall = false; } else { this._drawWrapper._forceRebindOnNextCall = false; } } _mustRebind(scene, effect, subMesh, visibility = 1) { return subMesh._drawWrapper._forceRebindOnNextCall || scene.isCachedMaterialInvalid(this, effect, visibility); } dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) { this._activeEffect = void 0; super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialPluginManager.js init_engineStore(); init_shaderProcessor(); init_shaderStore(); var RxOption = new RegExp("^([gimus]+)!"); var MaterialPluginManager = class _MaterialPluginManager { static { __name(this, "MaterialPluginManager"); } /** * Creates a new instance of the plugin manager * @param material material that this manager will manage the plugins for */ constructor(material) { this._plugins = []; this._activePlugins = []; this._activePluginsForExtraEvents = []; this._material = material; this._scene = material.getScene(); this._engine = this._scene.getEngine(); } /** * @internal */ _addPlugin(plugin) { for (let i = 0; i < this._plugins.length; ++i) { if (this._plugins[i].name === plugin.name) { return false; } } if (this._material._uniformBufferLayoutBuilt) { this._material.resetDrawCache(); this._material._createUniformBuffer(); } if (!plugin.isCompatible(this._material.shaderLanguage)) { throw `The plugin "${plugin.name}" can't be added to the material "${this._material.name}" because the plugin is not compatible with the shader language of the material.`; } const pluginClassName = plugin.getClassName(); if (!_MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName]) { _MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName] = "MATERIALPLUGIN_" + ++_MaterialPluginManager._MaterialPluginCounter; } this._material._callbackPluginEventGeneric = (id, info) => this._handlePluginEvent(id, info); this._plugins.push(plugin); this._plugins.sort((a, b) => a.priority - b.priority); this._codeInjectionPoints = {}; const defineNamesFromPlugins = {}; defineNamesFromPlugins[_MaterialPluginManager._MaterialPluginClassToMainDefine[pluginClassName]] = { type: "boolean", default: true }; for (const plugin2 of this._plugins) { plugin2.collectDefines(defineNamesFromPlugins); this._collectPointNames("vertex", plugin2.getCustomCode("vertex", this._material.shaderLanguage)); this._collectPointNames("fragment", plugin2.getCustomCode("fragment", this._material.shaderLanguage)); } this._defineNamesFromPlugins = defineNamesFromPlugins; return true; } /** * @internal */ _activatePlugin(plugin) { if (this._activePlugins.indexOf(plugin) === -1) { this._activePlugins.push(plugin); this._activePlugins.sort((a, b) => a.priority - b.priority); this._material._callbackPluginEventIsReadyForSubMesh = this._handlePluginEventIsReadyForSubMesh.bind(this); this._material._callbackPluginEventPrepareDefinesBeforeAttributes = this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this); this._material._callbackPluginEventPrepareDefines = this._handlePluginEventPrepareDefines.bind(this); this._material._callbackPluginEventBindForSubMesh = this._handlePluginEventBindForSubMesh.bind(this); if (plugin.registerForExtraEvents) { this._activePluginsForExtraEvents.push(plugin); this._activePluginsForExtraEvents.sort((a, b) => a.priority - b.priority); this._material._callbackPluginEventHasRenderTargetTextures = this._handlePluginEventHasRenderTargetTextures.bind(this); this._material._callbackPluginEventFillRenderTargetTextures = this._handlePluginEventFillRenderTargetTextures.bind(this); this._material._callbackPluginEventHardBindForSubMesh = this._handlePluginEventHardBindForSubMesh.bind(this); } } } /** * Gets a plugin from the list of plugins managed by this manager * @param name name of the plugin * @returns the plugin if found, else null */ getPlugin(name260) { for (let i = 0; i < this._plugins.length; ++i) { if (this._plugins[i].name === name260) { return this._plugins[i]; } } return null; } _handlePluginEventIsReadyForSubMesh(eventData) { let isReady = true; for (const plugin of this._activePlugins) { isReady = isReady && plugin.isReadyForSubMesh(eventData.defines, this._scene, this._engine, eventData.subMesh); } eventData.isReadyForSubMesh = isReady; } _handlePluginEventPrepareDefinesBeforeAttributes(eventData) { for (const plugin of this._activePlugins) { plugin.prepareDefinesBeforeAttributes(eventData.defines, this._scene, eventData.mesh); } } _handlePluginEventPrepareDefines(eventData) { for (const plugin of this._activePlugins) { plugin.prepareDefines(eventData.defines, this._scene, eventData.mesh); } } _handlePluginEventHardBindForSubMesh(eventData) { for (const plugin of this._activePluginsForExtraEvents) { plugin.hardBindForSubMesh(this._material._uniformBuffer, this._scene, this._engine, eventData.subMesh); } } _handlePluginEventBindForSubMesh(eventData) { for (const plugin of this._activePlugins) { plugin.bindForSubMesh(this._material._uniformBuffer, this._scene, this._engine, eventData.subMesh); } } _handlePluginEventHasRenderTargetTextures(eventData) { let hasRenderTargetTextures = false; for (const plugin of this._activePluginsForExtraEvents) { hasRenderTargetTextures = plugin.hasRenderTargetTextures(); if (hasRenderTargetTextures) { break; } } eventData.hasRenderTargetTextures = hasRenderTargetTextures; } _handlePluginEventFillRenderTargetTextures(eventData) { for (const plugin of this._activePluginsForExtraEvents) { plugin.fillRenderTargetTextures(eventData.renderTargets); } } _handlePluginEvent(id, info) { switch (id) { case 512: { const eventData = info; for (const plugin of this._activePlugins) { plugin.getActiveTextures(eventData.activeTextures); } break; } case 256: { const eventData = info; for (const plugin of this._activePlugins) { plugin.getAnimatables(eventData.animatables); } break; } case 1024: { const eventData = info; let hasTexture = false; for (const plugin of this._activePlugins) { hasTexture = plugin.hasTexture(eventData.texture); if (hasTexture) { break; } } eventData.hasTexture = hasTexture; break; } case 2: { const eventData = info; for (const plugin of this._plugins) { plugin.dispose(eventData.forceDisposeTextures); } break; } case 4: { const eventData = info; eventData.defineNames = this._defineNamesFromPlugins; break; } case 128: { const eventData = info; for (const plugin of this._activePlugins) { eventData.fallbackRank = plugin.addFallbacks(eventData.defines, eventData.fallbacks, eventData.fallbackRank); plugin.getAttributes(eventData.attributes, this._scene, eventData.mesh); } if (this._uniformList.length > 0) { eventData.uniforms.push(...this._uniformList); } if (this._samplerList.length > 0) { eventData.samplers.push(...this._samplerList); } if (this._uboList.length > 0) { eventData.uniformBuffersNames.push(...this._uboList); } eventData.customCode = this._injectCustomCode(eventData, eventData.customCode); break; } case 8: { const eventData = info; this._uboDeclaration = ""; this._vertexDeclaration = ""; this._fragmentDeclaration = ""; this._uniformList = []; this._samplerList = []; this._uboList = []; const isWebGPU = this._material.shaderLanguage === 1; for (const plugin of this._plugins) { const uniforms = plugin.getUniforms(this._material.shaderLanguage); if (uniforms) { if (uniforms.ubo) { for (const uniform of uniforms.ubo) { if (uniform.size && uniform.type) { const arraySize = uniform.arraySize ?? 0; eventData.ubo.addUniform(uniform.name, uniform.size, arraySize); if (isWebGPU) { let type; switch (uniform.type) { case "mat4": type = "mat4x4f"; break; case "float": type = "f32"; break; default: type = `${uniform.type}f`; break; } if (arraySize > 0) { this._uboDeclaration += `uniform ${uniform.name}: array<${type}, ${arraySize}>; `; } else { this._uboDeclaration += `uniform ${uniform.name}: ${type}; `; } } else { this._uboDeclaration += `${uniform.type} ${uniform.name}${arraySize > 0 ? `[${arraySize}]` : ""}; `; } } this._uniformList.push(uniform.name); } } if (uniforms.vertex) { this._vertexDeclaration += uniforms.vertex + "\n"; } if (uniforms.fragment) { this._fragmentDeclaration += uniforms.fragment + "\n"; } if (uniforms.externalUniforms) { this._uniformList.push(...uniforms.externalUniforms); } } plugin.getSamplers(this._samplerList); plugin.getUniformBuffersNames(this._uboList); } break; } } } _collectPointNames(shaderType, customCode) { if (!customCode) { return; } for (const pointName in customCode) { if (!this._codeInjectionPoints[shaderType]) { this._codeInjectionPoints[shaderType] = {}; } this._codeInjectionPoints[shaderType][pointName] = true; } } _injectCustomCode(eventData, existingCallback) { return (shaderType, code) => { if (existingCallback) { code = existingCallback(shaderType, code); } if (this._uboDeclaration) { code = code.replace("#define ADDITIONAL_UBO_DECLARATION", this._uboDeclaration); } if (this._vertexDeclaration) { code = code.replace("#define ADDITIONAL_VERTEX_DECLARATION", this._vertexDeclaration); } if (this._fragmentDeclaration) { code = code.replace("#define ADDITIONAL_FRAGMENT_DECLARATION", this._fragmentDeclaration); } const points = this._codeInjectionPoints?.[shaderType]; if (!points) { return code; } let processorOptions = null; for (let pointName in points) { let injectedCode = ""; for (const plugin of this._activePlugins) { let customCode = plugin.getCustomCode(shaderType, this._material.shaderLanguage)?.[pointName]; if (!customCode) { continue; } if (plugin.resolveIncludes) { if (processorOptions === null) { const shaderLanguage = 0; processorOptions = { defines: [], // not used by _ProcessIncludes indexParameters: eventData.indexParameters, isFragment: false, shouldUseHighPrecisionShader: this._engine._shouldUseHighPrecisionShader, processor: void 0, // not used by _ProcessIncludes supportsUniformBuffers: this._engine.supportsUniformBuffers, shadersRepository: ShaderStore.GetShadersRepository(shaderLanguage), includesShadersStore: ShaderStore.GetIncludesShadersStore(shaderLanguage), version: void 0, // not used by _ProcessIncludes platformName: this._engine.shaderPlatformName, processingContext: void 0, // not used by _ProcessIncludes isNDCHalfZRange: this._engine.isNDCHalfZRange, useReverseDepthBuffer: this._engine.useReverseDepthBuffer, processCodeAfterIncludes: void 0 // not used by _ProcessIncludes }; } processorOptions.isFragment = shaderType === "fragment"; ProcessIncludes(customCode, processorOptions, (code2) => customCode = code2); } injectedCode += customCode + "\n"; } if (injectedCode.length > 0) { if (pointName.charAt(0) === "!") { pointName = pointName.substring(1); let regexFlags = "g"; if (pointName.charAt(0) === "!") { regexFlags = ""; pointName = pointName.substring(1); } else { const matchOption = RxOption.exec(pointName); if (matchOption && matchOption.length >= 2) { regexFlags = matchOption[1]; pointName = pointName.substring(regexFlags.length + 1); } } if (regexFlags.indexOf("g") < 0) { regexFlags += "g"; } const sourceCode = code; const rx = new RegExp(pointName, regexFlags); let match = rx.exec(sourceCode); while (match !== null) { let newCode = injectedCode; for (let i = 0; i < match.length; ++i) { newCode = newCode.replace("$" + i, match[i]); } code = code.replace(match[0], newCode); match = rx.exec(sourceCode); } } else { const fullPointName = "#define " + pointName; code = code.replace(fullPointName, "\n" + injectedCode + "\n" + fullPointName); } } } return code; }; } }; MaterialPluginManager._MaterialPluginClassToMainDefine = {}; MaterialPluginManager._MaterialPluginCounter = 0; (() => { EngineStore.OnEnginesDisposedObservable.add(() => { UnregisterAllMaterialPlugins(); }); })(); var Plugins = []; var Inited = false; var MaterialObserver = null; function RegisterMaterialPlugin(pluginName, factory) { if (!Inited) { MaterialObserver = Material.OnEventObservable.add( (material) => { for (const [, factory2] of Plugins) { factory2(material); } }, 1 /* MaterialPluginEvent.Created */ ); Inited = true; } const existing = Plugins.filter(([name260, _factory]) => name260 === pluginName); if (existing.length > 0) { existing[0][1] = factory; } else { Plugins.push([pluginName, factory]); } } __name(RegisterMaterialPlugin, "RegisterMaterialPlugin"); function UnregisterMaterialPlugin(pluginName) { for (let i = 0; i < Plugins.length; ++i) { if (Plugins[i][0] === pluginName) { Plugins.splice(i, 1); if (Plugins.length === 0) { UnregisterAllMaterialPlugins(); } return true; } } return false; } __name(UnregisterMaterialPlugin, "UnregisterMaterialPlugin"); function UnregisterAllMaterialPlugins() { Plugins.length = 0; Inited = false; Material.OnEventObservable.remove(MaterialObserver); MaterialObserver = null; } __name(UnregisterAllMaterialPlugins, "UnregisterAllMaterialPlugins"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialPluginBase.js init_tslib_es6(); init_decorators(); init_decorators_serialization(); init_typeStore(); var MaterialPluginBase = class { static { __name(this, "MaterialPluginBase"); } /** * Gets a boolean indicating that the plugin is compatible with a given shader language. * @param shaderLanguage The shader language to use. * @returns true if the plugin is compatible with the shader language */ isCompatible(shaderLanguage) { switch (shaderLanguage) { case 0: return true; default: return false; } } _enable(enable) { if (enable) { this._pluginManager._activatePlugin(this); } } /** * Creates a new material plugin * @param material parent material of the plugin * @param name name of the plugin * @param priority priority of the plugin * @param defines list of defines used by the plugin. The value of the property is the default value for this property * @param addToPluginList true to add the plugin to the list of plugins managed by the material plugin manager of the material (default: true) * @param enable true to enable the plugin (it is handy if the plugin does not handle properties to switch its current activation) * @param resolveIncludes Indicates that any #include directive in the plugin code must be replaced by the corresponding code (default: false) */ constructor(material, name260, priority, defines, addToPluginList = true, enable = false, resolveIncludes = false) { this.priority = 500; this.resolveIncludes = false; this.registerForExtraEvents = false; this.doNotSerialize = false; this._material = material; this.name = name260; this.priority = priority; this.resolveIncludes = resolveIncludes; if (!material.pluginManager) { material.pluginManager = new MaterialPluginManager(material); material.onDisposeObservable.add(() => { material.pluginManager = void 0; }); } this._pluginDefineNames = defines; this._pluginManager = material.pluginManager; if (addToPluginList) { this._pluginManager._addPlugin(this); } if (enable) { this._enable(true); } this.markAllDefinesAsDirty = material._dirtyCallbacks[127]; } /** * Gets the current class name useful for serialization or dynamic coding. * @returns The class name. */ getClassName() { return "MaterialPluginBase"; } /** * 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. * @param _engine the engine this scene belongs to. * @param _subMesh the submesh to check for readiness * @returns - boolean indicating that the submesh is ready or not. */ isReadyForSubMesh(_defines, _scene, _engine, _subMesh) { return true; } /** * Binds the material data (this function is called even if mustRebind() returns false) * @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 _subMesh the submesh to bind data for */ hardBindForSubMesh(_uniformBuffer, _scene, _engine, _subMesh) { } /** * Binds the material data. * @param _uniformBuffer defines the Uniform buffer to fill in. * @param _scene defines the scene the material belongs to. * @param _engine the engine this scene belongs to. * @param _subMesh the submesh to bind data for */ bindForSubMesh(_uniformBuffer, _scene, _engine, _subMesh) { } /** * Disposes the resources of the material. * @param _forceDisposeTextures - Forces the disposal of all textures. */ dispose(_forceDisposeTextures) { } /** * Returns a list of custom shader code fragments to customize the shader. * @param _shaderType "vertex" or "fragment" * @param _shaderLanguage The shader language to use. * @returns null if no code to be added, or a list of pointName =\> code. * Note that `pointName` can also be a regular expression if it starts with a `!`. * In that case, the string found by the regular expression (if any) will be * replaced by the code provided. */ getCustomCode(_shaderType, _shaderLanguage = 0) { return null; } /** * Collects all defines. * @param defines The object to append to. */ collectDefines(defines) { if (!this._pluginDefineNames) { return; } for (const key of Object.keys(this._pluginDefineNames)) { if (key[0] === "_") { continue; } const type = typeof this._pluginDefineNames[key]; defines[key] = { type: type === "number" ? "number" : type === "string" ? "string" : type === "boolean" ? "boolean" : "object", default: this._pluginDefineNames[key] }; } } /** * Sets the defines for the next rendering. Called before PrepareDefinesForAttributes is called. * @param _defines the list of "defines" to update. * @param _scene defines the scene to the material belongs to. * @param _mesh the mesh being rendered */ prepareDefinesBeforeAttributes(_defines, _scene, _mesh) { } /** * Sets the defines for the next rendering * @param _defines the list of "defines" to update. * @param _scene defines the scene to the material belongs to. * @param _mesh the mesh being rendered */ prepareDefines(_defines, _scene, _mesh) { } /** * 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. */ hasTexture(_texture) { return false; } /** * Gets a boolean indicating that current material needs to register RTT * @returns true if this uses a render target otherwise false. */ hasRenderTargetTextures() { return false; } /** * Fills the list of render target textures. * @param _renderTargets the list of render targets to update */ fillRenderTargetTextures(_renderTargets) { } /** * Returns an array of the actively used textures. * @param _activeTextures Array of BaseTextures */ getActiveTextures(_activeTextures) { } /** * Returns the animatable textures. * @param _animatables Array of animatable textures. */ getAnimatables(_animatables) { } /** * 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. */ addFallbacks(defines, fallbacks, currentRank) { return currentRank; } /** * Gets the samplers used by the plugin. * @param _samplers list that the sampler names should be added to. */ getSamplers(_samplers) { } /** * Gets the attributes used by the plugin. * @param _attributes list that the attribute names should be added to. * @param _scene the scene that the material belongs to. * @param _mesh the mesh being rendered. */ getAttributes(_attributes, _scene, _mesh) { } /** * Gets the uniform buffers names added by the plugin. * @param _ubos list that the ubo names should be added to. */ getUniformBuffersNames(_ubos) { } /** * Gets the description of the uniforms to add to the ubo (if engine supports ubos) or to inject directly in the vertex/fragment shaders (if engine does not support ubos) * @param _shaderLanguage The shader language to use. * @returns the description of the uniforms */ getUniforms(_shaderLanguage = 0) { return {}; } /** * Makes a duplicate of the current configuration into another one. * @param plugin define the config where to copy the info */ copyTo(plugin) { SerializationHelper.Clone(() => plugin, this); } /** * Serializes this plugin configuration. * @returns - An object with the serialized config. */ serialize() { return SerializationHelper.Serialize(this); } /** * Parses a plugin 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 */ parse(source, scene, rootUrl) { SerializationHelper.Parse(() => this, source, scene, rootUrl); } }; __decorate([ serialize() ], MaterialPluginBase.prototype, "name", void 0); __decorate([ serialize() ], MaterialPluginBase.prototype, "priority", void 0); __decorate([ serialize() ], MaterialPluginBase.prototype, "resolveIncludes", void 0); __decorate([ serialize() ], MaterialPluginBase.prototype, "registerForExtraEvents", void 0); RegisterClass("BABYLON.MaterialPluginBase", MaterialPluginBase); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/material.detailMapConfiguration.js init_tslib_es6(); init_decorators(); init_materialFlags(); init_materialHelper_functions(); var MaterialDetailMapDefines = class extends MaterialDefines { static { __name(this, "MaterialDetailMapDefines"); } constructor() { super(...arguments); this.DETAIL = false; this.DETAILDIRECTUV = 0; this.DETAIL_NORMALBLENDMETHOD = 0; } }; var DetailMapConfiguration = class extends MaterialPluginBase { static { __name(this, "DetailMapConfiguration"); } /** @internal */ _markAllSubMeshesAsTexturesDirty() { this._enable(this._isEnabled); this._internalMarkAllSubMeshesAsTexturesDirty(); } /** * Gets a boolean indicating that the plugin is compatible with a given shader language. * @returns true if the plugin is compatible with the shader language */ isCompatible() { return true; } constructor(material, addToPluginList = true) { super(material, "DetailMap", 140, new MaterialDetailMapDefines(), addToPluginList); this._texture = null; this.diffuseBlendLevel = 1; this.roughnessBlendLevel = 1; this.bumpLevel = 1; this._normalBlendMethod = Material.MATERIAL_NORMALBLENDMETHOD_WHITEOUT; this._isEnabled = false; this.isEnabled = false; this._internalMarkAllSubMeshesAsTexturesDirty = material._dirtyCallbacks[1]; } isReadyForSubMesh(defines, scene, engine) { if (!this._isEnabled) { return true; } if (defines._areTexturesDirty && scene.texturesEnabled) { if (engine.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled) { if (!this._texture.isReady()) { return false; } } } return true; } prepareDefines(defines, scene) { if (this._isEnabled) { defines.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod; const engine = scene.getEngine(); if (defines._areTexturesDirty) { if (engine.getCaps().standardDerivatives && this._texture && MaterialFlags.DetailTextureEnabled && this._isEnabled) { PrepareDefinesForMergedUV(this._texture, defines, "DETAIL"); defines.DETAIL_NORMALBLENDMETHOD = this._normalBlendMethod; } else { defines.DETAIL = false; } } } else { defines.DETAIL = false; } } bindForSubMesh(uniformBuffer, scene) { if (!this._isEnabled) { return; } const isFrozen = this._material.isFrozen; if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) { if (this._texture && MaterialFlags.DetailTextureEnabled) { uniformBuffer.updateFloat4("vDetailInfos", this._texture.coordinatesIndex, this.diffuseBlendLevel, this.bumpLevel, this.roughnessBlendLevel); BindTextureMatrix(this._texture, uniformBuffer, "detail"); } } if (scene.texturesEnabled) { if (this._texture && MaterialFlags.DetailTextureEnabled) { uniformBuffer.setTexture("detailSampler", this._texture); } } } hasTexture(texture) { if (this._texture === texture) { return true; } return false; } getActiveTextures(activeTextures) { if (this._texture) { activeTextures.push(this._texture); } } getAnimatables(animatables) { if (this._texture && this._texture.animations && this._texture.animations.length > 0) { animatables.push(this._texture); } } dispose(forceDisposeTextures) { if (forceDisposeTextures) { this._texture?.dispose(); } } getClassName() { return "DetailMapConfiguration"; } getSamplers(samplers) { samplers.push("detailSampler"); } getUniforms() { return { ubo: [ { name: "vDetailInfos", size: 4, type: "vec4" }, { name: "detailMatrix", size: 16, type: "mat4" } ] }; } }; __decorate([ serializeAsTexture("detailTexture"), expandToProperty("_markAllSubMeshesAsTexturesDirty") ], DetailMapConfiguration.prototype, "texture", void 0); __decorate([ serialize() ], DetailMapConfiguration.prototype, "diffuseBlendLevel", void 0); __decorate([ serialize() ], DetailMapConfiguration.prototype, "roughnessBlendLevel", void 0); __decorate([ serialize() ], DetailMapConfiguration.prototype, "bumpLevel", void 0); __decorate([ serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty") ], DetailMapConfiguration.prototype, "normalBlendMethod", void 0); __decorate([ serialize(), expandToProperty("_markAllSubMeshesAsTexturesDirty") ], DetailMapConfiguration.prototype, "isEnabled", void 0); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/materialHelper.geometryrendering.js init_math_vector(); var GeometryRenderingTextureClearType; (function(GeometryRenderingTextureClearType2) { GeometryRenderingTextureClearType2[GeometryRenderingTextureClearType2["Zero"] = 0] = "Zero"; GeometryRenderingTextureClearType2[GeometryRenderingTextureClearType2["One"] = 1] = "One"; GeometryRenderingTextureClearType2[GeometryRenderingTextureClearType2["MaxViewZ"] = 2] = "MaxViewZ"; })(GeometryRenderingTextureClearType || (GeometryRenderingTextureClearType = {})); var MaterialHelperGeometryRendering = class _MaterialHelperGeometryRendering { static { __name(this, "MaterialHelperGeometryRendering"); } /** * Creates a new geometry rendering configuration. * @param renderPassId Render pass id the configuration is created for. * @returns The created configuration. */ static CreateConfiguration(renderPassId) { _MaterialHelperGeometryRendering._Configurations[renderPassId] = { defines: {}, previousWorldMatrices: {}, previousViewProjection: Matrix.Zero(), currentViewProjection: Matrix.Zero(), previousBones: {}, lastUpdateFrameId: -1, excludedSkinnedMesh: [], reverseCulling: false }; return _MaterialHelperGeometryRendering._Configurations[renderPassId]; } /** * Deletes a geometry rendering configuration. * @param renderPassId The render pass id of the configuration to delete. */ static DeleteConfiguration(renderPassId) { delete _MaterialHelperGeometryRendering._Configurations[renderPassId]; } /** * Gets a geometry rendering configuration. * @param renderPassId The render pass id of the configuration to get. * @returns The configuration. */ static GetConfiguration(renderPassId) { return _MaterialHelperGeometryRendering._Configurations[renderPassId]; } /** * Adds uniforms and samplers for geometry rendering. * @param uniforms The array of uniforms to add to. * @param _samplers The array of samplers to add to. */ static AddUniformsAndSamplers(uniforms, _samplers) { uniforms.push("previousWorld", "previousViewProjection", "mPreviousBones"); } /** * Marks a list of meshes as dirty for geometry rendering. * @param renderPassId The render pass id the meshes are marked as dirty for. * @param meshes The list of meshes to mark as dirty. */ static MarkAsDirty(renderPassId, meshes) { for (const mesh of meshes) { if (!mesh.subMeshes) { continue; } for (const subMesh of mesh.subMeshes) { subMesh._removeDrawWrapper(renderPassId); } } } /** * Prepares defines for geometry rendering. * @param renderPassId The render pass id the defines are prepared for. * @param mesh The mesh the defines are prepared for. * @param defines The defines to update according to the geometry rendering configuration. */ static PrepareDefines(renderPassId, mesh, defines) { if (!defines._arePrePassDirty) { return; } const configuration = _MaterialHelperGeometryRendering._Configurations[renderPassId]; if (!configuration) { return; } defines["PREPASS"] = true; defines["PREPASS_COLOR"] = false; defines["PREPASS_COLOR_INDEX"] = -1; let numMRT = 0; for (let i = 0; i < _MaterialHelperGeometryRendering.GeometryTextureDescriptions.length; i++) { const geometryTextureDescription = _MaterialHelperGeometryRendering.GeometryTextureDescriptions[i]; const defineName = geometryTextureDescription.define; const defineIndex = geometryTextureDescription.defineIndex; const index = configuration.defines[defineIndex]; if (index !== void 0) { defines[defineName] = true; defines[defineIndex] = index; numMRT++; } else { defines[defineName] = false; delete defines[defineIndex]; } } defines["SCENE_MRT_COUNT"] = numMRT; defines["BONES_VELOCITY_ENABLED"] = mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton && !mesh.skeleton.isUsingTextureForMatrices && configuration.excludedSkinnedMesh.indexOf(mesh) === -1; } /** * Binds geometry rendering data for a mesh. * @param renderPassId The render pass id the geometry rendering data is bound for. * @param effect The effect to bind the geometry rendering data to. * @param mesh The mesh to bind the geometry rendering data for. * @param world The world matrix of the mesh. * @param material The material of the mesh. */ static Bind(renderPassId, effect, mesh, world, material) { const configuration = _MaterialHelperGeometryRendering._Configurations[renderPassId]; if (!configuration) { return; } const scene = mesh.getScene(); const engine = scene.getEngine(); if (configuration.reverseCulling) { engine.setStateCullFaceType(scene._mirroredCameraPosition ? material.cullBackFaces : !material.cullBackFaces); } if (configuration.defines["PREPASS_VELOCITY_INDEX"] !== void 0 || configuration.defines["PREPASS_VELOCITY_LINEAR_INDEX"] !== void 0) { if (!configuration.previousWorldMatrices[mesh.uniqueId]) { configuration.previousWorldMatrices[mesh.uniqueId] = world.clone(); } if (!configuration.previousViewProjection) { configuration.previousViewProjection = scene.getTransformMatrix().clone(); configuration.currentViewProjection = scene.getTransformMatrix().clone(); } if (configuration.currentViewProjection.updateFlag !== scene.getTransformMatrix().updateFlag) { configuration.lastUpdateFrameId = engine.frameId; configuration.previousViewProjection.copyFrom(configuration.currentViewProjection); configuration.currentViewProjection.copyFrom(scene.getTransformMatrix()); } else if (configuration.lastUpdateFrameId !== engine.frameId) { configuration.lastUpdateFrameId = engine.frameId; configuration.previousViewProjection.copyFrom(configuration.currentViewProjection); } effect.setMatrix("previousWorld", configuration.previousWorldMatrices[mesh.uniqueId]); effect.setMatrix("previousViewProjection", configuration.previousViewProjection); configuration.previousWorldMatrices[mesh.uniqueId] = world.clone(); if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { const skeleton = mesh.skeleton; if (!skeleton.isUsingTextureForMatrices || effect.getUniformIndex("boneTextureWidth") === -1) { const matrices = skeleton.getTransformMatrices(mesh); if (matrices) { if (!configuration.previousBones[mesh.uniqueId]) { configuration.previousBones[mesh.uniqueId] = matrices.slice(); } effect.setMatrices("mPreviousBones", configuration.previousBones[mesh.uniqueId]); configuration.previousBones[mesh.uniqueId].set(matrices); } } } } } }; MaterialHelperGeometryRendering.GeometryTextureDescriptions = [ { type: 0, name: "Irradiance", clearType: 0, define: "PREPASS_IRRADIANCE", defineIndex: "PREPASS_IRRADIANCE_INDEX" }, { type: 1, name: "WorldPosition", clearType: 0, define: "PREPASS_POSITION", defineIndex: "PREPASS_POSITION_INDEX" }, { type: 2, name: "Velocity", clearType: 0, define: "PREPASS_VELOCITY", defineIndex: "PREPASS_VELOCITY_INDEX" }, { type: 3, name: "Reflectivity", clearType: 0, define: "PREPASS_REFLECTIVITY", defineIndex: "PREPASS_REFLECTIVITY_INDEX" }, { type: 5, name: "ViewDepth", clearType: 2, define: "PREPASS_DEPTH", defineIndex: "PREPASS_DEPTH_INDEX" }, { type: 6, name: "ViewNormal", clearType: 0, define: "PREPASS_NORMAL", defineIndex: "PREPASS_NORMAL_INDEX" }, { type: 7, name: "AlbedoSqrt", clearType: 0, define: "PREPASS_ALBEDO_SQRT", defineIndex: "PREPASS_ALBEDO_SQRT_INDEX" }, { type: 8, name: "WorldNormal", clearType: 0, define: "PREPASS_WORLD_NORMAL", defineIndex: "PREPASS_WORLD_NORMAL_INDEX" }, { type: 9, name: "LocalPosition", clearType: 0, define: "PREPASS_LOCAL_POSITION", defineIndex: "PREPASS_LOCAL_POSITION_INDEX" }, { type: 10, name: "ScreenDepth", clearType: 1, define: "PREPASS_SCREENSPACE_DEPTH", defineIndex: "PREPASS_SCREENSPACE_DEPTH_INDEX" }, { type: 11, name: "LinearVelocity", clearType: 0, define: "PREPASS_VELOCITY_LINEAR", defineIndex: "PREPASS_VELOCITY_LINEAR_INDEX" }, { type: 12, name: "Albedo", clearType: 0, define: "PREPASS_ALBEDO", defineIndex: "PREPASS_ALBEDO_INDEX" }, { type: 13, name: "NormalizedViewDepth", clearType: 1, define: "PREPASS_NORMALIZED_VIEW_DEPTH", defineIndex: "PREPASS_NORMALIZED_VIEW_DEPTH_INDEX" } ]; MaterialHelperGeometryRendering._Configurations = {}; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/uv.defines.js function UVDefinesMixin(base) { return class extends base { constructor() { super(...arguments); this.MAINUV1 = false; this.MAINUV2 = false; this.MAINUV3 = false; this.MAINUV4 = false; this.MAINUV5 = false; this.MAINUV6 = false; this.UV1 = false; this.UV2 = false; this.UV3 = false; this.UV4 = false; this.UV5 = false; this.UV6 = false; } }; } __name(UVDefinesMixin, "UVDefinesMixin"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/imageProcessing.js init_decorators(); function ImageProcessingMixin(base) { return class extends base { /** * Constructor for the ImageProcessingMixin. * @param args - arguments to pass to the base class constructor */ constructor(...args) { super(...args); serializeAsImageProcessingConfiguration.call(this, this, "_imageProcessingConfiguration"); } /** * Gets the image processing configuration used either in this material. */ get imageProcessingConfiguration() { 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 imageProcessingConfiguration(value) { this._attachImageProcessingConfiguration(value); if (this._markAllSubMeshesAsImageProcessingDirty) { this._markAllSubMeshesAsImageProcessingDirty(); } } /** * Attaches a new image processing configuration to the Standard Material. * @param configuration */ _attachImageProcessingConfiguration(configuration) { if (configuration === this._imageProcessingConfiguration) { return; } if (this._imageProcessingConfiguration && this._imageProcessingObserver) { this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); } if (!configuration && this.getScene) { this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration; } else if (configuration) { this._imageProcessingConfiguration = configuration; } if (this._imageProcessingConfiguration) { this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => { if (this._markAllSubMeshesAsImageProcessingDirty) { this._markAllSubMeshesAsImageProcessingDirty(); } }); } } /** * Gets whether the color curves effect is enabled. */ get cameraColorCurvesEnabled() { return this.imageProcessingConfiguration.colorCurvesEnabled; } /** * Sets whether the color curves effect is enabled. */ set cameraColorCurvesEnabled(value) { this.imageProcessingConfiguration.colorCurvesEnabled = value; } /** * Gets whether the color grading effect is enabled. */ get cameraColorGradingEnabled() { return this.imageProcessingConfiguration.colorGradingEnabled; } /** * Gets whether the color grading effect is enabled. */ set cameraColorGradingEnabled(value) { this.imageProcessingConfiguration.colorGradingEnabled = value; } /** * Gets whether tonemapping is enabled or not. */ get cameraToneMappingEnabled() { return this._imageProcessingConfiguration.toneMappingEnabled; } /** * Sets whether tonemapping is enabled or not */ set cameraToneMappingEnabled(value) { this._imageProcessingConfiguration.toneMappingEnabled = value; } /** * 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 cameraExposure() { 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 cameraExposure(value) { this._imageProcessingConfiguration.exposure = value; } /** * Gets The camera contrast used on this material. */ get cameraContrast() { return this._imageProcessingConfiguration.contrast; } /** * Sets The camera contrast used on this material. */ set cameraContrast(value) { this._imageProcessingConfiguration.contrast = value; } /** * Gets the Color Grading 2D Lookup Texture. */ get cameraColorGradingTexture() { return this._imageProcessingConfiguration.colorGradingTexture; } /** * Sets the Color Grading 2D Lookup Texture. */ set cameraColorGradingTexture(value) { this._imageProcessingConfiguration.colorGradingTexture = value; } /** * 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 cameraColorCurves() { return this._imageProcessingConfiguration.colorCurves; } /** * The color grading curves provide additional color adjustment 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 cameraColorCurves(value) { this._imageProcessingConfiguration.colorCurves = value; } }; } __name(ImageProcessingMixin, "ImageProcessingMixin"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/standardMaterial.js init_tslib_es6(); init_decorators(); init_smartArray(); init_scene(); init_math_color(); init_buffer(); init_imageProcessingConfiguration(); init_typeStore(); init_materialFlags(); init_effectFallbacks(); init_clipPlaneMaterialHelper(); init_materialHelper_functions(); init_decorators_serialization(); var onCreatedEffectParameters = { effect: null, subMesh: null }; var StandardMaterialDefinesBase = class extends UVDefinesMixin(MaterialDefines) { static { __name(this, "StandardMaterialDefinesBase"); } }; var StandardMaterialDefines = class extends ImageProcessingDefinesMixin(StandardMaterialDefinesBase) { static { __name(this, "StandardMaterialDefines"); } /** * Initializes the Standard Material defines. * @param externalProperties The external properties */ constructor(externalProperties) { super(externalProperties); this.DIFFUSE = false; this.DIFFUSEDIRECTUV = 0; this.BAKED_VERTEX_ANIMATION_TEXTURE = false; this.AMBIENT = false; this.AMBIENTDIRECTUV = 0; this.OPACITY = false; this.OPACITYDIRECTUV = 0; this.OPACITYRGB = false; this.REFLECTION = false; this.EMISSIVE = false; this.EMISSIVEDIRECTUV = 0; this.SPECULAR = false; this.SPECULARDIRECTUV = 0; this.BUMP = false; this.BUMPDIRECTUV = 0; this.PARALLAX = false; this.PARALLAX_RHS = false; this.PARALLAXOCCLUSION = false; this.SPECULAROVERALPHA = false; this.CLIPPLANE = false; this.CLIPPLANE2 = false; this.CLIPPLANE3 = false; this.CLIPPLANE4 = false; this.CLIPPLANE5 = false; this.CLIPPLANE6 = false; this.ALPHATEST = false; this.DEPTHPREPASS = false; this.ALPHAFROMDIFFUSE = false; this.POINTSIZE = false; this.FOG = false; this.SPECULARTERM = false; this.DIFFUSEFRESNEL = false; this.OPACITYFRESNEL = false; this.REFLECTIONFRESNEL = false; this.REFRACTIONFRESNEL = false; this.EMISSIVEFRESNEL = false; this.FRESNEL = false; this.NORMAL = false; this.TANGENT = false; this.VERTEXCOLOR = false; this.VERTEXALPHA = false; this.NUM_BONE_INFLUENCERS = 0; this.BonesPerMesh = 0; this.BONETEXTURE = false; this.BONES_VELOCITY_ENABLED = false; this.INSTANCES = false; this.THIN_INSTANCES = false; this.INSTANCESCOLOR = false; this.GLOSSINESS = false; this.ROUGHNESS = false; this.EMISSIVEASILLUMINATION = false; this.LINKEMISSIVEWITHDIFFUSE = false; this.REFLECTIONFRESNELFROMSPECULAR = false; this.LIGHTMAP = false; this.LIGHTMAPDIRECTUV = 0; this.OBJECTSPACE_NORMALMAP = false; this.USELIGHTMAPASSHADOWMAP = false; this.REFLECTIONMAP_3D = false; this.REFLECTIONMAP_SPHERICAL = false; this.REFLECTIONMAP_PLANAR = false; this.REFLECTIONMAP_CUBIC = false; this.USE_LOCAL_REFLECTIONMAP_CUBIC = false; this.USE_LOCAL_REFRACTIONMAP_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.REFLECTIONMAP_OPPOSITEZ = false; this.INVERTCUBICMAP = false; this.LOGARITHMICDEPTH = false; this.REFRACTION = false; this.REFRACTIONMAP_3D = false; this.REFLECTIONOVERALPHA = false; this.TWOSIDEDLIGHTING = false; this.SHADOWFLOAT = false; this.MORPHTARGETS = false; this.MORPHTARGETS_POSITION = false; this.MORPHTARGETS_NORMAL = false; this.MORPHTARGETS_TANGENT = false; this.MORPHTARGETS_UV = false; this.MORPHTARGETS_UV2 = false; this.MORPHTARGETS_COLOR = false; this.MORPHTARGETTEXTURE_HASPOSITIONS = false; this.MORPHTARGETTEXTURE_HASNORMALS = false; this.MORPHTARGETTEXTURE_HASTANGENTS = false; this.MORPHTARGETTEXTURE_HASUVS = false; this.MORPHTARGETTEXTURE_HASUV2S = false; this.MORPHTARGETTEXTURE_HASCOLORS = false; this.NUM_MORPH_INFLUENCERS = 0; this.MORPHTARGETS_TEXTURE = false; this.NONUNIFORMSCALING = false; this.PREMULTIPLYALPHA = false; this.ALPHATEST_AFTERALLALPHACOMPUTATIONS = false; this.ALPHABLEND = true; this.PREPASS = false; this.PREPASS_COLOR = false; this.PREPASS_COLOR_INDEX = -1; this.PREPASS_IRRADIANCE = false; this.PREPASS_IRRADIANCE_INDEX = -1; this.PREPASS_ALBEDO = false; this.PREPASS_ALBEDO_INDEX = -1; this.PREPASS_ALBEDO_SQRT = false; this.PREPASS_ALBEDO_SQRT_INDEX = -1; this.PREPASS_DEPTH = false; this.PREPASS_DEPTH_INDEX = -1; this.PREPASS_SCREENSPACE_DEPTH = false; this.PREPASS_SCREENSPACE_DEPTH_INDEX = -1; this.PREPASS_NORMALIZED_VIEW_DEPTH = false; this.PREPASS_NORMALIZED_VIEW_DEPTH_INDEX = -1; this.PREPASS_NORMAL = false; this.PREPASS_NORMAL_INDEX = -1; this.PREPASS_NORMAL_WORLDSPACE = false; this.PREPASS_WORLD_NORMAL = false; this.PREPASS_WORLD_NORMAL_INDEX = -1; this.PREPASS_POSITION = false; this.PREPASS_POSITION_INDEX = -1; this.PREPASS_LOCAL_POSITION = false; this.PREPASS_LOCAL_POSITION_INDEX = -1; this.PREPASS_VELOCITY = false; this.PREPASS_VELOCITY_INDEX = -1; this.PREPASS_VELOCITY_LINEAR = false; this.PREPASS_VELOCITY_LINEAR_INDEX = -1; this.PREPASS_REFLECTIVITY = false; this.PREPASS_REFLECTIVITY_INDEX = -1; this.SCENE_MRT_COUNT = 0; this.RGBDLIGHTMAP = false; this.RGBDREFLECTION = false; this.RGBDREFRACTION = false; this.MULTIVIEW = false; this.ORDER_INDEPENDENT_TRANSPARENCY = false; this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS = false; this.CAMERA_ORTHOGRAPHIC = false; this.CAMERA_PERSPECTIVE = false; this.AREALIGHTSUPPORTED = true; this.USE_VERTEX_PULLING = false; this.CLUSTLIGHT_SLICES = 0; this.CLUSTLIGHT_BATCH = 0; this.IS_REFLECTION_LINEAR = false; this.IS_REFRACTION_LINEAR = false; this.DECAL_AFTER_DETAIL = false; this.rebuild(); } }; var StandardMaterialBase = class extends ImageProcessingMixin(PushMaterial) { static { __name(this, "StandardMaterialBase"); } }; var StandardMaterial = class _StandardMaterial extends StandardMaterialBase { static { __name(this, "StandardMaterial"); } /** * Can this material render to prepass */ get isPrePassCapable() { return !this.disableDepthWrite; } /** * Can this material render to several textures at once */ get canRenderToMRT() { return true; } /** * Instantiates a new standard material. * This is the default material used in Babylon. It is the best trade off between quality * and performances. * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/materials_introduction * @param name Define the name of the material in the scene * @param scene Define the scene the material belong to * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false */ constructor(name260, scene, forceGLSL = false) { super(name260, scene, void 0, forceGLSL || _StandardMaterial.ForceGLSL); this._diffuseTexture = null; this._ambientTexture = null; this._opacityTexture = null; this._reflectionTexture = null; this._emissiveTexture = null; this._specularTexture = null; this._bumpTexture = null; this._lightmapTexture = null; this._refractionTexture = null; this.ambientColor = new Color3(0, 0, 0); this.diffuseColor = new Color3(1, 1, 1); this.specularColor = new Color3(1, 1, 1); this.emissiveColor = new Color3(0, 0, 0); this.specularPower = 64; this._useAlphaFromDiffuseTexture = false; this._useEmissiveAsIllumination = false; this._linkEmissiveWithDiffuse = false; this._useSpecularOverAlpha = false; this._useReflectionOverAlpha = false; this._disableLighting = false; this._useObjectSpaceNormalMap = false; this._useParallax = false; this._useParallaxOcclusion = false; this.parallaxScaleBias = 0.05; this._roughness = 0; this.indexOfRefraction = 0.98; this.invertRefractionY = true; this.alphaCutOff = 0.4; this._useLightmapAsShadowmap = false; this._useReflectionFresnelFromSpecular = false; this._useGlossinessFromSpecularMapAlpha = false; this._maxSimultaneousLights = 4; this._invertNormalMapX = false; this._invertNormalMapY = false; this._twoSidedLighting = false; this._applyDecalMapAfterDetailMap = false; this._shadersLoaded = false; this._renderTargets = new SmartArray(16); this._globalAmbientColor = new Color3(0, 0, 0); this._cacheHasRenderTargetTextures = false; this.detailMap = new DetailMapConfiguration(this); this._attachImageProcessingConfiguration(null); this.prePassConfiguration = new PrePassConfiguration(); this.getRenderTargetTextures = () => { this._renderTargets.reset(); if (_StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) { this._renderTargets.push(this._reflectionTexture); } if (_StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) { this._renderTargets.push(this._refractionTexture); } this._eventInfo.renderTargets = this._renderTargets; this._callbackPluginEventFillRenderTargetTextures(this._eventInfo); return this._renderTargets; }; } /** * Gets a boolean indicating that current material needs to register RTT */ get hasRenderTargetTextures() { if (_StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) { return true; } if (_StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) { return true; } return this._cacheHasRenderTargetTextures; } /** * Gets the current class name of the material e.g. "StandardMaterial" * Mainly use in serialization. * @returns the class name */ getClassName() { return "StandardMaterial"; } /** * Specifies if the material will require alpha blending * @returns a boolean specifying if alpha blending is needed */ needAlphaBlending() { if (this._hasTransparencyMode) { return this._transparencyModeIsBlend; } if (this._disableAlphaBlending) { return false; } return this.alpha < 1 || this._opacityTexture != null || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled; } /** * Specifies if this material should be rendered in alpha test mode * @returns a boolean specifying if an alpha test is needed. */ needAlphaTesting() { if (this._hasTransparencyMode) { return this._transparencyModeIsTest; } return this._hasAlphaChannel() && (this._transparencyMode == null || this._transparencyMode === Material.MATERIAL_ALPHATEST); } /** * @returns whether or not the alpha value of the diffuse texture should be used for alpha blending. */ _shouldUseAlphaFromDiffuseTexture() { return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture && this._transparencyMode !== Material.MATERIAL_OPAQUE; } /** * @returns whether or not there is a usable alpha channel for transparency. */ _hasAlphaChannel() { return this._diffuseTexture != null && this._diffuseTexture.hasAlpha || this._opacityTexture != null; } /** * Get the texture used for alpha test purpose. * @returns the diffuse texture in case of the standard material. */ getAlphaTestTexture() { return this._diffuseTexture; } /** * 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 */ isReadyForSubMesh(mesh, subMesh, useInstances = false) { if (!this._uniformBufferLayoutBuilt) { this.buildUniformLayout(); } const drawWrapper = subMesh._drawWrapper; if (drawWrapper.effect && this.isFrozen) { if (drawWrapper._wasPreviouslyReady && drawWrapper._wasPreviouslyUsingInstances === useInstances) { return true; } } if (!subMesh.materialDefines) { this._callbackPluginEventGeneric(4, this._eventInfo); subMesh.materialDefines = new StandardMaterialDefines(this._eventInfo.defineNames); } const scene = this.getScene(); const defines = subMesh.materialDefines; if (this._isReadyForSubMesh(subMesh)) { return true; } const engine = scene.getEngine(); defines._needNormals = PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting); PrepareDefinesForMultiview(scene, defines); const oit = this.needAlphaBlendingForMesh(mesh) && this.getScene().useOrderIndependentTransparency; PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT && !oit); PrepareDefinesForOIT(scene, defines, oit); MaterialHelperGeometryRendering.PrepareDefines(engine.currentRenderPassId, mesh, defines); if (defines._areTexturesDirty) { this._eventInfo.hasRenderTargetTextures = false; this._callbackPluginEventHasRenderTargetTextures(this._eventInfo); this._cacheHasRenderTargetTextures = this._eventInfo.hasRenderTargetTextures; defines._needUVs = false; for (let i = 1; i <= 6; ++i) { defines["MAINUV" + i] = false; } if (scene.texturesEnabled) { defines.DIFFUSEDIRECTUV = 0; defines.BUMPDIRECTUV = 0; defines.AMBIENTDIRECTUV = 0; defines.OPACITYDIRECTUV = 0; defines.EMISSIVEDIRECTUV = 0; defines.SPECULARDIRECTUV = 0; defines.LIGHTMAPDIRECTUV = 0; if (this._diffuseTexture && _StandardMaterial.DiffuseTextureEnabled) { if (!this._diffuseTexture.isReadyOrNotBlocking()) { return false; } else { PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE"); } } else { defines.DIFFUSE = false; } if (this._ambientTexture && _StandardMaterial.AmbientTextureEnabled) { if (!this._ambientTexture.isReadyOrNotBlocking()) { return false; } else { PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT"); } } else { defines.AMBIENT = false; } if (this._opacityTexture && _StandardMaterial.OpacityTextureEnabled) { if (!this._opacityTexture.isReadyOrNotBlocking()) { return false; } else { PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY"); defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB; } } else { defines.OPACITY = false; } if (this._reflectionTexture && _StandardMaterial.ReflectionTextureEnabled) { defines.ROUGHNESS = this._roughness > 0; defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha; } else { defines.ROUGHNESS = false; defines.REFLECTIONOVERALPHA = false; } if (!PrepareDefinesForIBL(scene, this._reflectionTexture, defines)) { return false; } if (this._emissiveTexture && _StandardMaterial.EmissiveTextureEnabled) { if (!this._emissiveTexture.isReadyOrNotBlocking()) { return false; } else { PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE"); } } else { defines.EMISSIVE = false; } if (this._lightmapTexture && _StandardMaterial.LightmapTextureEnabled) { if (!this._lightmapTexture.isReadyOrNotBlocking()) { return false; } else { PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP"); defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap; defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD; } } else { defines.LIGHTMAP = false; } if (this._specularTexture && _StandardMaterial.SpecularTextureEnabled) { if (!this._specularTexture.isReadyOrNotBlocking()) { return false; } else { PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR"); defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha; } } else { defines.SPECULAR = false; } if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && _StandardMaterial.BumpTextureEnabled) { if (!this._bumpTexture.isReady()) { return false; } else { PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP"); defines.PARALLAX = this._useParallax; defines.PARALLAX_RHS = scene.useRightHandedSystem; defines.PARALLAXOCCLUSION = this._useParallaxOcclusion; } defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap; } else { defines.BUMP = false; defines.PARALLAX = false; defines.PARALLAX_RHS = false; defines.PARALLAXOCCLUSION = false; } if (this._refractionTexture && _StandardMaterial.RefractionTextureEnabled) { if (!this._refractionTexture.isReadyOrNotBlocking()) { return false; } else { defines._needUVs = true; defines.REFRACTION = true; defines.REFRACTIONMAP_3D = this._refractionTexture.isCube; defines.RGBDREFRACTION = this._refractionTexture.isRGBD; defines.USE_LOCAL_REFRACTIONMAP_CUBIC = this._refractionTexture.boundingBoxSize ? true : false; } } else { defines.REFRACTION = false; } defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting; } else { defines.DIFFUSE = false; defines.AMBIENT = false; defines.OPACITY = false; defines.REFLECTION = false; defines.EMISSIVE = false; defines.LIGHTMAP = false; defines.BUMP = false; defines.REFRACTION = false; } defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture(); defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination; defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse; defines.SPECULAROVERALPHA = this._useSpecularOverAlpha; defines.PREMULTIPLYALPHA = this.alphaMode === 7 || this.alphaMode === 8; defines.ALPHATEST_AFTERALLALPHACOMPUTATIONS = this.transparencyMode !== null; defines.ALPHABLEND = this.transparencyMode === null || this.needAlphaBlendingForMesh(mesh); } this._eventInfo.isReadyForSubMesh = true; this._eventInfo.defines = defines; this._eventInfo.subMesh = subMesh; this._callbackPluginEventIsReadyForSubMesh(this._eventInfo); if (!this._eventInfo.isReadyForSubMesh) { return false; } if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) { if (!this._imageProcessingConfiguration.isReady()) { return false; } this._imageProcessingConfiguration.prepareDefines(defines); defines.IS_REFLECTION_LINEAR = this.reflectionTexture != null && !this.reflectionTexture.gammaSpace; defines.IS_REFRACTION_LINEAR = this.refractionTexture != null && !this.refractionTexture.gammaSpace; } if (defines._areFresnelDirty) { if (_StandardMaterial.FresnelEnabled) { if (this._diffuseFresnelParameters || this._opacityFresnelParameters || this._emissiveFresnelParameters || this._refractionFresnelParameters || this._reflectionFresnelParameters) { defines.DIFFUSEFRESNEL = this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled; defines.OPACITYFRESNEL = this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled; defines.REFLECTIONFRESNEL = this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled; defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular; defines.REFRACTIONFRESNEL = this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled; defines.EMISSIVEFRESNEL = this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled; defines._needNormals = true; defines.FRESNEL = true; } } else { defines.FRESNEL = false; } } if (defines["AREALIGHTUSED"] || defines["CLUSTLIGHT_BATCH"]) { for (let index = 0; index < mesh.lightSources.length; index++) { if (!mesh.lightSources[index]._isReady()) { return false; } } } PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this.needAlphaTestingForMesh(mesh), defines, this._applyDecalMapAfterDetailMap, this._useVertexPulling, subMesh.getRenderingMesh(), this._isVertexOutputInvariant); PrepareDefinesForFrameBoundValues(scene, engine, this, defines, useInstances, null, subMesh.getRenderingMesh().hasThinInstances); this._eventInfo.defines = defines; this._eventInfo.mesh = mesh; this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo); PrepareDefinesForAttributes(mesh, defines, true, true, true); this._callbackPluginEventPrepareDefines(this._eventInfo); let forceWasNotReadyPreviously = false; if (defines.isDirty) { const lightDisposed = defines._areLightsDisposed; defines.markAsProcessed(); const fallbacks = new EffectFallbacks(); if (defines.REFLECTION) { fallbacks.addFallback(0, "REFLECTION"); } if (defines.SPECULAR) { fallbacks.addFallback(0, "SPECULAR"); } if (defines.BUMP) { fallbacks.addFallback(0, "BUMP"); } if (defines.PARALLAX) { fallbacks.addFallback(1, "PARALLAX"); } if (defines.PARALLAX_RHS) { fallbacks.addFallback(1, "PARALLAX_RHS"); } if (defines.PARALLAXOCCLUSION) { fallbacks.addFallback(0, "PARALLAXOCCLUSION"); } if (defines.SPECULAROVERALPHA) { fallbacks.addFallback(0, "SPECULAROVERALPHA"); } if (defines.FOG) { fallbacks.addFallback(1, "FOG"); } if (defines.POINTSIZE) { fallbacks.addFallback(0, "POINTSIZE"); } if (defines.LOGARITHMICDEPTH) { fallbacks.addFallback(0, "LOGARITHMICDEPTH"); } HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights); if (defines.SPECULARTERM) { fallbacks.addFallback(0, "SPECULARTERM"); } if (defines.DIFFUSEFRESNEL) { fallbacks.addFallback(1, "DIFFUSEFRESNEL"); } if (defines.OPACITYFRESNEL) { fallbacks.addFallback(2, "OPACITYFRESNEL"); } if (defines.REFLECTIONFRESNEL) { fallbacks.addFallback(3, "REFLECTIONFRESNEL"); } if (defines.EMISSIVEFRESNEL) { fallbacks.addFallback(4, "EMISSIVEFRESNEL"); } if (defines.FRESNEL) { fallbacks.addFallback(4, "FRESNEL"); } if (defines.MULTIVIEW) { fallbacks.addFallback(0, "MULTIVIEW"); } const attribs = [VertexBuffer.PositionKind]; if (defines.NORMAL) { attribs.push(VertexBuffer.NormalKind); } if (defines.TANGENT) { attribs.push(VertexBuffer.TangentKind); } for (let i = 1; i <= 6; ++i) { if (defines["UV" + i]) { attribs.push(`uv${i === 1 ? "" : i}`); } } if (defines.VERTEXCOLOR) { attribs.push(VertexBuffer.ColorKind); } PrepareAttributesForBones(attribs, mesh, defines, fallbacks); PrepareAttributesForInstances(attribs, defines); PrepareAttributesForMorphTargets(attribs, mesh, defines); PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines); let shaderName = "default"; const uniforms = [ "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "visibility", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos", "mBones", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor", "vRefractionPosition", "vRefractionSize", "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff", "boneTextureWidth", "morphTargetTextureInfo", "morphTargetTextureIndices", "cameraInfo" ]; const samplers = [ "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler", "boneSampler", "morphTargets", "oitDepthSampler", "oitFrontColorSampler", "areaLightsLTC1Sampler", "areaLightsLTC2Sampler" ]; PrepareUniformsAndSamplersForIBL(uniforms, samplers, false); const uniformBuffers = ["Material", "Scene", "Mesh"]; const indexParameters = { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }; this._eventInfo.fallbacks = fallbacks; this._eventInfo.fallbackRank = 0; this._eventInfo.defines = defines; this._eventInfo.uniforms = uniforms; this._eventInfo.attributes = attribs; this._eventInfo.samplers = samplers; this._eventInfo.uniformBuffersNames = uniformBuffers; this._eventInfo.customCode = void 0; this._eventInfo.mesh = mesh; this._eventInfo.indexParameters = indexParameters; this._callbackPluginEventGeneric(128, this._eventInfo); MaterialHelperGeometryRendering.AddUniformsAndSamplers(uniforms, samplers); PrePassConfiguration.AddUniforms(uniforms); PrePassConfiguration.AddSamplers(samplers); if (ImageProcessingConfiguration) { ImageProcessingConfiguration.PrepareUniforms(uniforms, defines); ImageProcessingConfiguration.PrepareSamplers(samplers, defines); } PrepareUniformsAndSamplersList({ uniformsNames: uniforms, uniformBuffersNames: uniformBuffers, samplers, defines, maxSimultaneousLights: this._maxSimultaneousLights }); AddClipPlaneUniforms(uniforms); const csnrOptions = {}; if (this.customShaderNameResolve) { shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions); } const join = defines.toString(); const previousEffect = subMesh.effect; let effect = scene.getEngine().createEffect(shaderName, { attributes: attribs, uniformsNames: uniforms, uniformBuffersNames: uniformBuffers, samplers, defines: join, fallbacks, onCompiled: this.onCompiled, onError: this.onError, indexParameters, processFinalCode: csnrOptions.processFinalCode, processCodeAfterIncludes: this._eventInfo.customCode, multiTarget: defines.PREPASS, shaderLanguage: this._shaderLanguage, extraInitializationsAsync: this._shadersLoaded ? void 0 : async () => { if (this._shaderLanguage === 1) { await Promise.all([Promise.resolve().then(() => (init_default_vertex(), default_vertex_exports)), Promise.resolve().then(() => (init_default_fragment(), default_fragment_exports))]); } else { await Promise.all([Promise.resolve().then(() => (init_default_vertex2(), default_vertex_exports2)), Promise.resolve().then(() => (init_default_fragment2(), default_fragment_exports2))]); } this._shadersLoaded = true; } }, engine); this._eventInfo.customCode = void 0; if (effect) { if (this._onEffectCreatedObservable) { onCreatedEffectParameters.effect = effect; onCreatedEffectParameters.subMesh = subMesh; this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters); } if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) { effect = previousEffect; defines.markAsUnprocessed(); forceWasNotReadyPreviously = this.isFrozen; if (lightDisposed) { defines._areLightsDisposed = true; return false; } } else { scene.resetCachedMaterial(); subMesh.setEffect(effect, defines, this._materialContext); } } } if (!subMesh.effect || !subMesh.effect.isReady()) { return false; } defines._renderId = scene.getRenderId(); drawWrapper._wasPreviouslyReady = forceWasNotReadyPreviously ? false : true; drawWrapper._wasPreviouslyUsingInstances = useInstances; this._checkScenePerformancePriority(); return true; } /** * Builds the material UBO layouts. * Used internally during the effect preparation. */ buildUniformLayout() { const ubo = this._uniformBuffer; ubo.addUniform("diffuseLeftColor", 4); ubo.addUniform("diffuseRightColor", 4); ubo.addUniform("opacityParts", 4); ubo.addUniform("reflectionLeftColor", 4); ubo.addUniform("reflectionRightColor", 4); ubo.addUniform("refractionLeftColor", 4); ubo.addUniform("refractionRightColor", 4); ubo.addUniform("emissiveLeftColor", 4); ubo.addUniform("emissiveRightColor", 4); ubo.addUniform("vDiffuseInfos", 2); ubo.addUniform("vAmbientInfos", 2); ubo.addUniform("vOpacityInfos", 2); ubo.addUniform("vEmissiveInfos", 2); ubo.addUniform("vLightmapInfos", 2); ubo.addUniform("vSpecularInfos", 2); ubo.addUniform("vBumpInfos", 3); ubo.addUniform("diffuseMatrix", 16); ubo.addUniform("ambientMatrix", 16); ubo.addUniform("opacityMatrix", 16); ubo.addUniform("emissiveMatrix", 16); ubo.addUniform("lightmapMatrix", 16); ubo.addUniform("specularMatrix", 16); ubo.addUniform("bumpMatrix", 16); ubo.addUniform("vTangentSpaceParams", 2); ubo.addUniform("pointSize", 1); ubo.addUniform("alphaCutOff", 1); ubo.addUniform("refractionMatrix", 16); ubo.addUniform("vRefractionInfos", 4); ubo.addUniform("vRefractionPosition", 3); ubo.addUniform("vRefractionSize", 3); ubo.addUniform("vSpecularColor", 4); ubo.addUniform("vEmissiveColor", 3); ubo.addUniform("vDiffuseColor", 4); ubo.addUniform("vAmbientColor", 3); ubo.addUniform("cameraInfo", 4); PrepareUniformLayoutForIBL(ubo, false, true); super.buildUniformLayout(); } /** * 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 */ bindForSubMesh(world, mesh, subMesh) { const scene = this.getScene(); const defines = subMesh.materialDefines; if (!defines) { return; } const effect = subMesh.effect; if (!effect) { return; } this._activeEffect = effect; mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); mesh.transferToEffect(world); this._uniformBuffer.bindToEffect(effect, "Material"); this.prePassConfiguration.bindForSubMesh(this._activeEffect, scene, mesh, world, this.isFrozen); MaterialHelperGeometryRendering.Bind(scene.getEngine().currentRenderPassId, this._activeEffect, mesh, world, this); const camera = scene.activeCamera; if (camera) { this._uniformBuffer.updateFloat4("cameraInfo", camera.minZ, camera.maxZ, 0, 0); } else { this._uniformBuffer.updateFloat4("cameraInfo", 0, 0, 0, 0); } this._eventInfo.subMesh = subMesh; this._callbackPluginEventHardBindForSubMesh(this._eventInfo); if (defines.OBJECTSPACE_NORMALMAP) { world.toNormalMatrix(this._normalMatrix); this.bindOnlyNormalMatrix(this._normalMatrix); } const mustRebind = this._mustRebind(scene, effect, subMesh, mesh.visibility); BindBonesParameters(mesh, effect); const ubo = this._uniformBuffer; if (mustRebind) { this.bindViewProjection(effect); if (!ubo.useUbo || !this.isFrozen || !ubo.isSync || subMesh._drawWrapper._forceRebindOnNextCall) { if (_StandardMaterial.FresnelEnabled && defines.FRESNEL) { if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) { ubo.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power); ubo.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias); } if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) { ubo.updateColor4("opacityParts", new Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power); } if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) { ubo.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power); ubo.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias); } if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) { ubo.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power); ubo.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias); } if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) { ubo.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power); ubo.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias); } } if (scene.texturesEnabled) { if (this._diffuseTexture && _StandardMaterial.DiffuseTextureEnabled) { ubo.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level); BindTextureMatrix(this._diffuseTexture, ubo, "diffuse"); } if (this._ambientTexture && _StandardMaterial.AmbientTextureEnabled) { ubo.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level); BindTextureMatrix(this._ambientTexture, ubo, "ambient"); } if (this._opacityTexture && _StandardMaterial.OpacityTextureEnabled) { ubo.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level); BindTextureMatrix(this._opacityTexture, ubo, "opacity"); } if (this._hasAlphaChannel()) { ubo.updateFloat("alphaCutOff", this.alphaCutOff); } BindIBLParameters(scene, defines, ubo, Color3.White(), this._reflectionTexture, false, false, true, false, false, false, this.roughness); if (!this._reflectionTexture || !_StandardMaterial.ReflectionTextureEnabled) { ubo.updateFloat2("vReflectionInfos", 0, this.roughness); } if (this._emissiveTexture && _StandardMaterial.EmissiveTextureEnabled) { ubo.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level); BindTextureMatrix(this._emissiveTexture, ubo, "emissive"); } if (this._lightmapTexture && _StandardMaterial.LightmapTextureEnabled) { ubo.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level); BindTextureMatrix(this._lightmapTexture, ubo, "lightmap"); } if (this._specularTexture && _StandardMaterial.SpecularTextureEnabled) { ubo.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level); BindTextureMatrix(this._specularTexture, ubo, "specular"); } if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && _StandardMaterial.BumpTextureEnabled) { ubo.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1 / this._bumpTexture.level, this.parallaxScaleBias); BindTextureMatrix(this._bumpTexture, ubo, "bump"); if (scene._mirroredCameraPosition) { ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1 : -1, this._invertNormalMapY ? 1 : -1); } else { ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1 : 1, this._invertNormalMapY ? -1 : 1); } } if (this._refractionTexture && _StandardMaterial.RefractionTextureEnabled) { let depth = 1; if (!this._refractionTexture.isCube) { ubo.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix()); if (this._refractionTexture.depth) { depth = this._refractionTexture.depth; } } ubo.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1); if (this._refractionTexture.boundingBoxSize) { const cubeTexture = this._refractionTexture; ubo.updateVector3("vRefractionPosition", cubeTexture.boundingBoxPosition); ubo.updateVector3("vRefractionSize", cubeTexture.boundingBoxSize); } } } if (this.pointsCloud) { ubo.updateFloat("pointSize", this.pointSize); } ubo.updateColor4("vSpecularColor", this.specularColor, this.specularPower); ubo.updateColor3("vEmissiveColor", _StandardMaterial.EmissiveTextureEnabled ? this.emissiveColor : Color3.BlackReadOnly); ubo.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha); scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor); ubo.updateColor3("vAmbientColor", this._globalAmbientColor); } if (scene.texturesEnabled) { if (this._diffuseTexture && _StandardMaterial.DiffuseTextureEnabled) { effect.setTexture("diffuseSampler", this._diffuseTexture); } if (this._ambientTexture && _StandardMaterial.AmbientTextureEnabled) { effect.setTexture("ambientSampler", this._ambientTexture); } if (this._opacityTexture && _StandardMaterial.OpacityTextureEnabled) { effect.setTexture("opacitySampler", this._opacityTexture); } if (this._reflectionTexture && _StandardMaterial.ReflectionTextureEnabled) { if (this._reflectionTexture.isCube) { effect.setTexture("reflectionCubeSampler", this._reflectionTexture); } else { effect.setTexture("reflection2DSampler", this._reflectionTexture); } } if (this._emissiveTexture && _StandardMaterial.EmissiveTextureEnabled) { effect.setTexture("emissiveSampler", this._emissiveTexture); } if (this._lightmapTexture && _StandardMaterial.LightmapTextureEnabled) { effect.setTexture("lightmapSampler", this._lightmapTexture); } if (this._specularTexture && _StandardMaterial.SpecularTextureEnabled) { effect.setTexture("specularSampler", this._specularTexture); } if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && _StandardMaterial.BumpTextureEnabled) { effect.setTexture("bumpSampler", this._bumpTexture); } if (this._refractionTexture && _StandardMaterial.RefractionTextureEnabled) { if (this._refractionTexture.isCube) { effect.setTexture("refractionCubeSampler", this._refractionTexture); } else { effect.setTexture("refraction2DSampler", this._refractionTexture); } } } if (this.getScene().useOrderIndependentTransparency && this.needAlphaBlendingForMesh(mesh)) { this.getScene().depthPeelingRenderer.bind(effect); } this._eventInfo.subMesh = subMesh; this._callbackPluginEventBindForSubMesh(this._eventInfo); BindClipPlane(effect, this, scene); this.bindEyePosition(effect); } else if (scene.getEngine()._features.needToAlwaysBindUniformBuffers) { this._needToBindSceneUbo = true; } if (mustRebind || !this.isFrozen) { if (scene.lightsEnabled && !this._disableLighting) { BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights); } if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture || mesh.receiveShadows || defines.PREPASS || defines["CLUSTLIGHT_BATCH"]) { this.bindView(effect); } BindFogParameters(scene, mesh, effect); if (defines.NUM_MORPH_INFLUENCERS) { BindMorphTargetParameters(mesh, effect); } if (defines.BAKED_VERTEX_ANIMATION_TEXTURE) { mesh.bakedVertexAnimationManager?.bind(effect, defines.INSTANCES); } if (this.useLogarithmicDepth) { BindLogDepth(defines, effect, scene); } if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) { this._imageProcessingConfiguration.bind(this._activeEffect); } } this._afterBind(mesh, this._activeEffect, subMesh); ubo.update(); } /** * Get the list of animatables in the material. * @returns the list of animatables object used in the material */ getAnimatables() { const results = super.getAnimatables(); if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) { results.push(this._diffuseTexture); } 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._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) { results.push(this._specularTexture); } 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); } if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) { results.push(this._refractionTexture); } return results; } /** * Gets the active textures from the material * @returns an array of textures */ getActiveTextures() { const activeTextures = super.getActiveTextures(); if (this._diffuseTexture) { activeTextures.push(this._diffuseTexture); } 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._specularTexture) { activeTextures.push(this._specularTexture); } if (this._bumpTexture) { activeTextures.push(this._bumpTexture); } if (this._lightmapTexture) { activeTextures.push(this._lightmapTexture); } if (this._refractionTexture) { activeTextures.push(this._refractionTexture); } return activeTextures; } /** * 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 */ hasTexture(texture) { if (super.hasTexture(texture)) { return true; } if (this._diffuseTexture === texture) { return true; } if (this._ambientTexture === texture) { return true; } if (this._opacityTexture === texture) { return true; } if (this._reflectionTexture === texture) { return true; } if (this._emissiveTexture === texture) { return true; } if (this._specularTexture === texture) { return true; } if (this._bumpTexture === texture) { return true; } if (this._lightmapTexture === texture) { return true; } if (this._refractionTexture === 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 */ dispose(forceDisposeEffect, forceDisposeTextures) { if (forceDisposeTextures) { this._diffuseTexture?.dispose(); this._ambientTexture?.dispose(); this._opacityTexture?.dispose(); this._reflectionTexture?.dispose(); this._emissiveTexture?.dispose(); this._specularTexture?.dispose(); this._bumpTexture?.dispose(); this._lightmapTexture?.dispose(); this._refractionTexture?.dispose(); } if (this._imageProcessingConfiguration && this._imageProcessingObserver) { this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); } super.dispose(forceDisposeEffect, forceDisposeTextures); } /** * Makes a duplicate of the material, and gives it a new name * @param name defines the new name for the duplicated material * @param cloneTexturesOnlyOnce - if a texture is used in more than one channel (e.g diffuse and opacity), only clone it once and reuse it on the other channels. Default false. * @param rootUrl defines the root URL to use to load textures * @returns the cloned material */ clone(name260, cloneTexturesOnlyOnce = true, rootUrl = "") { const result = SerializationHelper.Clone(() => new _StandardMaterial(name260, this.getScene()), this, { cloneTexturesOnlyOnce }); result.name = name260; result.id = name260; this.stencil.copyTo(result.stencil); this._clonePlugins(result, rootUrl); return result; } /** * Creates a standard 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 standard material */ static Parse(source, scene, rootUrl) { const material = SerializationHelper.Parse(() => new _StandardMaterial(source.name, scene), source, scene, rootUrl); if (source.stencil) { material.stencil.parse(source.stencil, scene, rootUrl); } Material._ParsePlugins(source, material, scene, rootUrl); return material; } // Flags used to enable or disable a type of texture for all Standard Materials /** * Are diffuse textures enabled in the application. */ static get DiffuseTextureEnabled() { return MaterialFlags.DiffuseTextureEnabled; } static set DiffuseTextureEnabled(value) { MaterialFlags.DiffuseTextureEnabled = value; } /** * Are detail textures enabled in the application. */ static get DetailTextureEnabled() { return MaterialFlags.DetailTextureEnabled; } static set DetailTextureEnabled(value) { MaterialFlags.DetailTextureEnabled = value; } /** * Are ambient textures enabled in the application. */ static get AmbientTextureEnabled() { return MaterialFlags.AmbientTextureEnabled; } static set AmbientTextureEnabled(value) { MaterialFlags.AmbientTextureEnabled = value; } /** * Are opacity textures enabled in the application. */ static get OpacityTextureEnabled() { return MaterialFlags.OpacityTextureEnabled; } static set OpacityTextureEnabled(value) { MaterialFlags.OpacityTextureEnabled = value; } /** * Are reflection textures enabled in the application. */ static get ReflectionTextureEnabled() { return MaterialFlags.ReflectionTextureEnabled; } static set ReflectionTextureEnabled(value) { MaterialFlags.ReflectionTextureEnabled = value; } /** * Are emissive textures enabled in the application. */ static get EmissiveTextureEnabled() { return MaterialFlags.EmissiveTextureEnabled; } static set EmissiveTextureEnabled(value) { MaterialFlags.EmissiveTextureEnabled = value; } /** * Are specular textures enabled in the application. */ static get SpecularTextureEnabled() { return MaterialFlags.SpecularTextureEnabled; } static set SpecularTextureEnabled(value) { MaterialFlags.SpecularTextureEnabled = value; } /** * Are bump textures enabled in the application. */ static get BumpTextureEnabled() { return MaterialFlags.BumpTextureEnabled; } static set BumpTextureEnabled(value) { MaterialFlags.BumpTextureEnabled = value; } /** * Are lightmap textures enabled in the application. */ static get LightmapTextureEnabled() { return MaterialFlags.LightmapTextureEnabled; } static set LightmapTextureEnabled(value) { MaterialFlags.LightmapTextureEnabled = value; } /** * Are refraction textures enabled in the application. */ static get RefractionTextureEnabled() { return MaterialFlags.RefractionTextureEnabled; } static set RefractionTextureEnabled(value) { MaterialFlags.RefractionTextureEnabled = value; } /** * Are color grading textures enabled in the application. */ static get ColorGradingTextureEnabled() { return MaterialFlags.ColorGradingTextureEnabled; } static set ColorGradingTextureEnabled(value) { MaterialFlags.ColorGradingTextureEnabled = value; } /** * Are fresnels enabled in the application. */ static get FresnelEnabled() { return MaterialFlags.FresnelEnabled; } static set FresnelEnabled(value) { MaterialFlags.FresnelEnabled = value; } }; StandardMaterial.ForceGLSL = false; __decorate([ serializeAsTexture("diffuseTexture") ], StandardMaterial.prototype, "_diffuseTexture", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") ], StandardMaterial.prototype, "diffuseTexture", void 0); __decorate([ serializeAsTexture("ambientTexture") ], StandardMaterial.prototype, "_ambientTexture", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "ambientTexture", void 0); __decorate([ serializeAsTexture("opacityTexture") ], StandardMaterial.prototype, "_opacityTexture", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") ], StandardMaterial.prototype, "opacityTexture", void 0); __decorate([ serializeAsTexture("reflectionTexture") ], StandardMaterial.prototype, "_reflectionTexture", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "reflectionTexture", void 0); __decorate([ serializeAsTexture("emissiveTexture") ], StandardMaterial.prototype, "_emissiveTexture", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "emissiveTexture", void 0); __decorate([ serializeAsTexture("specularTexture") ], StandardMaterial.prototype, "_specularTexture", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "specularTexture", void 0); __decorate([ serializeAsTexture("bumpTexture") ], StandardMaterial.prototype, "_bumpTexture", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "bumpTexture", void 0); __decorate([ serializeAsTexture("lightmapTexture") ], StandardMaterial.prototype, "_lightmapTexture", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "lightmapTexture", void 0); __decorate([ serializeAsTexture("refractionTexture") ], StandardMaterial.prototype, "_refractionTexture", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "refractionTexture", void 0); __decorate([ serializeAsColor3("ambient") ], StandardMaterial.prototype, "ambientColor", void 0); __decorate([ serializeAsColor3("diffuse") ], StandardMaterial.prototype, "diffuseColor", void 0); __decorate([ serializeAsColor3("specular") ], StandardMaterial.prototype, "specularColor", void 0); __decorate([ serializeAsColor3("emissive") ], StandardMaterial.prototype, "emissiveColor", void 0); __decorate([ serialize() ], StandardMaterial.prototype, "specularPower", void 0); __decorate([ serialize("useAlphaFromDiffuseTexture") ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty") ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0); __decorate([ serialize("useEmissiveAsIllumination") ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0); __decorate([ serialize("linkEmissiveWithDiffuse") ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0); __decorate([ serialize("useSpecularOverAlpha") ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0); __decorate([ serialize("useReflectionOverAlpha") ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0); __decorate([ serialize("disableLighting") ], StandardMaterial.prototype, "_disableLighting", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsLightsDirty") ], StandardMaterial.prototype, "disableLighting", void 0); __decorate([ serialize("useObjectSpaceNormalMap") ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0); __decorate([ serialize("useParallax") ], StandardMaterial.prototype, "_useParallax", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useParallax", void 0); __decorate([ serialize("useParallaxOcclusion") ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useParallaxOcclusion", void 0); __decorate([ serialize() ], StandardMaterial.prototype, "parallaxScaleBias", void 0); __decorate([ serialize("roughness") ], StandardMaterial.prototype, "_roughness", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "roughness", void 0); __decorate([ serialize() ], StandardMaterial.prototype, "indexOfRefraction", void 0); __decorate([ serialize() ], StandardMaterial.prototype, "invertRefractionY", void 0); __decorate([ serialize() ], StandardMaterial.prototype, "alphaCutOff", void 0); __decorate([ serialize("useLightmapAsShadowmap") ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0); __decorate([ serializeAsFresnelParameters("diffuseFresnelParameters") ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsFresnelDirty") ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0); __decorate([ serializeAsFresnelParameters("opacityFresnelParameters") ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty") ], StandardMaterial.prototype, "opacityFresnelParameters", void 0); __decorate([ serializeAsFresnelParameters("reflectionFresnelParameters") ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsFresnelDirty") ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0); __decorate([ serializeAsFresnelParameters("refractionFresnelParameters") ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsFresnelDirty") ], StandardMaterial.prototype, "refractionFresnelParameters", void 0); __decorate([ serializeAsFresnelParameters("emissiveFresnelParameters") ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsFresnelDirty") ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0); __decorate([ serialize("useReflectionFresnelFromSpecular") ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsFresnelDirty") ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0); __decorate([ serialize("useGlossinessFromSpecularMapAlpha") ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0); __decorate([ serialize("maxSimultaneousLights") ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsLightsDirty") ], StandardMaterial.prototype, "maxSimultaneousLights", void 0); __decorate([ serialize("invertNormalMapX") ], StandardMaterial.prototype, "_invertNormalMapX", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "invertNormalMapX", void 0); __decorate([ serialize("invertNormalMapY") ], StandardMaterial.prototype, "_invertNormalMapY", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "invertNormalMapY", void 0); __decorate([ serialize("twoSidedLighting") ], StandardMaterial.prototype, "_twoSidedLighting", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsTexturesDirty") ], StandardMaterial.prototype, "twoSidedLighting", void 0); __decorate([ serialize("applyDecalMapAfterDetailMap") ], StandardMaterial.prototype, "_applyDecalMapAfterDetailMap", void 0); __decorate([ expandToProperty("_markAllSubMeshesAsMiscDirty") ], StandardMaterial.prototype, "applyDecalMapAfterDetailMap", void 0); RegisterClass("BABYLON.StandardMaterial", StandardMaterial); Scene.DefaultMaterialFactory = (scene) => { return new StandardMaterial("default material", scene); }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/geometry.js init_math_vector(); init_math_color(); init_buffer(); init_boundingInfo(); init_tools(); init_tags(); init_engineStore(); init_compatibilityOptions(); init_bufferUtils(); var Geometry = class _Geometry { static { __name(this, "Geometry"); } /** * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y */ get boundingBias() { return this._boundingBias; } /** * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y */ set boundingBias(value) { if (this._boundingBias) { this._boundingBias.copyFrom(value); } else { this._boundingBias = value.clone(); } this._updateBoundingInfo(true, null); } /** * Static function used to attach a new empty geometry to a mesh * @param mesh defines the mesh to attach the geometry to * @returns the new Geometry */ static CreateGeometryForMesh(mesh) { const geometry = new _Geometry(_Geometry.RandomId(), mesh.getScene()); geometry.applyToMesh(mesh); return geometry; } /** Get the list of meshes using this geometry */ get meshes() { return this._meshes; } /** * Creates a new geometry * @param id defines the unique ID * @param scene defines the hosting scene * @param vertexData defines the VertexData used to get geometry data * @param updatable defines if geometry must be updatable (false by default) * @param mesh defines the mesh that will be associated with the geometry */ constructor(id, scene, vertexData, updatable = false, mesh = null) { this.delayLoadState = 0; this._totalVertices = 0; this._isDisposed = false; this._extend = { minimum: new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE), maximum: new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE) }; this._indexBufferIsUpdatable = false; this._positionsCache = []; this._parentContainer = null; this.useBoundingInfoFromGeometry = false; this._scene = scene || EngineStore.LastCreatedScene; if (!this._scene) { return; } this.id = id; this.uniqueId = this._scene.getUniqueId(); this._engine = this._scene.getEngine(); this._meshes = []; this._vertexBuffers = {}; this._indices = []; this._updatable = updatable; if (vertexData) { this.setAllVerticesData(vertexData, updatable); } else { this._totalVertices = 0; } if (this._engine.getCaps().vertexArrayObject) { this._vertexArrayObjects = {}; } if (mesh) { this.applyToMesh(mesh); mesh.computeWorldMatrix(true); } } /** * Gets the current extend of the geometry */ get extend() { return this._extend; } /** * Gets the hosting scene * @returns the hosting Scene */ getScene() { return this._scene; } /** * Gets the hosting engine * @returns the hosting Engine */ getEngine() { return this._engine; } /** * Defines if the geometry is ready to use * @returns true if the geometry is ready to be used */ isReady() { return this.delayLoadState === 1 || this.delayLoadState === 0; } /** * Gets a value indicating that the geometry should not be serialized */ get doNotSerialize() { for (let index = 0; index < this._meshes.length; index++) { if (!this._meshes[index].doNotSerialize) { return false; } } return true; } /** @internal */ _rebuild() { if (this._vertexArrayObjects) { this._vertexArrayObjects = {}; } if (this._meshes.length !== 0 && this._indices) { this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable, "Geometry_" + this.id + "_IndexBuffer"); } const buffers = /* @__PURE__ */ new Set(); for (const key in this._vertexBuffers) { buffers.add(this._vertexBuffers[key].getWrapperBuffer()); } buffers.forEach((buffer) => { buffer._rebuild(); }); } /** * Affects all geometry data in one call * @param vertexData defines the geometry data * @param updatable defines if the geometry must be flagged as updatable (false as default) */ setAllVerticesData(vertexData, updatable) { vertexData.applyToGeometry(this, updatable); this._notifyUpdate(); } /** * Set specific vertex data * @param kind defines the data kind (Position, normal, etc...) * @param data defines the vertex data to use * @param updatable defines if the vertex must be flagged as updatable (false as default) * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified */ setVerticesData(kind, data, updatable = false, stride) { if (updatable && Array.isArray(data)) { data = new Float32Array(data); } const buffer = new VertexBuffer(this._engine, data, kind, { updatable, postponeInternalCreation: this._meshes.length === 0, stride, label: "Geometry_" + this.id + "_" + kind }); this.setVerticesBuffer(buffer); } /** * Removes a specific vertex data * @param kind defines the data kind (Position, normal, etc...) */ removeVerticesData(kind) { if (this._vertexBuffers[kind]) { this._vertexBuffers[kind].dispose(); delete this._vertexBuffers[kind]; } if (this._vertexArrayObjects) { this._disposeVertexArrayObjects(); } } /** * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data * @param buffer defines the vertex buffer to use * @param totalVertices defines the total number of vertices for position kind (could be null) * @param disposeExistingBuffer disposes the existing buffer, if any (default: true) */ setVerticesBuffer(buffer, totalVertices = null, disposeExistingBuffer = true) { const kind = buffer.getKind(); if (this._vertexBuffers[kind] && disposeExistingBuffer) { this._vertexBuffers[kind].dispose(); } if (buffer._buffer && buffer._ownsBuffer) { buffer._buffer._increaseReferences(); } this._vertexBuffers[kind] = buffer; const meshes = this._meshes; const numOfMeshes = meshes.length; if (kind === VertexBuffer.PositionKind) { this._totalVertices = totalVertices ?? buffer._maxVerticesCount; this._updateExtend(this.useBoundingInfoFromGeometry && this._boundingInfo ? null : buffer.getFloatData(this._totalVertices)); this._resetPointsArrayCache(); const minimum = this._extend && this._extend.minimum || new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); const maximum = this._extend && this._extend.maximum || new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); for (let index = 0; index < numOfMeshes; index++) { const mesh = meshes[index]; mesh.buildBoundingInfo(minimum, maximum); mesh._createGlobalSubMesh(mesh.isUnIndexed); mesh.computeWorldMatrix(true); mesh.synchronizeInstances(); } } this._notifyUpdate(kind); } /** * Update a specific vertex buffer * This function will directly update the underlying DataBuffer according to the passed numeric array or Float32Array * It will do nothing if the buffer is not updatable * @param kind defines the data kind (Position, normal, etc...) * @param data defines the data to use * @param offset defines the offset in the target buffer where to store the data * @param useBytes set to true if the offset is in bytes */ updateVerticesDataDirectly(kind, data, offset, useBytes = false) { const vertexBuffer = this.getVertexBuffer(kind); if (!vertexBuffer) { return; } vertexBuffer.updateDirectly(data, offset, useBytes); this._notifyUpdate(kind); } /** * Update a specific vertex buffer * This function will create a new buffer if the current one is not updatable * @param kind defines the data kind (Position, normal, etc...) * @param data defines the data to use * @param updateExtends defines if the geometry extends must be recomputed (false by default) */ updateVerticesData(kind, data, updateExtends = false) { const vertexBuffer = this.getVertexBuffer(kind); if (!vertexBuffer) { return; } vertexBuffer.update(data); if (kind === VertexBuffer.PositionKind) { this._updateBoundingInfo(updateExtends, data); } this._notifyUpdate(kind); } _updateBoundingInfo(updateExtends, data) { if (updateExtends) { this._updateExtend(data); } this._resetPointsArrayCache(); if (updateExtends) { const meshes = this._meshes; for (const mesh of meshes) { if (mesh.hasBoundingInfo) { mesh.getBoundingInfo().reConstruct(this._extend.minimum, this._extend.maximum); } else { mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum); } const subMeshes = mesh.subMeshes; for (const subMesh of subMeshes) { subMesh.refreshBoundingInfo(); } } } } /** * @internal */ _bind(effect, indexToBind, overrideVertexBuffers, overrideVertexArrayObjects) { if (!effect) { return; } if (indexToBind === void 0) { indexToBind = this._indexBuffer; } const vbs = this.getVertexBuffers(); if (!vbs) { return; } if (indexToBind != this._indexBuffer || !this._vertexArrayObjects && !overrideVertexArrayObjects) { this._engine.bindBuffers(vbs, indexToBind, effect, overrideVertexBuffers); return; } const vaos = overrideVertexArrayObjects ? overrideVertexArrayObjects : this._vertexArrayObjects; const engine = this._engine; if (!vaos[effect.key]) { vaos[effect.key] = engine.recordVertexArrayObject(vbs, indexToBind, effect, overrideVertexBuffers); } engine.bindVertexArrayObject(vaos[effect.key], indexToBind); } /** * Gets total number of vertices * @returns the total number of vertices */ getTotalVertices() { if (!this.isReady()) { return 0; } return this._totalVertices; } /** * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly. * @param kind defines the data kind (Position, normal, etc...) * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it * @returns a float array containing vertex data */ getVerticesData(kind, copyWhenShared, forceCopy) { const vertexBuffer = this.getVertexBuffer(kind); if (!vertexBuffer) { return null; } return vertexBuffer.getFloatData(this._totalVertices, forceCopy || copyWhenShared && this._meshes.length !== 1); } /** * Copies the requested vertex data kind into the given vertex data map. Float data is constructed if the map doesn't have the data. * @param kind defines the data kind (Position, normal, etc...) * @param vertexData defines the map that stores the resulting data */ copyVerticesData(kind, vertexData) { const vertexBuffer = this.getVertexBuffer(kind); if (!vertexBuffer) { return; } vertexData[kind] || (vertexData[kind] = new Float32Array(this._totalVertices * vertexBuffer.getSize())); const data = vertexBuffer.getData(); if (data) { CopyFloatData(data, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.byteOffset, vertexBuffer.byteStride, vertexBuffer.normalized, this._totalVertices, vertexData[kind]); } } /** * Returns a boolean defining if the vertex data for the requested `kind` is updatable * @param kind defines the data kind (Position, normal, etc...) * @returns true if the vertex buffer with the specified kind is updatable */ isVertexBufferUpdatable(kind) { const vb = this._vertexBuffers[kind]; if (!vb) { return false; } return vb.isUpdatable(); } /** * Gets a specific vertex buffer * @param kind defines the data kind (Position, normal, etc...) * @returns a VertexBuffer */ getVertexBuffer(kind) { if (!this.isReady()) { return null; } return this._vertexBuffers[kind]; } /** * Returns all vertex buffers * @returns an object holding all vertex buffers indexed by kind */ getVertexBuffers() { if (!this.isReady()) { return null; } return this._vertexBuffers; } /** * Gets a boolean indicating if specific vertex buffer is present * @param kind defines the data kind (Position, normal, etc...) * @returns true if data is present */ isVerticesDataPresent(kind) { if (!this._vertexBuffers) { if (this._delayInfo) { return this._delayInfo.indexOf(kind) !== -1; } return false; } return this._vertexBuffers[kind] !== void 0; } /** * Gets a list of all attached data kinds (Position, normal, etc...) * @returns a list of string containing all kinds */ getVerticesDataKinds() { const result = []; let kind; if (!this._vertexBuffers && this._delayInfo) { for (kind in this._delayInfo) { result.push(kind); } } else { for (kind in this._vertexBuffers) { result.push(kind); } } return result; } /** * Update index buffer * @param indices defines the indices to store in the index buffer * @param offset defines the offset in the target buffer where to store the data * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default) */ updateIndices(indices, offset, gpuMemoryOnly = false) { if (!this._indexBuffer) { return; } if (!this._indexBufferIsUpdatable) { this.setIndices(indices, null, true); } else { const needToUpdateSubMeshes = indices.length !== this._indices.length; if (!gpuMemoryOnly) { this._indices = indices.slice(); } this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset); if (needToUpdateSubMeshes) { for (const mesh of this._meshes) { mesh._createGlobalSubMesh(true); } } } } /** * Sets the index buffer for this geometry. * @param indexBuffer Defines the index buffer to use for this geometry * @param totalVertices Defines the total number of vertices used by the buffer * @param totalIndices Defines the total number of indices in the index buffer * @param is32Bits Defines if the indices are 32 bits. If null (default), the value is guessed from the number of vertices */ setIndexBuffer(indexBuffer, totalVertices, totalIndices, is32Bits = null) { this._indices = []; this._indexBufferIsUpdatable = false; this._indexBuffer = indexBuffer; this._totalVertices = totalVertices; this._totalIndices = totalIndices; if (is32Bits === null) { indexBuffer.is32Bits = totalVertices > 65535; } else { indexBuffer.is32Bits = is32Bits; } for (const mesh of this._meshes) { mesh._createGlobalSubMesh(true); mesh.synchronizeInstances(); } this._notifyUpdate(); } /** * Creates a new index buffer * @param indices defines the indices to store in the index buffer * @param totalVertices defines the total number of vertices (could be null) * @param updatable defines if the index buffer must be flagged as updatable (false by default) * @param dontForceSubMeshRecreation defines a boolean indicating that we don't want to force the recreation of sub-meshes if we don't have to (false by default) */ setIndices(indices, totalVertices = null, updatable = false, dontForceSubMeshRecreation = false) { if (this._indexBuffer) { this._engine._releaseBuffer(this._indexBuffer); } this._indices = indices; this._indexBufferIsUpdatable = updatable; if (this._meshes.length !== 0 && this._indices) { this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable, "Geometry_" + this.id + "_IndexBuffer"); } if (totalVertices != void 0) { this._totalVertices = totalVertices; } for (const mesh of this._meshes) { mesh._createGlobalSubMesh(!dontForceSubMeshRecreation); mesh.synchronizeInstances(); } this._notifyUpdate(); } /** * Return the total number of indices * @returns the total number of indices */ getTotalIndices() { if (!this.isReady()) { return 0; } return this._totalIndices !== void 0 ? this._totalIndices : this._indices.length; } /** * Gets the index buffer array * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it * @returns the index buffer array */ getIndices(copyWhenShared, forceCopy) { if (!this.isReady()) { return null; } const orig = this._indices; if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) { return orig; } else { return orig.slice(); } } /** * Gets the index buffer * @returns the index buffer */ getIndexBuffer() { if (!this.isReady()) { return null; } return this._indexBuffer; } /** * @internal */ _releaseVertexArrayObject(effect = null) { if (!effect || !this._vertexArrayObjects) { return; } if (this._vertexArrayObjects[effect.key]) { this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]); delete this._vertexArrayObjects[effect.key]; } } /** * Release the associated resources for a specific mesh * @param mesh defines the source mesh * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it */ releaseForMesh(mesh, shouldDispose) { const meshes = this._meshes; const index = meshes.indexOf(mesh); if (index === -1) { return; } meshes.splice(index, 1); if (this._vertexArrayObjects) { mesh._invalidateInstanceVertexArrayObject(); } mesh._geometry = null; if (meshes.length === 0 && shouldDispose) { this.dispose(); } } /** * Apply current geometry to a given mesh * @param mesh defines the mesh to apply geometry to */ applyToMesh(mesh) { if (mesh._geometry === this) { return; } const previousGeometry = mesh._geometry; if (previousGeometry) { previousGeometry.releaseForMesh(mesh); } if (this._vertexArrayObjects) { mesh._invalidateInstanceVertexArrayObject(); } const meshes = this._meshes; mesh._geometry = this; mesh._internalAbstractMeshDataInfo._positions = null; this._scene.pushGeometry(this); meshes.push(mesh); if (this.isReady()) { this._applyToMesh(mesh); } else if (this._boundingInfo) { mesh.setBoundingInfo(this._boundingInfo); } } _updateExtend(data = null) { if (this.useBoundingInfoFromGeometry && this._boundingInfo) { this._extend = { minimum: this._boundingInfo.minimum.clone(), maximum: this._boundingInfo.maximum.clone() }; } else { if (!data) { data = this.getVerticesData(VertexBuffer.PositionKind); if (!data) { return; } } this._extend = extractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3); } } _applyToMesh(mesh) { for (const kind in this._vertexBuffers) { const vertexBuffer = this._vertexBuffers[kind]; if (!vertexBuffer._buffer.getBuffer()) { vertexBuffer.create(); } if (kind === VertexBuffer.PositionKind) { if (!this._extend) { this._updateExtend(); } mesh.buildBoundingInfo(this._extend.minimum, this._extend.maximum); mesh._createGlobalSubMesh(mesh.isUnIndexed); mesh._updateBoundingInfo(); } } if (!this._indexBuffer && this._indices && this._indices.length > 0) { this._indexBuffer = this._engine.createIndexBuffer(this._indices, this._updatable, "Geometry_" + this.id + "_IndexBuffer"); } mesh._syncGeometryWithMorphTargetManager(); mesh.synchronizeInstances(); } _notifyUpdate(kind) { if (this.onGeometryUpdated) { this.onGeometryUpdated(this, kind); } if (this._vertexArrayObjects) { this._disposeVertexArrayObjects(); } for (const mesh of this._meshes) { mesh._markSubMeshesAsAttributesDirty(); } } /** * Load the geometry if it was flagged as delay loaded * @param scene defines the hosting scene * @param onLoaded defines a callback called when the geometry is loaded */ load(scene, onLoaded) { if (this.delayLoadState === 2) { return; } if (this.isReady()) { if (onLoaded) { onLoaded(); } return; } this.delayLoadState = 2; this._queueLoad(scene, onLoaded); } _queueLoad(scene, onLoaded) { if (!this.delayLoadingFile) { return; } scene.addPendingData(this); scene._loadFile(this.delayLoadingFile, (data) => { if (!this._delayLoadingFunction) { return; } this._delayLoadingFunction(JSON.parse(data), this); this.delayLoadState = 1; this._delayInfo = []; scene.removePendingData(this); const meshes = this._meshes; const numOfMeshes = meshes.length; for (let index = 0; index < numOfMeshes; index++) { this._applyToMesh(meshes[index]); } if (onLoaded) { onLoaded(); } }, void 0, true); } /** * Invert the geometry to move from a right handed system to a left handed one. */ toLeftHanded() { const tIndices = this.getIndices(false); if (tIndices != null && tIndices.length > 0) { for (let i = 0; i < tIndices.length; i += 3) { const tTemp = tIndices[i + 0]; tIndices[i + 0] = tIndices[i + 2]; tIndices[i + 2] = tTemp; } this.setIndices(tIndices); } const tPositions = this.getVerticesData(VertexBuffer.PositionKind, false); if (tPositions != null && tPositions.length > 0) { for (let i = 0; i < tPositions.length; i += 3) { tPositions[i + 2] = -tPositions[i + 2]; } this.setVerticesData(VertexBuffer.PositionKind, tPositions, false); } const tNormals = this.getVerticesData(VertexBuffer.NormalKind, false); if (tNormals != null && tNormals.length > 0) { for (let i = 0; i < tNormals.length; i += 3) { tNormals[i + 2] = -tNormals[i + 2]; } this.setVerticesData(VertexBuffer.NormalKind, tNormals, false); } } // Cache /** @internal */ _resetPointsArrayCache() { this._positions = null; } /** @internal */ _generatePointsArray() { if (this._positions) { return true; } const data = this.getVerticesData(VertexBuffer.PositionKind); if (!data || data.length === 0) { return false; } for (let index = this._positionsCache.length * 3, arrayIdx = this._positionsCache.length; index < data.length; index += 3, ++arrayIdx) { this._positionsCache[arrayIdx] = Vector3.FromArray(data, index); } for (let index = 0, arrayIdx = 0; index < data.length; index += 3, ++arrayIdx) { this._positionsCache[arrayIdx].set(data[0 + index], data[1 + index], data[2 + index]); } this._positionsCache.length = data.length / 3; this._positions = this._positionsCache; return true; } /** * Gets a value indicating if the geometry is disposed * @returns true if the geometry was disposed */ isDisposed() { return this._isDisposed; } _disposeVertexArrayObjects() { if (this._vertexArrayObjects) { for (const kind in this._vertexArrayObjects) { this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]); } this._vertexArrayObjects = {}; const meshes = this._meshes; const numOfMeshes = meshes.length; for (let index = 0; index < numOfMeshes; index++) { meshes[index]._invalidateInstanceVertexArrayObject(); } } } /** * Free all associated resources */ dispose() { const meshes = this._meshes; const numOfMeshes = meshes.length; let index; for (index = 0; index < numOfMeshes; index++) { this.releaseForMesh(meshes[index]); } this._meshes.length = 0; this._disposeVertexArrayObjects(); for (const kind in this._vertexBuffers) { this._vertexBuffers[kind].dispose(); } this._vertexBuffers = {}; this._totalVertices = 0; if (this._indexBuffer) { this._engine._releaseBuffer(this._indexBuffer); } this._indexBuffer = null; this._indices = []; this.delayLoadState = 0; this.delayLoadingFile = null; this._delayLoadingFunction = null; this._delayInfo = []; this._boundingInfo = null; this._scene.removeGeometry(this); if (this._parentContainer) { const index2 = this._parentContainer.geometries.indexOf(this); if (index2 > -1) { this._parentContainer.geometries.splice(index2, 1); } this._parentContainer = null; } this._isDisposed = true; } /** * Clone the current geometry into a new geometry * @param id defines the unique ID of the new geometry * @returns a new geometry object */ copy(id) { const geometry = new _Geometry(id, this._scene); const indices = this.getIndices(void 0, true); if (indices) { geometry.setIndices(indices); } let updatable = false; let kind; for (kind in this._vertexBuffers) { const vb = this.getVertexBuffer(kind); const bufferData = vb.getData(); if (!bufferData) { continue; } const isUpdatable = vb.isUpdatable(); const size = vb.getSize(); const { type, byteOffset, byteStride, normalized } = vb; updatable = updatable || isUpdatable; const copy = GetTypedArrayData(bufferData, size, type, byteOffset, byteStride, this._totalVertices, true); const newVb = new VertexBuffer(this._engine, copy, kind, { updatable: isUpdatable, useBytes: false, stride: size, // Copy is tightly-packed, so stride = size size, // Component size stays the same offset: 0, // Copy starts at beginning of its own buffer type, normalized, takeBufferOwnership: true }); geometry.setVerticesBuffer(newVb, this._totalVertices); } geometry._updatable = updatable; geometry.delayLoadState = this.delayLoadState; geometry.delayLoadingFile = this.delayLoadingFile; geometry._delayLoadingFunction = this._delayLoadingFunction; for (kind in this._delayInfo) { geometry._delayInfo = geometry._delayInfo || []; geometry._delayInfo.push(kind); } geometry._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum); return geometry; } /** * Serialize the current geometry info (and not the vertices data) into a JSON object * @returns a JSON representation of the current geometry data (without the vertices data) */ serialize() { const serializationObject = {}; serializationObject.id = this.id; serializationObject.uniqueId = this.uniqueId; serializationObject.updatable = this._updatable; if (Tags && Tags.HasTags(this)) { serializationObject.tags = Tags.GetTags(this); } return serializationObject; } _toNumberArray(origin) { if (Array.isArray(origin)) { return origin; } else { return Array.prototype.slice.call(origin); } } /** * Release any memory retained by the cached data on the Geometry. * * Call this function to reduce memory footprint of the mesh. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly) */ clearCachedData() { this._indices = []; this._resetPointsArrayCache(); for (const vbName in this._vertexBuffers) { if (!Object.prototype.hasOwnProperty.call(this._vertexBuffers, vbName)) { continue; } this._vertexBuffers[vbName]._buffer._data = null; } } /** * Serialize all vertices data into a JSON object * @returns a JSON representation of the current geometry data */ serializeVerticeData() { const serializationObject = this.serialize(); if (this.isVerticesDataPresent(VertexBuffer.PositionKind)) { serializationObject.positions = this._toNumberArray(this.getVerticesData(VertexBuffer.PositionKind)); if (this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) { serializationObject.positionsUpdatable = true; } } if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) { serializationObject.normals = this._toNumberArray(this.getVerticesData(VertexBuffer.NormalKind)); if (this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) { serializationObject.normalsUpdatable = true; } } if (this.isVerticesDataPresent(VertexBuffer.TangentKind)) { serializationObject.tangents = this._toNumberArray(this.getVerticesData(VertexBuffer.TangentKind)); if (this.isVertexBufferUpdatable(VertexBuffer.TangentKind)) { serializationObject.tangentsUpdatable = true; } } if (this.isVerticesDataPresent(VertexBuffer.UVKind)) { serializationObject.uvs = this._toNumberArray(this.getVerticesData(VertexBuffer.UVKind)); if (this.isVertexBufferUpdatable(VertexBuffer.UVKind)) { serializationObject.uvsUpdatable = true; } } if (this.isVerticesDataPresent(VertexBuffer.UV2Kind)) { serializationObject.uvs2 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV2Kind)); if (this.isVertexBufferUpdatable(VertexBuffer.UV2Kind)) { serializationObject.uvs2Updatable = true; } } if (this.isVerticesDataPresent(VertexBuffer.UV3Kind)) { serializationObject.uvs3 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV3Kind)); if (this.isVertexBufferUpdatable(VertexBuffer.UV3Kind)) { serializationObject.uvs3Updatable = true; } } if (this.isVerticesDataPresent(VertexBuffer.UV4Kind)) { serializationObject.uvs4 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV4Kind)); if (this.isVertexBufferUpdatable(VertexBuffer.UV4Kind)) { serializationObject.uvs4Updatable = true; } } if (this.isVerticesDataPresent(VertexBuffer.UV5Kind)) { serializationObject.uvs5 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV5Kind)); if (this.isVertexBufferUpdatable(VertexBuffer.UV5Kind)) { serializationObject.uvs5Updatable = true; } } if (this.isVerticesDataPresent(VertexBuffer.UV6Kind)) { serializationObject.uvs6 = this._toNumberArray(this.getVerticesData(VertexBuffer.UV6Kind)); if (this.isVertexBufferUpdatable(VertexBuffer.UV6Kind)) { serializationObject.uvs6Updatable = true; } } if (this.isVerticesDataPresent(VertexBuffer.ColorKind)) { serializationObject.colors = this._toNumberArray(this.getVerticesData(VertexBuffer.ColorKind)); if (this.isVertexBufferUpdatable(VertexBuffer.ColorKind)) { serializationObject.colorsUpdatable = true; } } if (this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) { serializationObject.matricesIndices = this._toNumberArray(this.getVerticesData(VertexBuffer.MatricesIndicesKind)); serializationObject.matricesIndicesExpanded = true; if (this.isVertexBufferUpdatable(VertexBuffer.MatricesIndicesKind)) { serializationObject.matricesIndicesUpdatable = true; } } if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) { serializationObject.matricesWeights = this._toNumberArray(this.getVerticesData(VertexBuffer.MatricesWeightsKind)); if (this.isVertexBufferUpdatable(VertexBuffer.MatricesWeightsKind)) { serializationObject.matricesWeightsUpdatable = true; } } serializationObject.indices = this._toNumberArray(this.getIndices()); return serializationObject; } // Statics /** * Extracts a clone of a mesh geometry * @param mesh defines the source mesh * @param id defines the unique ID of the new geometry object * @returns the new geometry object */ static ExtractFromMesh(mesh, id) { const geometry = mesh._geometry; if (!geometry) { return null; } return geometry.copy(id); } /** * You should now use Tools.RandomId(), this method is still here for legacy reasons. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 * Be aware Math.random() could cause collisions, but: * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide" * @returns a string containing a new GUID */ static RandomId() { return Tools.RandomId(); } static _GetGeometryByLoadedUniqueId(uniqueId, scene) { for (let index = 0; index < scene.geometries.length; index++) { if (scene.geometries[index]._loadedUniqueId === uniqueId) { return scene.geometries[index]; } } return null; } /** * @internal */ static _ImportGeometry(parsedGeometry, mesh) { const scene = mesh.getScene(); const geometryUniqueId = parsedGeometry.geometryUniqueId; const geometryId = parsedGeometry.geometryId; if (geometryUniqueId || geometryId) { const geometry = geometryUniqueId ? this._GetGeometryByLoadedUniqueId(geometryUniqueId, scene) : scene.getGeometryById(geometryId); if (geometry) { geometry.applyToMesh(mesh); } } else if (parsedGeometry instanceof ArrayBuffer) { const binaryInfo = mesh._binaryInfo; if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) { const positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count); mesh.setVerticesData(VertexBuffer.PositionKind, positionsData, false); } if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) { const normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count); mesh.setVerticesData(VertexBuffer.NormalKind, normalsData, false); } if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) { const tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count); mesh.setVerticesData(VertexBuffer.TangentKind, tangentsData, false); } if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) { const uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count); if (useOpenGLOrientationForUV) { for (let index = 1; index < uvsData.length; index += 2) { uvsData[index] = 1 - uvsData[index]; } } mesh.setVerticesData(VertexBuffer.UVKind, uvsData, false); } if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) { const uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count); if (useOpenGLOrientationForUV) { for (let index = 1; index < uvs2Data.length; index += 2) { uvs2Data[index] = 1 - uvs2Data[index]; } } mesh.setVerticesData(VertexBuffer.UV2Kind, uvs2Data, false); } if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) { const uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count); if (useOpenGLOrientationForUV) { for (let index = 1; index < uvs3Data.length; index += 2) { uvs3Data[index] = 1 - uvs3Data[index]; } } mesh.setVerticesData(VertexBuffer.UV3Kind, uvs3Data, false); } if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) { const uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count); if (useOpenGLOrientationForUV) { for (let index = 1; index < uvs4Data.length; index += 2) { uvs4Data[index] = 1 - uvs4Data[index]; } } mesh.setVerticesData(VertexBuffer.UV4Kind, uvs4Data, false); } if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) { const uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count); if (useOpenGLOrientationForUV) { for (let index = 1; index < uvs5Data.length; index += 2) { uvs5Data[index] = 1 - uvs5Data[index]; } } mesh.setVerticesData(VertexBuffer.UV5Kind, uvs5Data, false); } if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) { const uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count); if (useOpenGLOrientationForUV) { for (let index = 1; index < uvs6Data.length; index += 2) { uvs6Data[index] = 1 - uvs6Data[index]; } } mesh.setVerticesData(VertexBuffer.UV6Kind, uvs6Data, false); } if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) { const colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count); mesh.setVerticesData(VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride); } if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) { const matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count); const floatIndices = []; for (let i = 0; i < matricesIndicesData.length; i++) { const index = matricesIndicesData[i]; floatIndices.push(index & 255); floatIndices.push((index & 65280) >> 8); floatIndices.push((index & 16711680) >> 16); floatIndices.push(index >> 24 & 255); } mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, false); } if (binaryInfo.matricesIndicesExtraAttrDesc && binaryInfo.matricesIndicesExtraAttrDesc.count > 0) { const matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesExtraAttrDesc.offset, binaryInfo.matricesIndicesExtraAttrDesc.count); const floatIndices = []; for (let i = 0; i < matricesIndicesData.length; i++) { const index = matricesIndicesData[i]; floatIndices.push(index & 255); floatIndices.push((index & 65280) >> 8); floatIndices.push((index & 16711680) >> 16); floatIndices.push(index >> 24 & 255); } mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, false); } if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) { const matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count); mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsData, false); } if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) { const indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count); mesh.setIndices(indicesData, null); } if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) { const subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5); mesh.subMeshes = []; for (let i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) { const materialIndex = subMeshesData[i * 5 + 0]; const verticesStart = subMeshesData[i * 5 + 1]; const verticesCount = subMeshesData[i * 5 + 2]; const indexStart = subMeshesData[i * 5 + 3]; const indexCount = subMeshesData[i * 5 + 4]; SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh); } } } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) { mesh.setVerticesData(VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable || parsedGeometry.positionsUpdatable); mesh.setVerticesData(VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable || parsedGeometry.normalsUpdatable); if (parsedGeometry.tangents) { mesh.setVerticesData(VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable || parsedGeometry.tangentsUpdatable); } if (parsedGeometry.uvs) { mesh.setVerticesData(VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable || parsedGeometry.uvsUpdatable); } if (parsedGeometry.uvs2) { mesh.setVerticesData(VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable || parsedGeometry.uvs2Updatable); } if (parsedGeometry.uvs3) { mesh.setVerticesData(VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable || parsedGeometry.uvs3Updatable); } if (parsedGeometry.uvs4) { mesh.setVerticesData(VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable || parsedGeometry.uvs4Updatable); } if (parsedGeometry.uvs5) { mesh.setVerticesData(VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable || parsedGeometry.uvs5Updatable); } if (parsedGeometry.uvs6) { mesh.setVerticesData(VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable || parsedGeometry.uvs6Updatable); } if (parsedGeometry.colors) { mesh.setVerticesData(VertexBuffer.ColorKind, Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable); } if (parsedGeometry.matricesIndices) { if (!parsedGeometry.matricesIndices._isExpanded && !parsedGeometry.matricesIndicesExpanded) { const floatIndices = []; for (let i = 0; i < parsedGeometry.matricesIndices.length; i++) { const matricesIndex = parsedGeometry.matricesIndices[i]; floatIndices.push(matricesIndex & 255); floatIndices.push((matricesIndex & 65280) >> 8); floatIndices.push((matricesIndex & 16711680) >> 16); floatIndices.push(matricesIndex >> 24 & 255); } mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable || parsedGeometry.matricesIndicesUpdatable); } else { delete parsedGeometry.matricesIndices._isExpanded; delete parsedGeometry.matricesIndicesExpanded; mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable || parsedGeometry.matricesIndicesUpdatable); } } if (parsedGeometry.matricesIndicesExtra) { if (!(parsedGeometry.matricesIndicesExtraExpanded || parsedGeometry.matricesIndicesExtra._isExpanded)) { const floatIndices = []; for (let i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) { const matricesIndex = parsedGeometry.matricesIndicesExtra[i]; floatIndices.push(matricesIndex & 255); floatIndices.push((matricesIndex & 65280) >> 8); floatIndices.push((matricesIndex & 16711680) >> 16); floatIndices.push(matricesIndex >> 24 & 255); } mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable || parsedGeometry.matricesIndicesExtraUpdatable); } else { delete parsedGeometry.matricesIndices._isExpanded; delete parsedGeometry.matricesIndicesExtraExpanded; mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable || parsedGeometry.matricesIndicesExtraUpdatable); } } if (parsedGeometry.matricesWeights) { _Geometry._CleanMatricesWeights(parsedGeometry, mesh); mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable); } if (parsedGeometry.matricesWeightsExtra) { mesh.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable); } mesh.setIndices(parsedGeometry.indices, null); } if (parsedGeometry.subMeshes) { mesh.subMeshes = []; for (let subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) { const parsedSubMesh = parsedGeometry.subMeshes[subIndex]; SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh); } } if (mesh._shouldGenerateFlatShading) { mesh.convertToFlatShadedMesh(); mesh._shouldGenerateFlatShading = false; } mesh.computeWorldMatrix(true); scene.onMeshImportedObservable.notifyObservers(mesh); } static _CleanMatricesWeights(parsedGeometry, mesh) { const epsilon = 1e-3; if (!SceneLoaderFlags.CleanBoneMatrixWeights) { return; } let noInfluenceBoneIndex = 0; if (parsedGeometry.skeletonId > -1) { const skeleton = mesh.getScene().getLastSkeletonById(parsedGeometry.skeletonId); if (!skeleton) { return; } noInfluenceBoneIndex = skeleton.bones.length; } else { return; } const matricesIndices = mesh.getVerticesData(VertexBuffer.MatricesIndicesKind); const matricesIndicesExtra = mesh.getVerticesData(VertexBuffer.MatricesIndicesExtraKind); const matricesWeights = parsedGeometry.matricesWeights; const matricesWeightsExtra = parsedGeometry.matricesWeightsExtra; const influencers = parsedGeometry.numBoneInfluencer; const size = matricesWeights.length; for (let i = 0; i < size; i += 4) { let weight = 0; let firstZeroWeight = -1; for (let j = 0; j < 4; j++) { const w = matricesWeights[i + j]; weight += w; if (w < epsilon && firstZeroWeight < 0) { firstZeroWeight = j; } } if (matricesWeightsExtra) { for (let j = 0; j < 4; j++) { const w = matricesWeightsExtra[i + j]; weight += w; if (w < epsilon && firstZeroWeight < 0) { firstZeroWeight = j + 4; } } } if (firstZeroWeight < 0 || firstZeroWeight > influencers - 1) { firstZeroWeight = influencers - 1; } if (weight > epsilon) { const mweight = 1 / weight; for (let j = 0; j < 4; j++) { matricesWeights[i + j] *= mweight; } if (matricesWeightsExtra) { for (let j = 0; j < 4; j++) { matricesWeightsExtra[i + j] *= mweight; } } } else { if (firstZeroWeight >= 4) { matricesWeightsExtra[i + firstZeroWeight - 4] = 1 - weight; matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex; } else { matricesWeights[i + firstZeroWeight] = 1 - weight; matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex; } } } mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, matricesIndices); if (parsedGeometry.matricesWeightsExtra) { mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra); } } /** * Create a new geometry from persisted data (Using .babylon file format) * @param parsedVertexData defines the persisted data * @param scene defines the hosting scene * @param rootUrl defines the root url to use to load assets (like delayed data) * @returns the new geometry object */ static Parse(parsedVertexData, scene, rootUrl) { const geometry = new _Geometry(parsedVertexData.id, scene, void 0, parsedVertexData.updatable); geometry._loadedUniqueId = parsedVertexData.uniqueId; if (Tags) { Tags.AddTagsTo(geometry, parsedVertexData.tags); } if (parsedVertexData.delayLoadingFile) { geometry.delayLoadState = 4; geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile; geometry._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedVertexData.boundingBoxMinimum), Vector3.FromArray(parsedVertexData.boundingBoxMaximum)); geometry._delayInfo = []; if (parsedVertexData.hasUVs) { geometry._delayInfo.push(VertexBuffer.UVKind); } if (parsedVertexData.hasUVs2) { geometry._delayInfo.push(VertexBuffer.UV2Kind); } if (parsedVertexData.hasUVs3) { geometry._delayInfo.push(VertexBuffer.UV3Kind); } if (parsedVertexData.hasUVs4) { geometry._delayInfo.push(VertexBuffer.UV4Kind); } if (parsedVertexData.hasUVs5) { geometry._delayInfo.push(VertexBuffer.UV5Kind); } if (parsedVertexData.hasUVs6) { geometry._delayInfo.push(VertexBuffer.UV6Kind); } if (parsedVertexData.hasColors) { geometry._delayInfo.push(VertexBuffer.ColorKind); } if (parsedVertexData.hasMatricesIndices) { geometry._delayInfo.push(VertexBuffer.MatricesIndicesKind); } if (parsedVertexData.hasMatricesWeights) { geometry._delayInfo.push(VertexBuffer.MatricesWeightsKind); } geometry._delayLoadingFunction = VertexData.ImportVertexData; } else { VertexData.ImportVertexData(parsedVertexData, geometry); } scene.pushGeometry(geometry, true); return geometry; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/multiMaterial.js init_tags(); init_typeStore(); var MultiMaterial = class _MultiMaterial extends Material { static { __name(this, "MultiMaterial"); } /** * Gets or Sets the list of Materials used within the multi material. * They need to be ordered according to the submeshes order in the associated mesh */ get subMaterials() { return this._subMaterials; } set subMaterials(value) { this._subMaterials = value; this._hookArray(value); } /** * Function used to align with Node.getChildren() * @returns the list of Materials used within the multi material */ getChildren() { return this.subMaterials; } /** * Instantiates a new Multi Material * A multi-material is used to apply different materials to different parts of the same object without the need of * separate meshes. This can be use to improve performances. * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/using/multiMaterials * @param name Define the name in the scene * @param scene Define the scene the material belongs to */ constructor(name260, scene) { super(name260, scene, true); this._waitingSubMaterialsUniqueIds = []; this.getScene().addMultiMaterial(this); this.subMaterials = []; this._storeEffectOnSubMeshes = true; } _hookArray(array) { const oldPush = array.push; array.push = (...items) => { const result = oldPush.apply(array, items); this._markAllSubMeshesAsTexturesDirty(); return result; }; const oldSplice = array.splice; array.splice = (index, deleteCount) => { const deleted = oldSplice.apply(array, [index, deleteCount]); this._markAllSubMeshesAsTexturesDirty(); return deleted; }; } /** * Get one of the submaterial by its index in the submaterials array * @param index The index to look the sub material at * @returns The Material if the index has been defined */ getSubMaterial(index) { if (index < 0 || index >= this.subMaterials.length) { return this.getScene().defaultMaterial; } return this.subMaterials[index]; } /** * Get the list of active textures for the whole sub materials list. * @returns All the textures that will be used during the rendering */ getActiveTextures() { return super.getActiveTextures().concat(...this.subMaterials.map((subMaterial) => { if (subMaterial) { return subMaterial.getActiveTextures(); } else { return []; } })); } /** * Specifies if any sub-materials of this multi-material use a given texture. * @param texture Defines the texture to check against this multi-material's sub-materials. * @returns A boolean specifying if any sub-material of this multi-material uses the texture. */ hasTexture(texture) { if (super.hasTexture(texture)) { return true; } for (let i = 0; i < this.subMaterials.length; i++) { if (this.subMaterials[i]?.hasTexture(texture)) { return true; } } return false; } /** * Gets the current class name of the material e.g. "MultiMaterial" * Mainly use in serialization. * @returns the class name */ getClassName() { return "MultiMaterial"; } /** * Checks if the material is ready to render the requested sub mesh * @param mesh Define the mesh the submesh belongs to * @param subMesh Define the sub mesh to look readiness for * @param useInstances Define whether or not the material is used with instances * @returns true if ready, otherwise false */ isReadyForSubMesh(mesh, subMesh, useInstances) { for (let index = 0; index < this.subMaterials.length; index++) { const subMaterial = this.subMaterials[index]; if (subMaterial) { if (subMaterial._storeEffectOnSubMeshes) { if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) { return false; } continue; } if (!subMaterial.isReady(mesh)) { return false; } } } return true; } /** * Clones the current material and its related sub materials * @param name Define the name of the newly cloned material * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance * @returns the cloned material */ clone(name260, cloneChildren) { const newMultiMaterial = new _MultiMaterial(name260, this.getScene()); for (let index = 0; index < this.subMaterials.length; index++) { let subMaterial = null; const current = this.subMaterials[index]; if (cloneChildren && current) { subMaterial = current.clone(name260 + "-" + current.name); } else { subMaterial = this.subMaterials[index]; } newMultiMaterial.subMaterials.push(subMaterial); } return newMultiMaterial; } /** * Serializes the materials into a JSON representation. * @returns the JSON representation */ serialize() { const serializationObject = {}; serializationObject.name = this.name; serializationObject.id = this.id; serializationObject.uniqueId = this.uniqueId; if (Tags) { serializationObject.tags = Tags.GetTags(this); } serializationObject.materialsUniqueIds = []; serializationObject.materials = []; for (let matIndex = 0; matIndex < this.subMaterials.length; matIndex++) { const subMat = this.subMaterials[matIndex]; if (subMat) { serializationObject.materialsUniqueIds.push(subMat.uniqueId); serializationObject.materials.push(subMat.id); } else { serializationObject.materialsUniqueIds.push(null); serializationObject.materials.push(null); } } return serializationObject; } /** * Dispose the material and release its associated resources * @param forceDisposeEffect Define if we want to force disposing the associated effect (if false the shader is not released and could be reuse later on) * @param forceDisposeTextures Define if we want to force disposing the associated textures (if false, they will not be disposed and can still be use elsewhere in the app) * @param forceDisposeChildren Define if we want to force disposing the associated submaterials (if false, they will not be disposed and can still be use elsewhere in the app) */ dispose(forceDisposeEffect, forceDisposeTextures, forceDisposeChildren) { const scene = this.getScene(); if (!scene) { return; } if (forceDisposeChildren) { for (let index2 = 0; index2 < this.subMaterials.length; index2++) { const subMaterial = this.subMaterials[index2]; if (subMaterial) { subMaterial.dispose(forceDisposeEffect, forceDisposeTextures); } } } const index = scene.multiMaterials.indexOf(this); if (index >= 0) { scene.multiMaterials.splice(index, 1); } super.dispose(forceDisposeEffect, forceDisposeTextures); } /** * Creates a MultiMaterial from parsed MultiMaterial data. * @param parsedMultiMaterial defines parsed MultiMaterial data. * @param scene defines the hosting scene * @returns a new MultiMaterial */ static ParseMultiMaterial(parsedMultiMaterial, scene) { const multiMaterial = new _MultiMaterial(parsedMultiMaterial.name, scene); multiMaterial.id = parsedMultiMaterial.id; multiMaterial._loadedUniqueId = parsedMultiMaterial.uniqueId; if (Tags) { Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags); } if (parsedMultiMaterial.materialsUniqueIds) { multiMaterial._waitingSubMaterialsUniqueIds = parsedMultiMaterial.materialsUniqueIds; } else { for (const subMatId of parsedMultiMaterial.materials) { multiMaterial.subMaterials.push(scene.getLastMaterialById(subMatId)); } } return multiMaterial; } }; RegisterClass("BABYLON.MultiMaterial", MultiMaterial); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/meshLODLevel.js var MeshLODLevel = class { static { __name(this, "MeshLODLevel"); } /** * Creates a new LOD level * @param distanceOrScreenCoverage defines either the distance or the screen coverage where this level should start being displayed * @param mesh defines the mesh to use to render this level */ constructor(distanceOrScreenCoverage, mesh) { this.distanceOrScreenCoverage = distanceOrScreenCoverage; this.mesh = mesh; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/mesh.js init_observable(); init_tools(); init_deepCopier(); init_tags(); init_camera(); init_math_vector(); init_math_color(); init_node(); init_buffer(); init_decorators_serialization(); init_logger(); init_typeStore(); init_devTools(); init_sceneComponent(); var _CreationDataStorage = class { static { __name(this, "_CreationDataStorage"); } }; var _InstanceDataStorageRenderPass = class { static { __name(this, "_InstanceDataStorageRenderPass"); } constructor() { this.batchCache = new _InstancesBatch(this); this.batchCacheReplacementModeInFrozenMode = new _InstancesBatch(this); this.instancesBufferSize = 32 * 16 * 4; } }; var _InstanceDataStorage = class { static { __name(this, "_InstanceDataStorage"); } constructor() { this.renderPasses = {}; } }; var _InstancesBatch = class { static { __name(this, "_InstancesBatch"); } constructor(parent) { this.parent = parent; this.mustReturn = false; this.visibleInstances = new Array(); this.renderSelf = []; this.hardwareInstancedRendering = []; } }; var _ThinInstanceDataStorage = class { static { __name(this, "_ThinInstanceDataStorage"); } constructor() { this.instancesCount = 0; this.matrixBuffer = null; this.previousMatrixBuffer = null; this.matrixBufferSize = 32 * 16; this.matrixData = null; this.boundingVectors = []; this.worldMatrices = null; } }; var _InternalMeshDataInfo = class { static { __name(this, "_InternalMeshDataInfo"); } constructor() { this._areNormalsFrozen = false; this._source = null; this.meshMap = null; this._preActivateId = -1; this._LODLevels = new Array(); this._useLODScreenCoverage = false; this._effectiveMaterial = null; this._forcedInstanceCount = 0; this._overrideRenderingFillMode = null; } }; var MeshCreationOptions = { source: null, parent: null, doNotCloneChildren: false, clonePhysicsImpostor: true, cloneThinInstances: false }; var Mesh = class _Mesh extends AbstractMesh { static { __name(this, "Mesh"); } /** * Gets the default side orientation. * @param orientation the orientation to value to attempt to get * @returns the default orientation * @internal */ static _GetDefaultSideOrientation(orientation) { return orientation || _Mesh.FRONTSIDE; } /** * Determines if the LOD levels are intended to be calculated using screen coverage (surface area ratio) instead of distance. */ get useLODScreenCoverage() { return this._internalMeshDataInfo._useLODScreenCoverage; } set useLODScreenCoverage(value) { this._internalMeshDataInfo._useLODScreenCoverage = value; this._sortLODLevels(); } get computeBonesUsingShaders() { return this._internalAbstractMeshDataInfo._computeBonesUsingShaders; } set computeBonesUsingShaders(value) { if (this._internalAbstractMeshDataInfo._computeBonesUsingShaders === value) { return; } if (value && this._internalMeshDataInfo._sourcePositions) { this.setVerticesData(VertexBuffer.PositionKind, this._internalMeshDataInfo._sourcePositions, true); if (this._internalMeshDataInfo._sourceNormals) { this.setVerticesData(VertexBuffer.NormalKind, this._internalMeshDataInfo._sourceNormals, true); } this._internalMeshDataInfo._sourcePositions = null; this._internalMeshDataInfo._sourceNormals = null; } this._internalAbstractMeshDataInfo._computeBonesUsingShaders = value; this._markSubMeshesAsAttributesDirty(); } /** * An event triggered before rendering the mesh */ get onBeforeRenderObservable() { if (!this._internalMeshDataInfo._onBeforeRenderObservable) { this._internalMeshDataInfo._onBeforeRenderObservable = new Observable(); } return this._internalMeshDataInfo._onBeforeRenderObservable; } /** * An event triggered before binding the mesh */ get onBeforeBindObservable() { if (!this._internalMeshDataInfo._onBeforeBindObservable) { this._internalMeshDataInfo._onBeforeBindObservable = new Observable(); } return this._internalMeshDataInfo._onBeforeBindObservable; } /** * An event triggered after rendering the mesh */ get onAfterRenderObservable() { if (!this._internalMeshDataInfo._onAfterRenderObservable) { this._internalMeshDataInfo._onAfterRenderObservable = new Observable(); } return this._internalMeshDataInfo._onAfterRenderObservable; } /** * An event triggeredbetween rendering pass when using separateCullingPass = true */ get onBetweenPassObservable() { if (!this._internalMeshDataInfo._onBetweenPassObservable) { this._internalMeshDataInfo._onBetweenPassObservable = new Observable(); } return this._internalMeshDataInfo._onBetweenPassObservable; } /** * An event triggered before drawing the mesh */ get onBeforeDrawObservable() { if (!this._internalMeshDataInfo._onBeforeDrawObservable) { this._internalMeshDataInfo._onBeforeDrawObservable = new Observable(); } return this._internalMeshDataInfo._onBeforeDrawObservable; } /** * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead */ set onBeforeDraw(callback) { if (this._onBeforeDrawObserver) { this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver); } this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback); } get hasInstances() { return this.instances.length > 0; } get hasThinInstances() { return (this.forcedInstanceCount || this._thinInstanceDataStorage.instancesCount || 0) > 0; } /** * Gets or sets the forced number of instances to display. * If 0 (default value), the number of instances is not forced and depends on the draw type * (regular / instance / thin instances mesh) */ get forcedInstanceCount() { return this._internalMeshDataInfo._forcedInstanceCount; } set forcedInstanceCount(count) { this._internalMeshDataInfo._forcedInstanceCount = count; } /** * Use this property to change the original side orientation defined at construction time * Material.sideOrientation will override this value if set * User will still be able to change the material sideOrientation afterwards if they really need it */ get sideOrientation() { return this._internalMeshDataInfo._sideOrientation; } set sideOrientation(value) { this._internalMeshDataInfo._sideOrientation = value; this._internalAbstractMeshDataInfo._sideOrientationHint = this._scene.useRightHandedSystem && value === 1 || !this._scene.useRightHandedSystem && value === 0; } /** @internal */ get _effectiveSideOrientation() { return this._internalMeshDataInfo._effectiveSideOrientation; } /** * @deprecated Please use sideOrientation instead. * @see https://doc.babylonjs.com/breaking-changes#7110 */ get overrideMaterialSideOrientation() { return this.sideOrientation; } set overrideMaterialSideOrientation(value) { this.sideOrientation = value; if (this.material) { this.material.sideOrientation = null; } } /** * Use this property to override the Material's fillMode value */ get overrideRenderingFillMode() { return this._internalMeshDataInfo._overrideRenderingFillMode; } set overrideRenderingFillMode(fillMode) { this._internalMeshDataInfo._overrideRenderingFillMode = fillMode; } get material() { return this._internalAbstractMeshDataInfo._material; } set material(value) { if (value && (this.material && this.material.sideOrientation === null || this._internalAbstractMeshDataInfo._sideOrientationHint)) { value.sideOrientation = null; } this._setMaterial(value); } /** * Gets the source mesh (the one used to clone this one from) */ get source() { return this._internalMeshDataInfo._source; } /** * Gets the list of clones of this mesh * The scene must have been constructed with useClonedMeshMap=true for this to work! * Note that useClonedMeshMap=true is the default setting */ get cloneMeshMap() { return this._internalMeshDataInfo.meshMap; } /** * Gets or sets a boolean indicating that this mesh does not use index buffer */ get isUnIndexed() { return this._unIndexed; } set isUnIndexed(value) { if (this._unIndexed !== value) { this._unIndexed = value; this._markSubMeshesAsAttributesDirty(); } } /** Gets the array buffer used to store the instanced buffer used for instances' world matrices */ get worldMatrixInstancedBuffer() { const instanceDataStorage = this._instanceDataStorage.renderPasses[this._instanceDataStorage.engine.isWebGPU ? this._instanceDataStorage.engine.currentRenderPassId : 0]; return instanceDataStorage ? instanceDataStorage.instancesData : void 0; } /** Gets the array buffer used to store the instanced buffer used for instances' previous world matrices */ get previousWorldMatrixInstancedBuffer() { const instanceDataStorage = this._instanceDataStorage.renderPasses[this._instanceDataStorage.engine.isWebGPU ? this._instanceDataStorage.engine.currentRenderPassId : 0]; return instanceDataStorage ? instanceDataStorage.instancesPreviousData : void 0; } /** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices is manual */ get manualUpdateOfWorldMatrixInstancedBuffer() { return this._instanceDataStorage.manualUpdate; } set manualUpdateOfWorldMatrixInstancedBuffer(value) { this._instanceDataStorage.manualUpdate = value; } /** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices is manual */ get manualUpdateOfPreviousWorldMatrixInstancedBuffer() { return this._instanceDataStorage.previousManualUpdate; } set manualUpdateOfPreviousWorldMatrixInstancedBuffer(value) { this._instanceDataStorage.previousManualUpdate = value; } /** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices must be performed in all cases (and notably even in frozen mode) */ get forceWorldMatrixInstancedBufferUpdate() { return this._instanceDataStorage.forceMatrixUpdates; } set forceWorldMatrixInstancedBufferUpdate(value) { this._instanceDataStorage.forceMatrixUpdates = value; } _copySource(source, doNotCloneChildren, clonePhysicsImpostor = true, cloneThinInstances = false) { const scene = this.getScene(); if (source._geometry) { source._geometry.applyToMesh(this); } DeepCopier.DeepCopy(source, this, [ "name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata", "morphTargetManager", "hasInstances", "worldMatrixInstancedBuffer", "previousWorldMatrixInstancedBuffer", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen", "facetNb", "isFacetDataEnabled", "lightSources", "useBones", "isAnInstance", "collider", "edgesRenderer", "forward", "up", "right", "absolutePosition", "absoluteScaling", "absoluteRotationQuaternion", "isWorldMatrixFrozen", "nonUniformScaling", "behaviors", "worldMatrixFromCache", "hasThinInstances", "cloneMeshMap", "hasBoundingInfo", "physicsBody", "physicsImpostor" ], ["_poseMatrix"]); this._internalMeshDataInfo._source = source; if (scene.useClonedMeshMap) { if (!source._internalMeshDataInfo.meshMap) { source._internalMeshDataInfo.meshMap = {}; } source._internalMeshDataInfo.meshMap[this.uniqueId] = this; } this._originalBuilderSideOrientation = source._originalBuilderSideOrientation; this._creationDataStorage = source._creationDataStorage; if (source._ranges) { const ranges = source._ranges; for (const name260 in ranges) { if (!Object.prototype.hasOwnProperty.call(ranges, name260)) { continue; } if (!ranges[name260]) { continue; } this.createAnimationRange(name260, ranges[name260].from, ranges[name260].to); } } if (source.metadata && source.metadata.clone) { this.metadata = source.metadata.clone(); } else { this.metadata = source.metadata; } this._internalMetadata = source._internalMetadata; if (Tags && Tags.HasTags(source)) { Tags.AddTagsTo(this, Tags.GetTags(source, true)); } this.setEnabled(source.isEnabled(false)); this.parent = source.parent; this.setPivotMatrix(source.getPivotMatrix(), this._postMultiplyPivotMatrix); this.id = this.name + "." + source.id; this.material = source.material; if (!doNotCloneChildren) { const directDescendants = source.getDescendants(true); for (let index = 0; index < directDescendants.length; index++) { const child = directDescendants[index]; if (child._isMesh) { MeshCreationOptions.parent = this; MeshCreationOptions.doNotCloneChildren = doNotCloneChildren; MeshCreationOptions.clonePhysicsImpostor = clonePhysicsImpostor; MeshCreationOptions.cloneThinInstances = cloneThinInstances; child.clone(this.name + "." + child.name, MeshCreationOptions); } else if (child.clone) { child.clone(this.name + "." + child.name, this); } } } if (source.morphTargetManager) { this.morphTargetManager = source.morphTargetManager; } if (scene.getPhysicsEngine) { const physicsEngine = scene.getPhysicsEngine(); if (clonePhysicsImpostor && physicsEngine) { if (physicsEngine.getPluginVersion() === 1) { const impostor = physicsEngine.getImpostorForPhysicsObject(source); if (impostor) { this.physicsImpostor = impostor.clone(this); } } else if (physicsEngine.getPluginVersion() === 2) { if (source.physicsBody) { source.physicsBody.clone(this); } } } } for (let index = 0; index < scene.particleSystems.length; index++) { const system = scene.particleSystems[index]; if (system.emitter === source) { system.clone(system.name, this); } } this.skeleton = source.skeleton; if (cloneThinInstances) { if (source._thinInstanceDataStorage.matrixData) { this.thinInstanceSetBuffer("matrix", new Float32Array(source._thinInstanceDataStorage.matrixData), 16, !source._thinInstanceDataStorage.matrixBuffer.isUpdatable()); this._thinInstanceDataStorage.matrixBufferSize = source._thinInstanceDataStorage.matrixBufferSize; this._thinInstanceDataStorage.instancesCount = source._thinInstanceDataStorage.instancesCount; } else { this._thinInstanceDataStorage.matrixBufferSize = source._thinInstanceDataStorage.matrixBufferSize; } if (source._userThinInstanceBuffersStorage) { const userThinInstance = source._userThinInstanceBuffersStorage; for (const kind in userThinInstance.data) { this.thinInstanceSetBuffer(kind, new Float32Array(userThinInstance.data[kind]), userThinInstance.strides[kind], !userThinInstance.vertexBuffers?.[kind]?.isUpdatable()); this._userThinInstanceBuffersStorage.sizes[kind] = userThinInstance.sizes[kind]; } } } this.refreshBoundingInfo(true, true); this.computeWorldMatrix(true); } /** @internal */ constructor(name260, scene = null, parentOrOptions = null, source = null, doNotCloneChildren, clonePhysicsImpostor = true) { super(name260, scene); this._internalMeshDataInfo = new _InternalMeshDataInfo(); this.delayLoadState = 0; this.instances = []; this._creationDataStorage = null; this._geometry = null; this._thinInstanceDataStorage = new _ThinInstanceDataStorage(); this._shouldGenerateFlatShading = false; this._originalBuilderSideOrientation = _Mesh.DEFAULTSIDE; this.ignoreCameraMaxZ = false; scene = this.getScene(); this._instanceDataStorage = new _InstanceDataStorage(); this._instanceDataStorage.engine = scene.getEngine(); if (this._scene.useRightHandedSystem) { this.sideOrientation = 0; } else { this.sideOrientation = 1; } this._onBeforeDraw = (isInstance, world, effectiveMaterial) => { if (isInstance && effectiveMaterial) { if (this._uniformBuffer) { this.transferToEffect(world); } else { effectiveMaterial.bindOnlyWorldMatrix(world); } } }; let parent = null; let cloneThinInstances = false; if (parentOrOptions && parentOrOptions._addToSceneRootNodes === void 0) { const options = parentOrOptions; parent = options.parent ?? null; source = options.source ?? null; doNotCloneChildren = options.doNotCloneChildren ?? false; clonePhysicsImpostor = options.clonePhysicsImpostor ?? true; cloneThinInstances = options.cloneThinInstances ?? false; } else { parent = parentOrOptions; } if (source) { this._copySource(source, doNotCloneChildren, clonePhysicsImpostor, cloneThinInstances); } if (parent !== null) { this.parent = parent; } this._instanceDataStorage.hardwareInstancedRendering = this.getEngine().getCaps().instancedArrays; this._internalMeshDataInfo._onMeshReadyObserverAdded = (observer) => { observer.unregisterOnNextCall = true; if (this.isReady(true)) { this.onMeshReadyObservable.notifyObservers(this); } else { if (!this._internalMeshDataInfo._checkReadinessObserver) { this._internalMeshDataInfo._checkReadinessObserver = this._scene.onBeforeRenderObservable.add(() => { if (this.isReady(true)) { this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver); this._internalMeshDataInfo._checkReadinessObserver = null; this.onMeshReadyObservable.notifyObservers(this); } }); } } }; this.onMeshReadyObservable = new Observable(this._internalMeshDataInfo._onMeshReadyObserverAdded); if (source) { source.onClonedObservable.notifyObservers(this); } } instantiateHierarchy(newParent = null, options, onNewNodeCreated) { const instance = this.getTotalVertices() === 0 || options && options.doNotInstantiate && (options.doNotInstantiate === true || options.doNotInstantiate(this)) ? this.clone("Clone of " + (this.name || this.id), newParent || this.parent, true) : this.createInstance("instance of " + (this.name || this.id)); instance.parent = newParent || this.parent; instance.position = this.position.clone(); instance.scaling = this.scaling.clone(); if (this.rotationQuaternion) { instance.rotationQuaternion = this.rotationQuaternion.clone(); } else { instance.rotation = this.rotation.clone(); } if (onNewNodeCreated) { onNewNodeCreated(this, instance); } for (const child of this.getChildTransformNodes(true)) { if (child.getClassName() === "InstancedMesh" && instance.getClassName() === "Mesh" && child.sourceMesh === this) { child.instantiateHierarchy(instance, { doNotInstantiate: options && options.doNotInstantiate || false, newSourcedMesh: instance }, onNewNodeCreated); } else { child.instantiateHierarchy(instance, options, onNewNodeCreated); } } return instance; } /** * Gets the class name * @returns the string "Mesh". */ getClassName() { return "Mesh"; } /** @internal */ get _isMesh() { return true; } /** * Returns a description of this mesh * @param fullDetails define if full details about this mesh must be used * @returns a descriptive string representing this mesh */ toString(fullDetails) { let ret = super.toString(fullDetails); ret += ", n vertices: " + this.getTotalVertices(); ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : this.parent ? this.parent.name : "NONE"); if (this.animations) { for (let i = 0; i < this.animations.length; i++) { ret += ", animation[0]: " + this.animations[i].toString(fullDetails); } } if (fullDetails) { if (this._geometry) { const ib = this.getIndices(); const vb = this.getVerticesData(VertexBuffer.PositionKind); if (vb && ib) { ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO"); } } else { ret += ", flat shading: UNKNOWN"; } } return ret; } /** @internal */ _unBindEffect() { super._unBindEffect(); for (const instance of this.instances) { instance._unBindEffect(); } } /** * Gets a boolean indicating if this mesh has LOD */ get hasLODLevels() { return this._internalMeshDataInfo._LODLevels.length > 0; } /** * Gets the list of MeshLODLevel associated with the current mesh * @returns an array of MeshLODLevel */ getLODLevels() { return this._internalMeshDataInfo._LODLevels; } _sortLODLevels() { const sortingOrderFactor = this._internalMeshDataInfo._useLODScreenCoverage ? -1 : 1; this._internalMeshDataInfo._LODLevels.sort((a, b) => { if (a.distanceOrScreenCoverage < b.distanceOrScreenCoverage) { return sortingOrderFactor; } if (a.distanceOrScreenCoverage > b.distanceOrScreenCoverage) { return -sortingOrderFactor; } return 0; }); } /** * Add a mesh as LOD level triggered at the given distance. * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD * @param distanceOrScreenCoverage Either distance from the center of the object to show this level or the screen coverage if `useScreenCoverage` is set to `true`. * If screen coverage, value is a fraction of the screen's total surface, between 0 and 1. * Example Playground for distance https://playground.babylonjs.com/#QE7KM#197 * Example Playground for screen coverage https://playground.babylonjs.com/#QE7KM#196 * @param mesh The mesh to be added as LOD level (can be null) * @returns This mesh (for chaining) */ addLODLevel(distanceOrScreenCoverage, mesh) { if (mesh && mesh._masterMesh) { Logger.Warn("You cannot use a mesh as LOD level twice"); return this; } const level = new MeshLODLevel(distanceOrScreenCoverage, mesh); this._internalMeshDataInfo._LODLevels.push(level); if (mesh) { mesh._masterMesh = this; } this._sortLODLevels(); return this; } /** * Returns the LOD level mesh at the passed distance or null if not found. * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD * @param distance The distance from the center of the object to show this level * @returns a Mesh or `null` */ getLODLevelAtDistance(distance) { const internalDataInfo = this._internalMeshDataInfo; for (let index = 0; index < internalDataInfo._LODLevels.length; index++) { const level = internalDataInfo._LODLevels[index]; if (level.distanceOrScreenCoverage === distance) { return level.mesh; } } return null; } /** * Remove a mesh from the LOD array * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD * @param mesh defines the mesh to be removed * @returns This mesh (for chaining) */ removeLODLevel(mesh) { const internalDataInfo = this._internalMeshDataInfo; for (let index = 0; index < internalDataInfo._LODLevels.length; index++) { if (internalDataInfo._LODLevels[index].mesh === mesh) { internalDataInfo._LODLevels.splice(index, 1); if (mesh) { mesh._masterMesh = null; } } } this._sortLODLevels(); return this; } /** * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh. * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/LOD * @param camera defines the camera to use to compute distance * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh * @returns This mesh (for chaining) */ getLOD(camera, boundingSphere) { const internalDataInfo = this._internalMeshDataInfo; if (!internalDataInfo._LODLevels || internalDataInfo._LODLevels.length === 0) { return this; } const bSphere = boundingSphere || this.getBoundingInfo().boundingSphere; const distanceToCamera = camera.mode === Camera.ORTHOGRAPHIC_CAMERA ? camera.minZ : bSphere.centerWorld.subtract(camera.globalPosition).length(); let compareValue = distanceToCamera; let compareSign = 1; if (internalDataInfo._useLODScreenCoverage) { const screenArea = camera.screenArea; let meshArea = bSphere.radiusWorld * camera.minZ / distanceToCamera; meshArea = meshArea * meshArea * Math.PI; compareValue = meshArea / screenArea; compareSign = -1; } if (compareSign * internalDataInfo._LODLevels[internalDataInfo._LODLevels.length - 1].distanceOrScreenCoverage > compareSign * compareValue) { if (this.onLODLevelSelection) { this.onLODLevelSelection(compareValue, this, this); } return this; } for (let index = 0; index < internalDataInfo._LODLevels.length; index++) { const level = internalDataInfo._LODLevels[index]; if (compareSign * level.distanceOrScreenCoverage < compareSign * compareValue) { if (level.mesh) { if (level.mesh.delayLoadState === 4) { level.mesh._checkDelayState(); return this; } if (level.mesh.delayLoadState === 2) { return this; } level.mesh._preActivate(); level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache); } if (this.onLODLevelSelection) { this.onLODLevelSelection(compareValue, this, level.mesh); } return level.mesh; } } if (this.onLODLevelSelection) { this.onLODLevelSelection(compareValue, this, this); } return this; } /** * Gets the mesh internal Geometry object */ get geometry() { return this._geometry; } /** * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry. * @returns the total number of vertices */ getTotalVertices() { if (this._geometry === null || this._geometry === void 0) { return 0; } return this._geometry.getTotalVertices(); } /** * Returns the content of an associated vertex buffer * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values : * - VertexBuffer.PositionKind * - VertexBuffer.UVKind * - VertexBuffer.UV2Kind * - VertexBuffer.UV3Kind * - VertexBuffer.UV4Kind * - VertexBuffer.UV5Kind * - VertexBuffer.UV6Kind * - VertexBuffer.ColorKind * - VertexBuffer.MatricesIndicesKind * - VertexBuffer.MatricesIndicesExtraKind * - VertexBuffer.MatricesWeightsKind * - VertexBuffer.MatricesWeightsExtraKind * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind. */ getVerticesData(kind, copyWhenShared, forceCopy, bypassInstanceData) { if (!this._geometry) { return null; } let data = bypassInstanceData ? void 0 : this._userInstancedBuffersStorage?.vertexBuffers[kind]?.getFloatData( this.instances.length + 1, // +1 because the master mesh is not included in the instances array forceCopy || copyWhenShared && this._geometry.meshes.length !== 1 ); if (!data) { data = this._geometry.getVerticesData(kind, copyWhenShared, forceCopy); } return data; } copyVerticesData(kind, vertexData) { if (this._geometry) { this._geometry.copyVerticesData(kind, vertexData); } } getVertexBuffer(kind, bypassInstanceData) { if (!this._geometry) { return null; } return (bypassInstanceData ? void 0 : this._userInstancedBuffersStorage?.vertexBuffers[kind]) ?? this._geometry.getVertexBuffer(kind); } /** * Tests if a specific vertex buffer is associated with this mesh * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values : * - VertexBuffer.PositionKind * - VertexBuffer.NormalKind * - VertexBuffer.UVKind * - VertexBuffer.UV2Kind * - VertexBuffer.UV3Kind * - VertexBuffer.UV4Kind * - VertexBuffer.UV5Kind * - VertexBuffer.UV6Kind * - VertexBuffer.ColorKind * - VertexBuffer.MatricesIndicesKind * - VertexBuffer.MatricesIndicesExtraKind * - VertexBuffer.MatricesWeightsKind * - VertexBuffer.MatricesWeightsExtraKind * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false * @returns a boolean */ isVerticesDataPresent(kind, bypassInstanceData) { if (!this._geometry) { if (this._delayInfo) { return this._delayInfo.indexOf(kind) !== -1; } return false; } return !bypassInstanceData && this._userInstancedBuffersStorage?.vertexBuffers[kind] !== void 0 || this._geometry.isVerticesDataPresent(kind); } /** * Returns a boolean defining if the vertex data for the requested `kind` is updatable. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values : * - VertexBuffer.PositionKind * - VertexBuffer.UVKind * - VertexBuffer.UV2Kind * - VertexBuffer.UV3Kind * - VertexBuffer.UV4Kind * - VertexBuffer.UV5Kind * - VertexBuffer.UV6Kind * - VertexBuffer.ColorKind * - VertexBuffer.MatricesIndicesKind * - VertexBuffer.MatricesIndicesExtraKind * - VertexBuffer.MatricesWeightsKind * - VertexBuffer.MatricesWeightsExtraKind * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false * @returns a boolean */ isVertexBufferUpdatable(kind, bypassInstanceData) { if (!this._geometry) { if (this._delayInfo) { return this._delayInfo.indexOf(kind) !== -1; } return false; } if (!bypassInstanceData) { const buffer = this._userInstancedBuffersStorage?.vertexBuffers[kind]; if (buffer) { return buffer.isUpdatable(); } } return this._geometry.isVertexBufferUpdatable(kind); } /** * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh. * @param bypassInstanceData defines a boolean indicating that the function should not take into account the instance data (applies only if the mesh has instances). Default: false * @returns an array of strings */ getVerticesDataKinds(bypassInstanceData) { if (!this._geometry) { const result = []; if (this._delayInfo) { for (const kind of this._delayInfo) { result.push(kind); } } return result; } const kinds = this._geometry.getVerticesDataKinds(); if (!bypassInstanceData && this._userInstancedBuffersStorage) { for (const kind in this._userInstancedBuffersStorage.vertexBuffers) { if (kinds.indexOf(kind) === -1) { kinds.push(kind); } } } return kinds; } /** * Returns a positive integer : the total number of indices in this mesh geometry. * @returns the number of indices or zero if the mesh has no geometry. */ getTotalIndices() { if (!this._geometry) { return 0; } return this._geometry.getTotalIndices(); } /** * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices. * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it * @returns the indices array or an empty array if the mesh has no geometry */ getIndices(copyWhenShared, forceCopy) { if (!this._geometry) { return []; } return this._geometry.getIndices(copyWhenShared, forceCopy); } get isBlocked() { return this._masterMesh !== null && this._masterMesh !== void 0; } /** * Determine if the current mesh is ready to be rendered * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default) * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default) * @returns true if all associated assets are ready (material, textures, shaders) */ isReady(completeCheck = false, forceInstanceSupport = false) { if (this.delayLoadState === 2) { return false; } if (!super.isReady(completeCheck)) { return false; } if (!this.subMeshes || this.subMeshes.length === 0) { return true; } if (!completeCheck) { return true; } const engine = this.getEngine(); const scene = this.getScene(); const hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && (this.instances.length > 0 || this.hasThinInstances); this.computeWorldMatrix(); const mat = this.material || scene.defaultMaterial; if (mat) { if (mat._storeEffectOnSubMeshes) { for (const subMesh of this.subMeshes) { const effectiveMaterial = subMesh.getMaterial(); if (effectiveMaterial) { if (effectiveMaterial._storeEffectOnSubMeshes) { if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) { return false; } } else { if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) { return false; } } } } } else { if (!mat.isReady(this, hardwareInstancedRendering)) { return false; } } } const currentRenderPassId = engine.currentRenderPassId; for (const light of this.lightSources) { const generators = light.getShadowGenerators(); if (!generators) { continue; } const iterator = generators.values(); for (let key = iterator.next(); key.done !== true; key = iterator.next()) { const generator = key.value; if (generator && (!generator.getShadowMap()?.renderList || generator.getShadowMap()?.renderList && generator.getShadowMap()?.renderList?.indexOf(this) !== -1)) { const shadowMap = generator.getShadowMap(); const renderPassIds = shadowMap.renderPassIds ?? [engine.currentRenderPassId]; for (let p = 0; p < renderPassIds.length; ++p) { engine.currentRenderPassId = renderPassIds[p]; for (const subMesh of this.subMeshes) { if (!generator.isReady(subMesh, hardwareInstancedRendering, subMesh.getMaterial()?.needAlphaBlendingForMesh(this) ?? false)) { engine.currentRenderPassId = currentRenderPassId; return false; } } } engine.currentRenderPassId = currentRenderPassId; } } } for (const lod of this._internalMeshDataInfo._LODLevels) { if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) { return false; } } return true; } /** * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes. */ get areNormalsFrozen() { return this._internalMeshDataInfo._areNormalsFrozen; } /** * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update. * @returns the current mesh */ freezeNormals() { this._internalMeshDataInfo._areNormalsFrozen = true; return this; } /** * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen * @returns the current mesh */ unfreezeNormals() { this._internalMeshDataInfo._areNormalsFrozen = false; return this; } /** * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs */ set overridenInstanceCount(count) { this._instanceDataStorage.overridenInstanceCount = count; } /** @internal */ _getInstanceDataStorage() { const renderPassId = this._instanceDataStorage.engine.isWebGPU ? this._instanceDataStorage.engine.currentRenderPassId : 0; let instanceDataStorage = this._instanceDataStorage.renderPasses[renderPassId]; if (!instanceDataStorage) { instanceDataStorage = new _InstanceDataStorageRenderPass(); this._instanceDataStorage.renderPasses[renderPassId] = instanceDataStorage; } return instanceDataStorage; } // Methods /** @internal */ _preActivate() { const internalDataInfo = this._internalMeshDataInfo; const sceneRenderId = this.getScene().getRenderId(); if (internalDataInfo._preActivateId === sceneRenderId) { return this; } internalDataInfo._preActivateId = sceneRenderId; this._getInstanceDataStorage().visibleInstances = null; return this; } /** * @internal */ _preActivateForIntermediateRendering(renderId) { const instanceDataStorage = this._getInstanceDataStorage(); if (instanceDataStorage.visibleInstances) { instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId; } return this; } /** * @internal */ _registerInstanceForRenderId(instance, renderId) { const instanceDataStorage = this._getInstanceDataStorage(); if (!instanceDataStorage.visibleInstances) { instanceDataStorage.visibleInstances = { defaultRenderId: renderId, selfDefaultRenderId: this._renderId, intermediateDefaultRenderId: -1 }; } if (!instanceDataStorage.visibleInstances[renderId]) { if (instanceDataStorage.previousRenderId !== void 0 && this._instanceDataStorage.isFrozen) { instanceDataStorage.visibleInstances[instanceDataStorage.previousRenderId] = null; } instanceDataStorage.previousRenderId = renderId; instanceDataStorage.visibleInstances[renderId] = new Array(); } instanceDataStorage.visibleInstances[renderId].push(instance); return this; } _afterComputeWorldMatrix() { super._afterComputeWorldMatrix(); if (!this.hasThinInstances) { return; } if (!this.doNotSyncBoundingInfo) { this.thinInstanceRefreshBoundingInfo(false); } } /** @internal */ _postActivate() { if (this.edgesShareWithInstances && this.edgesRenderer && this.edgesRenderer.isEnabled && this._renderingGroup) { this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer); this.edgesRenderer.customInstances.push(this.getWorldMatrix()); } } /** * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked. * This means the mesh underlying bounding box and sphere are recomputed. * @param applySkeletonOrOptions defines whether to apply the skeleton before computing the bounding info or a set of options * @param applyMorph defines whether to apply the morph target before computing the bounding info * @returns the current mesh */ refreshBoundingInfo(applySkeletonOrOptions = false, applyMorph = false) { if (this.hasBoundingInfo && this.getBoundingInfo().isLocked) { return this; } let options; if (typeof applySkeletonOrOptions === "object") { options = applySkeletonOrOptions; } else { options = { applySkeleton: applySkeletonOrOptions, applyMorph }; } const bias = this.geometry ? this.geometry.boundingBias : null; this._refreshBoundingInfo(this._getData(options, null, VertexBuffer.PositionKind), bias); return this; } /** * @internal */ _createGlobalSubMesh(force) { const totalVertices = this.getTotalVertices(); if (!totalVertices || !this.getIndices()) { return null; } if (this.subMeshes && this.subMeshes.length > 0) { const ib = this.getIndices(); if (!ib) { return null; } const totalIndices = ib.length; let needToRecreate = false; if (force) { needToRecreate = true; } else { for (const submesh of this.subMeshes) { if (submesh.indexStart + submesh.indexCount > totalIndices) { needToRecreate = true; break; } if (submesh.verticesStart + submesh.verticesCount > totalVertices) { needToRecreate = true; break; } } } if (!needToRecreate) { return this.subMeshes[0]; } } this.releaseSubMeshes(); return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices() || (this.isUnIndexed ? totalVertices : 0), this); } /** * This function will subdivide the mesh into multiple submeshes * @param count defines the expected number of submeshes */ subdivide(count) { if (count < 1) { return; } const totalIndices = this.getTotalIndices(); let subdivisionSize = totalIndices / count | 0; let offset = 0; while (subdivisionSize % 3 !== 0) { subdivisionSize++; } this.releaseSubMeshes(); for (let index = 0; index < count; index++) { if (offset >= totalIndices) { break; } SubMesh.CreateFromIndices(0, offset, index === count - 1 ? totalIndices - offset : subdivisionSize, this, void 0, false); offset += subdivisionSize; } this.refreshBoundingInfo(); this.synchronizeInstances(); } /** * Copy a FloatArray into a specific associated vertex buffer * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values : * - VertexBuffer.PositionKind * - VertexBuffer.UVKind * - VertexBuffer.UV2Kind * - VertexBuffer.UV3Kind * - VertexBuffer.UV4Kind * - VertexBuffer.UV5Kind * - VertexBuffer.UV6Kind * - VertexBuffer.ColorKind * - VertexBuffer.MatricesIndicesKind * - VertexBuffer.MatricesIndicesExtraKind * - VertexBuffer.MatricesWeightsKind * - VertexBuffer.MatricesWeightsExtraKind * @param data defines the data source * @param updatable defines if the updated vertex buffer must be flagged as updatable * @param stride defines the data stride size (can be null) * @returns the current mesh */ setVerticesData(kind, data, updatable = false, stride) { if (!this._geometry) { const vertexData = new VertexData(); vertexData.set(data, kind); const scene = this.getScene(); new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this); } else { this._geometry.setVerticesData(kind, data, updatable, stride); } return this; } /** * Delete a vertex buffer associated with this mesh * @param kind defines which buffer to delete (positions, indices, normals, etc). Possible `kind` values : * - VertexBuffer.PositionKind * - VertexBuffer.UVKind * - VertexBuffer.UV2Kind * - VertexBuffer.UV3Kind * - VertexBuffer.UV4Kind * - VertexBuffer.UV5Kind * - VertexBuffer.UV6Kind * - VertexBuffer.ColorKind * - VertexBuffer.MatricesIndicesKind * - VertexBuffer.MatricesIndicesExtraKind * - VertexBuffer.MatricesWeightsKind * - VertexBuffer.MatricesWeightsExtraKind */ removeVerticesData(kind) { if (!this._geometry) { return; } this._geometry.removeVerticesData(kind); } /** * Flags an associated vertex buffer as updatable * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values : * - VertexBuffer.PositionKind * - VertexBuffer.UVKind * - VertexBuffer.UV2Kind * - VertexBuffer.UV3Kind * - VertexBuffer.UV4Kind * - VertexBuffer.UV5Kind * - VertexBuffer.UV6Kind * - VertexBuffer.ColorKind * - VertexBuffer.MatricesIndicesKind * - VertexBuffer.MatricesIndicesExtraKind * - VertexBuffer.MatricesWeightsKind * - VertexBuffer.MatricesWeightsExtraKind * @param updatable defines if the updated vertex buffer must be flagged as updatable */ markVerticesDataAsUpdatable(kind, updatable = true) { const vb = this.getVertexBuffer(kind); if (!vb || vb.isUpdatable() === updatable) { return; } this.setVerticesData(kind, this.getVerticesData(kind), updatable); } /** * Sets the mesh global Vertex Buffer * @param buffer defines the buffer to use * @param disposeExistingBuffer disposes the existing buffer, if any (default: true) * @returns the current mesh */ setVerticesBuffer(buffer, disposeExistingBuffer = true) { if (!this._geometry) { this._geometry = Geometry.CreateGeometryForMesh(this); } this._geometry.setVerticesBuffer(buffer, null, disposeExistingBuffer); return this; } /** * Update a specific associated vertex buffer * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values : * - VertexBuffer.PositionKind * - VertexBuffer.UVKind * - VertexBuffer.UV2Kind * - VertexBuffer.UV3Kind * - VertexBuffer.UV4Kind * - VertexBuffer.UV5Kind * - VertexBuffer.UV6Kind * - VertexBuffer.ColorKind * - VertexBuffer.MatricesIndicesKind * - VertexBuffer.MatricesIndicesExtraKind * - VertexBuffer.MatricesWeightsKind * - VertexBuffer.MatricesWeightsExtraKind * @param data defines the data source * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry) * @returns the current mesh */ updateVerticesData(kind, data, updateExtends, makeItUnique) { if (!this._geometry) { return this; } if (!makeItUnique) { this._geometry.updateVerticesData(kind, data, updateExtends); } else { this.makeGeometryUnique(); this.updateVerticesData(kind, data, updateExtends, false); } return this; } /** * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values. * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#other-shapes-updatemeshpositions * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update * @returns the current mesh */ updateMeshPositions(positionFunction, computeNormals = true) { const positions = this.getVerticesData(VertexBuffer.PositionKind); if (!positions) { return this; } positionFunction(positions); this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false); if (computeNormals) { const indices = this.getIndices(); const normals = this.getVerticesData(VertexBuffer.NormalKind); if (!normals) { return this; } VertexData.ComputeNormals(positions, indices, normals); this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false); } return this; } /** * Creates a un-shared specific occurence of the geometry for the mesh. * @returns the current mesh */ makeGeometryUnique() { if (!this._geometry) { return this; } if (this._geometry.meshes.length === 1) { return this; } const oldGeometry = this._geometry; const geometry = this._geometry.copy(Geometry.RandomId()); oldGeometry.releaseForMesh(this, true); geometry.applyToMesh(this); return this; } /** * Sets the index buffer of this mesh. * @param indexBuffer Defines the index buffer to use for this mesh * @param totalVertices Defines the total number of vertices used by the buffer * @param totalIndices Defines the total number of indices in the index buffer * @param is32Bits Defines if the indices are 32 bits. If null (default), the value is guessed from the number of vertices */ setIndexBuffer(indexBuffer, totalVertices, totalIndices, is32Bits = null) { let geometry = this._geometry; if (!geometry) { geometry = new Geometry(Geometry.RandomId(), this.getScene(), void 0, void 0, this); } geometry.setIndexBuffer(indexBuffer, totalVertices, totalIndices, is32Bits); } /** * Set the index buffer of this mesh * @param indices defines the source data * @param totalVertices defines the total number of vertices referenced by this index data (can be null) * @param updatable defines if the updated index buffer must be flagged as updatable (default is false) * @param dontForceSubMeshRecreation defines a boolean indicating that we don't want to force the recreation of sub-meshes if we don't have to (false by default) * @returns the current mesh */ setIndices(indices, totalVertices = null, updatable = false, dontForceSubMeshRecreation = false) { if (!this._geometry) { const vertexData = new VertexData(); vertexData.indices = indices; const scene = this.getScene(); new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this); } else { this._geometry.setIndices(indices, totalVertices, updatable, dontForceSubMeshRecreation); } return this; } /** * Update the current index buffer * @param indices defines the source data * @param offset defines the offset in the index buffer where to store the new data (can be null) * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default) * @returns the current mesh */ updateIndices(indices, offset, gpuMemoryOnly = false) { if (!this._geometry) { return this; } this._geometry.updateIndices(indices, offset, gpuMemoryOnly); return this; } /** * Invert the geometry to move from a right handed system to a left handed one. * @returns the current mesh */ toLeftHanded() { if (!this._geometry) { return this; } this._geometry.toLeftHanded(); return this; } /** * @internal */ _bind(subMesh, effect, fillMode, allowInstancedRendering = true) { if (!this._geometry) { return this; } const engine = this.getScene().getEngine(); let indexToBind; if (this._unIndexed) { switch (this._getRenderingFillMode(fillMode)) { case Material.WireFrameFillMode: indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine); break; default: indexToBind = null; break; } } else { switch (this._getRenderingFillMode(fillMode)) { case Material.PointFillMode: indexToBind = null; break; case Material.WireFrameFillMode: indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine); break; default: case Material.TriangleFillMode: indexToBind = this._geometry.getIndexBuffer(); break; } } return this._bindDirect(effect, indexToBind, allowInstancedRendering); } /** * @internal */ _bindDirect(effect, indexToBind, allowInstancedRendering = true) { if (!this._geometry) { return this; } if (this.morphTargetManager && this.morphTargetManager.isUsingTextureForTargets) { this.morphTargetManager._bind(effect); } if (!allowInstancedRendering || !this._userInstancedBuffersStorage || this.hasThinInstances) { this._geometry._bind(effect, indexToBind); } else { if (this._instanceDataStorage.engine.isWebGPU && this._userInstancedBuffersStorage.renderPasses && this._userInstancedBuffersStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId]) { const vertexBuffers = this._userInstancedBuffersStorage.renderPasses[this._instanceDataStorage.engine.currentRenderPassId]; for (const kind in vertexBuffers) { this._userInstancedBuffersStorage.vertexBuffers[kind] = vertexBuffers[kind]; } } this._geometry._bind(effect, indexToBind, this._userInstancedBuffersStorage.vertexBuffers, this._userInstancedBuffersStorage.vertexArrayObjects); } return this; } /** * @internal */ _draw(subMesh, fillMode, instancesCount) { if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer()) { return this; } if (this._internalMeshDataInfo._onBeforeDrawObservable) { this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this); } const scene = this.getScene(); const engine = scene.getEngine(); const currentMaterialContext = engine._currentMaterialContext; const useVertexPulling = currentMaterialContext && currentMaterialContext.useVertexPulling; if (this._unIndexed && fillMode !== Material.WireFrameFillMode || fillMode == Material.PointFillMode) { engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, this.forcedInstanceCount || instancesCount); } else if (fillMode == Material.WireFrameFillMode) { engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, this.forcedInstanceCount || instancesCount); } else if (useVertexPulling) { engine.drawArraysType(fillMode, subMesh.indexStart, subMesh.indexCount, this.forcedInstanceCount || instancesCount); } else { engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, this.forcedInstanceCount || instancesCount); } return this; } /** * Registers for this mesh a javascript function called just before the rendering process * @param func defines the function to call before rendering this mesh * @returns the current mesh */ registerBeforeRender(func) { this.onBeforeRenderObservable.add(func); return this; } /** * Disposes a previously registered javascript function called before the rendering * @param func defines the function to remove * @returns the current mesh */ unregisterBeforeRender(func) { this.onBeforeRenderObservable.removeCallback(func); return this; } /** * Registers for this mesh a javascript function called just after the rendering is complete * @param func defines the function to call after rendering this mesh * @returns the current mesh */ registerAfterRender(func) { this.onAfterRenderObservable.add(func); return this; } /** * Disposes a previously registered javascript function called after the rendering. * @param func defines the function to remove * @returns the current mesh */ unregisterAfterRender(func) { this.onAfterRenderObservable.removeCallback(func); return this; } /** * @internal */ _getInstancesRenderList(subMeshId, isReplacementMode = false) { const instanceDataStorage = this._getInstanceDataStorage(); if (this._instanceDataStorage.isFrozen) { if (isReplacementMode) { instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[subMeshId] = false; instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[subMeshId] = true; return instanceDataStorage.batchCacheReplacementModeInFrozenMode; } if (instanceDataStorage.previousBatch) { return instanceDataStorage.previousBatch; } } const scene = this.getScene(); const isInIntermediateRendering = scene._isInIntermediateRendering(); const onlyForInstances = isInIntermediateRendering ? this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate : this._internalAbstractMeshDataInfo._onlyForInstances; const batchCache = instanceDataStorage.batchCache; batchCache.mustReturn = false; batchCache.renderSelf[subMeshId] = isReplacementMode || !onlyForInstances && this.isEnabled() && this.isVisible; batchCache.visibleInstances[subMeshId] = null; if (instanceDataStorage.visibleInstances && !isReplacementMode) { const visibleInstances = instanceDataStorage.visibleInstances; const currentRenderId = scene.getRenderId(); const defaultRenderId = isInIntermediateRendering ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId; batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId]; if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) { batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId]; } } batchCache.hardwareInstancedRendering[subMeshId] = !isReplacementMode && this._instanceDataStorage.hardwareInstancedRendering && batchCache.visibleInstances[subMeshId] !== null && batchCache.visibleInstances[subMeshId] !== void 0; instanceDataStorage.previousBatch = batchCache; return batchCache; } /** * This method will also draw the instances if fillMode and effect are passed * @internal */ _updateInstancedBuffers(subMesh, batch, currentInstancesBufferSize, engine, fillMode, effect) { const visibleInstances = batch.visibleInstances[subMesh._id]; const visibleInstanceCount = visibleInstances ? visibleInstances.length : 0; const instanceStorage = batch.parent; const instanceDataStorage = this._instanceDataStorage; let instancesBuffer = instanceStorage.instancesBuffer; let instancesPreviousBuffer = instanceStorage.instancesPreviousBuffer; let offset = 0; let instancesCount = 0; const renderSelf = batch.renderSelf[subMesh._id]; const floatingOriginOffset = this._scene.floatingOriginOffset; const needUpdateBuffer = !instancesBuffer || currentInstancesBufferSize !== instanceStorage.instancesBufferSize || this._scene.needsPreviousWorldMatrices && !instanceStorage.instancesPreviousBuffer; if (!this._instanceDataStorage.manualUpdate && (!instanceDataStorage.isFrozen || needUpdateBuffer)) { const world = this.getWorldMatrix(); if (renderSelf) { if (this._scene.needsPreviousWorldMatrices) { if (!instanceDataStorage.masterMeshPreviousWorldMatrix) { instanceDataStorage.masterMeshPreviousWorldMatrix = world.clone(); instanceDataStorage.masterMeshPreviousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset); } else { instanceDataStorage.masterMeshPreviousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset); instanceDataStorage.masterMeshPreviousWorldMatrix.copyFrom(world); } } world.copyToArray(instanceStorage.instancesData, offset); instanceStorage.instancesData[offset + 12] -= floatingOriginOffset.x; instanceStorage.instancesData[offset + 13] -= floatingOriginOffset.y; instanceStorage.instancesData[offset + 14] -= floatingOriginOffset.z; offset += 16; instancesCount++; } if (visibleInstances) { if (_Mesh.INSTANCEDMESH_SORT_TRANSPARENT && this._scene.activeCamera && subMesh.getMaterial()?.needAlphaBlendingForMesh(subMesh.getRenderingMesh())) { const cameraPosition = this._scene.activeCamera.globalPosition; for (let instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) { const instanceMesh = visibleInstances[instanceIndex]; instanceMesh._distanceToCamera = Vector3.Distance(instanceMesh.getBoundingInfo().boundingSphere.centerWorld, cameraPosition); } visibleInstances.sort((m1, m2) => { return m1._distanceToCamera > m2._distanceToCamera ? -1 : m1._distanceToCamera < m2._distanceToCamera ? 1 : 0; }); } for (let instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) { const instance = visibleInstances[instanceIndex]; const matrix = instance.getWorldMatrix(); matrix.copyToArray(instanceStorage.instancesData, offset); if (this._scene.needsPreviousWorldMatrices) { if (!instance._previousWorldMatrix) { instance._previousWorldMatrix = matrix.clone(); instance._previousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset); } else { instance._previousWorldMatrix.copyToArray(instanceStorage.instancesPreviousData, offset); instance._previousWorldMatrix.copyFrom(matrix); } } instanceStorage.instancesData[offset + 12] -= floatingOriginOffset.x; instanceStorage.instancesData[offset + 13] -= floatingOriginOffset.y; instanceStorage.instancesData[offset + 14] -= floatingOriginOffset.z; offset += 16; instancesCount++; } } } else { instancesCount = (renderSelf ? 1 : 0) + visibleInstanceCount; } if (needUpdateBuffer) { if (instancesBuffer) { instancesBuffer.dispose(); } if (instancesPreviousBuffer) { instancesPreviousBuffer.dispose(); } instancesBuffer = new Buffer2(engine, instanceStorage.instancesData, true, 16, false, true); instanceStorage.instancesBuffer = instancesBuffer; if (!this._userInstancedBuffersStorage) { this._userInstancedBuffersStorage = { data: {}, vertexBuffers: {}, strides: {}, sizes: {}, vertexArrayObjects: this.getEngine().getCaps().vertexArrayObject ? {} : void 0 }; } let vertexAndArrayObjectBuffers; if (this._instanceDataStorage.engine.isWebGPU) { if (!this._userInstancedBuffersStorage.renderPasses) { this._userInstancedBuffersStorage.renderPasses = {}; } const currentRenderPassId = this._instanceDataStorage.engine.currentRenderPassId; vertexAndArrayObjectBuffers = this._userInstancedBuffersStorage.renderPasses[currentRenderPassId]; if (!vertexAndArrayObjectBuffers) { this._userInstancedBuffersStorage.renderPasses[currentRenderPassId] = vertexAndArrayObjectBuffers = {}; } } else { vertexAndArrayObjectBuffers = this._userInstancedBuffersStorage.vertexBuffers; } vertexAndArrayObjectBuffers["world0"] = instancesBuffer.createVertexBuffer("world0", 0, 4); vertexAndArrayObjectBuffers["world1"] = instancesBuffer.createVertexBuffer("world1", 4, 4); vertexAndArrayObjectBuffers["world2"] = instancesBuffer.createVertexBuffer("world2", 8, 4); vertexAndArrayObjectBuffers["world3"] = instancesBuffer.createVertexBuffer("world3", 12, 4); if (this._scene.needsPreviousWorldMatrices) { instancesPreviousBuffer = new Buffer2(engine, instanceStorage.instancesPreviousData, true, 16, false, true); instanceStorage.instancesPreviousBuffer = instancesPreviousBuffer; vertexAndArrayObjectBuffers["previousWorld0"] = instancesPreviousBuffer.createVertexBuffer("previousWorld0", 0, 4); vertexAndArrayObjectBuffers["previousWorld1"] = instancesPreviousBuffer.createVertexBuffer("previousWorld1", 4, 4); vertexAndArrayObjectBuffers["previousWorld2"] = instancesPreviousBuffer.createVertexBuffer("previousWorld2", 8, 4); vertexAndArrayObjectBuffers["previousWorld3"] = instancesPreviousBuffer.createVertexBuffer("previousWorld3", 12, 4); } this._invalidateInstanceVertexArrayObject(); } else { if (!this._instanceDataStorage.isFrozen || this._instanceDataStorage.forceMatrixUpdates) { instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount); if (this._scene.needsPreviousWorldMatrices && (!this._instanceDataStorage.manualUpdate || this._instanceDataStorage.previousManualUpdate)) { instancesPreviousBuffer.updateDirectly(instanceStorage.instancesPreviousData, 0, instancesCount); } } } this._processInstancedBuffers(visibleInstances, renderSelf); if (effect && fillMode !== void 0) { this.getScene()._activeIndices.addCount(subMesh.indexCount * instancesCount, false); if (engine._currentDrawContext) { engine._currentDrawContext.useInstancing = true; } this._bind(subMesh, effect, fillMode); this._draw(subMesh, fillMode, instancesCount); } if (this._scene.needsPreviousWorldMatrices && !needUpdateBuffer && this._instanceDataStorage.manualUpdate && (!this._instanceDataStorage.isFrozen || this._instanceDataStorage.forceMatrixUpdates) && !this._instanceDataStorage.previousManualUpdate) { instancesPreviousBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount); } } /** * @internal */ _renderWithInstances(subMesh, fillMode, batch, effect, engine) { const visibleInstances = batch.visibleInstances[subMesh._id]; const visibleInstanceCount = visibleInstances ? visibleInstances.length : 0; const instanceStorage = batch.parent; const currentInstancesBufferSize = instanceStorage.instancesBufferSize; const matricesCount = visibleInstanceCount + 1; const bufferSize = matricesCount * 16 * 4; while (instanceStorage.instancesBufferSize < bufferSize) { instanceStorage.instancesBufferSize *= 2; } if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) { instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4); } if (this._scene.needsPreviousWorldMatrices && !instanceStorage.instancesPreviousData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) { instanceStorage.instancesPreviousData = new Float32Array(instanceStorage.instancesBufferSize / 4); } this._updateInstancedBuffers(subMesh, batch, currentInstancesBufferSize, engine, fillMode, effect); engine.unbindInstanceAttributes(); return this; } /** * @internal */ _renderWithThinInstances(subMesh, fillMode, effect, engine) { const instancesCount = this._thinInstanceDataStorage?.instancesCount ?? 0; this.getScene()._activeIndices.addCount(subMesh.indexCount * instancesCount, false); if (engine._currentDrawContext) { engine._currentDrawContext.useInstancing = true; } this._bind(subMesh, effect, fillMode); this._draw(subMesh, fillMode, instancesCount); if (this._scene.needsPreviousWorldMatrices && !this._thinInstanceDataStorage.previousMatrixData && this._thinInstanceDataStorage.matrixData) { if (!this._thinInstanceDataStorage.previousMatrixBuffer) { this._thinInstanceDataStorage.previousMatrixBuffer = this._thinInstanceCreateMatrixBuffer("previousWorld", this._thinInstanceDataStorage.matrixData, false); } else { this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData, 0, instancesCount); } } engine.unbindInstanceAttributes(); } /** * @internal */ // eslint-disable-next-line @typescript-eslint/no-unused-vars _processInstancedBuffers(visibleInstances, renderSelf) { } /** * @internal */ _processRendering(renderingMesh, subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) { const scene = this.getScene(); const engine = scene.getEngine(); fillMode = this._getRenderingFillMode(fillMode); if (hardwareInstancedRendering && subMesh.getRenderingMesh().hasThinInstances) { this._renderWithThinInstances(subMesh, fillMode, effect, engine); return this; } if (hardwareInstancedRendering) { this._renderWithInstances(subMesh, fillMode, batch, effect, engine); } else { if (engine._currentDrawContext) { engine._currentDrawContext.useInstancing = false; } let instanceCount = 0; if (batch.renderSelf[subMesh._id]) { if (onBeforeDraw) { onBeforeDraw(false, renderingMesh.getWorldMatrix(), effectiveMaterial); } instanceCount++; this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount); } const visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id]; if (visibleInstancesForSubMesh) { const visibleInstanceCount = visibleInstancesForSubMesh.length; instanceCount += visibleInstanceCount; for (let instanceIndex = 0; instanceIndex < visibleInstanceCount; instanceIndex++) { const instance = visibleInstancesForSubMesh[instanceIndex]; const world = instance.getWorldMatrix(); if (onBeforeDraw) { onBeforeDraw(true, world, effectiveMaterial); } this._draw(subMesh, fillMode); } } scene._activeIndices.addCount(subMesh.indexCount * instanceCount, false); } return this; } /** * @internal */ _rebuild(dispose = false) { for (const renderPassId in this._instanceDataStorage.renderPasses) { const instanceDataStorage = this._instanceDataStorage.renderPasses[renderPassId]; if (instanceDataStorage.instancesBuffer) { if (dispose) { instanceDataStorage.instancesBuffer.dispose(); } instanceDataStorage.instancesBuffer = null; } } if (this._userInstancedBuffersStorage) { for (const kind in this._userInstancedBuffersStorage.vertexBuffers) { const buffer = this._userInstancedBuffersStorage.vertexBuffers[kind]; if (buffer) { if (dispose) { buffer.dispose(); } this._userInstancedBuffersStorage.vertexBuffers[kind] = null; } } if (this._userInstancedBuffersStorage.vertexArrayObjects) { this._userInstancedBuffersStorage.vertexArrayObjects = {}; } } this._internalMeshDataInfo._effectiveMaterial = null; super._rebuild(dispose); } /** @internal */ _freeze() { if (!this.subMeshes) { return; } for (let index = 0; index < this.subMeshes.length; index++) { this._getInstancesRenderList(index); } this._internalMeshDataInfo._effectiveMaterial = null; this._instanceDataStorage.isFrozen = true; } /** @internal */ _unFreeze() { this._instanceDataStorage.isFrozen = false; for (const renderPassId in this._instanceDataStorage.renderPasses) { const instanceDataStorage = this._instanceDataStorage.renderPasses[renderPassId]; instanceDataStorage.previousBatch = null; } } /** * Triggers the draw call for the mesh (or a submesh), for a specific render pass id * @param renderPassId defines the render pass id to use to draw the mesh / submesh. If not provided, use the current renderPassId of the engine. * @param enableAlphaMode defines if alpha mode can be changed (default: false) * @param effectiveMeshReplacement defines an optional mesh used to provide info for the rendering (default: undefined) * @param subMesh defines the subMesh to render. If not provided, draw all mesh submeshes (default: undefined) * @param checkFrustumCulling defines if frustum culling must be checked (default: true). If you know the mesh is in the frustum (or if you don't care!), you can pass false to optimize. * @returns the current mesh */ renderWithRenderPassId(renderPassId, enableAlphaMode, effectiveMeshReplacement, subMesh, checkFrustumCulling = true) { const engine = this._scene.getEngine(); const currentRenderPassId = engine.currentRenderPassId; if (renderPassId !== void 0) { engine.currentRenderPassId = renderPassId; } if (subMesh) { if (!checkFrustumCulling || checkFrustumCulling && subMesh.isInFrustum(this._scene._frustumPlanes)) { this.render(subMesh, !!enableAlphaMode, effectiveMeshReplacement); } } else { for (let s = 0; s < this.subMeshes.length; s++) { const subMesh2 = this.subMeshes[s]; if (!checkFrustumCulling || checkFrustumCulling && subMesh2.isInFrustum(this._scene._frustumPlanes)) { this.render(subMesh2, !!enableAlphaMode, effectiveMeshReplacement); } } } if (renderPassId !== void 0) { engine.currentRenderPassId = currentRenderPassId; } return this; } /** * Render a complete mesh by going through all submeshes * @returns the current mesh * @see [simple test](https://playground.babylonjs.com/#5SPY1V#2) * @see [perf test](https://playground.babylonjs.com/#5SPY1V#5) */ directRender() { if (!this.subMeshes) { return this; } for (const submesh of this.subMeshes) { this.render(submesh, false); } return this; } /** * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager * @param subMesh defines the subMesh to render * @param enableAlphaMode defines if alpha mode can be changed * @param effectiveMeshReplacement defines an optional mesh used to provide info for the rendering * @returns the current mesh */ render(subMesh, enableAlphaMode, effectiveMeshReplacement) { const scene = this.getScene(); if (this._internalAbstractMeshDataInfo._isActiveIntermediate) { this._internalAbstractMeshDataInfo._isActiveIntermediate = false; } else { this._internalAbstractMeshDataInfo._isActive = false; } const numActiveCameras = scene.activeCameras?.length ?? 0; const canCheckOcclusionQuery = numActiveCameras > 1 && scene.activeCamera === scene.activeCameras[0] || numActiveCameras <= 1; if (canCheckOcclusionQuery && this._checkOcclusionQuery() && !this._occlusionDataStorage.forceRenderingWhenOccluded) { return this; } const batch = this._getInstancesRenderList(subMesh._id, !!effectiveMeshReplacement); if (batch.mustReturn) { return this; } if (!this._geometry || !this._geometry.getVertexBuffers() || !this._unIndexed && !this._geometry.getIndexBuffer()) { return this; } const engine = scene.getEngine(); let oldCameraMaxZ = 0; let oldCamera = null; if (this.ignoreCameraMaxZ && scene.activeCamera && !scene._isInIntermediateRendering()) { oldCameraMaxZ = scene.activeCamera.maxZ; oldCamera = scene.activeCamera; scene.activeCamera.maxZ = 0; scene.updateTransformMatrix(true); } if (this._internalMeshDataInfo._onBeforeRenderObservable) { this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this); } const renderingMesh = subMesh.getRenderingMesh(); const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances || !!this._userInstancedBuffersStorage && !subMesh.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh; const instanceDataStorage = this._instanceDataStorage; const material = subMesh.getMaterial(); if (!material) { if (oldCamera) { oldCamera.maxZ = oldCameraMaxZ; scene.updateTransformMatrix(true); } return this; } if (!instanceDataStorage.isFrozen || !this._internalMeshDataInfo._effectiveMaterial || this._internalMeshDataInfo._effectiveMaterial !== material) { if (material._storeEffectOnSubMeshes) { if (!material.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) { if (oldCamera) { oldCamera.maxZ = oldCameraMaxZ; scene.updateTransformMatrix(true); } return this; } } else if (!material.isReady(this, hardwareInstancedRendering)) { if (oldCamera) { oldCamera.maxZ = oldCameraMaxZ; scene.updateTransformMatrix(true); } return this; } this._internalMeshDataInfo._effectiveMaterial = material; } else if (material._storeEffectOnSubMeshes && !subMesh._drawWrapper?._wasPreviouslyReady || !material._storeEffectOnSubMeshes && !material._getDrawWrapper()._wasPreviouslyReady) { if (oldCamera) { oldCamera.maxZ = oldCameraMaxZ; scene.updateTransformMatrix(true); } return this; } if (enableAlphaMode) { const effectiveMaterial2 = this._internalMeshDataInfo._effectiveMaterial; if (effectiveMaterial2.alphaModes.length === 1) { engine.setAlphaMode(effectiveMaterial2.alphaMode); } else { for (let i = 0; i < effectiveMaterial2.alphaModes.length; i++) { const alphaMode = effectiveMaterial2.alphaModes[i]; engine.setAlphaMode(alphaMode !== void 0 ? alphaMode : 2, false, i); } } } let drawWrapper; if (this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes) { drawWrapper = subMesh._drawWrapper; } else { drawWrapper = this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper(); } const effect = drawWrapper?.effect ?? null; for (const step of scene._beforeRenderingMeshStage) { step.action(this, subMesh, batch, effect); } if (!drawWrapper || !effect) { if (oldCamera) { oldCamera.maxZ = oldCameraMaxZ; scene.updateTransformMatrix(true); } return this; } const effectiveMesh = effectiveMeshReplacement || this; let sideOrientation; if (!instanceDataStorage.isFrozen && (this._internalMeshDataInfo._effectiveMaterial.backFaceCulling || this._internalMeshDataInfo._effectiveMaterial.sideOrientation !== null || this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)) { const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant(); sideOrientation = this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this); if (mainDeterminant < 0) { sideOrientation = sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation; } this._internalMeshDataInfo._effectiveSideOrientation = sideOrientation; } else { sideOrientation = this._internalMeshDataInfo._effectiveSideOrientation; } const reverse = this._internalMeshDataInfo._effectiveMaterial._preBind(drawWrapper, this._internalMeshDataInfo._effectiveSideOrientation); if (this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite) { engine.setDepthWrite(true); } const effectiveMaterial = this._internalMeshDataInfo._effectiveMaterial; const fillMode = effectiveMaterial.fillMode; if (this._internalMeshDataInfo._onBeforeBindObservable) { this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this); } if (!hardwareInstancedRendering) { this._bind(subMesh, effect, fillMode, false); } const world = effectiveMesh.getWorldMatrix(); if (effectiveMaterial._storeEffectOnSubMeshes) { effectiveMaterial.bindForSubMesh(world, this, subMesh); } else { effectiveMaterial.bind(world, this); } if (!effectiveMaterial.backFaceCulling && effectiveMaterial.separateCullingPass) { engine.setState(true, effectiveMaterial.zOffset, false, !reverse, effectiveMaterial.cullBackFaces, effectiveMaterial.stencil, effectiveMaterial.zOffsetUnits); this._processRendering(this, subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial); engine.setState(true, effectiveMaterial.zOffset, false, reverse, effectiveMaterial.cullBackFaces, effectiveMaterial.stencil, effectiveMaterial.zOffsetUnits); if (this._internalMeshDataInfo._onBetweenPassObservable) { this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(subMesh); } } this._processRendering(this, subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._internalMeshDataInfo._effectiveMaterial); this._internalMeshDataInfo._effectiveMaterial.unbind(); for (const step of scene._afterRenderingMeshStage) { step.action(this, subMesh, batch, effect); } if (this._internalMeshDataInfo._onAfterRenderObservable) { this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this); } if (oldCamera) { oldCamera.maxZ = oldCameraMaxZ; scene.updateTransformMatrix(true); } if (scene.performancePriority === 2 && !instanceDataStorage.isFrozen) { this._freeze(); } return this; } /** * Renormalize the mesh and patch it up if there are no weights * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1. * However in the case of zero weights then we set just a single influence to 1. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version. */ cleanMatrixWeights() { if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) { if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind)) { this._normalizeSkinWeightsAndExtra(); } else { this._normalizeSkinFourWeights(); } } } // faster 4 weight version. _normalizeSkinFourWeights() { const matricesWeights = this.getVerticesData(VertexBuffer.MatricesWeightsKind); const numWeights = matricesWeights.length; for (let a = 0; a < numWeights; a += 4) { const t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3]; if (t === 0) { matricesWeights[a] = 1; } else { const recip = 1 / t; matricesWeights[a] *= recip; matricesWeights[a + 1] *= recip; matricesWeights[a + 2] *= recip; matricesWeights[a + 3] *= recip; } } this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeights); } // handle special case of extra verts. (in theory gltf can handle 12 influences) _normalizeSkinWeightsAndExtra() { const matricesWeightsExtra = this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind); const matricesWeights = this.getVerticesData(VertexBuffer.MatricesWeightsKind); const numWeights = matricesWeights.length; for (let a = 0; a < numWeights; a += 4) { let t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3]; t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3]; if (t === 0) { matricesWeights[a] = 1; } else { const recip = 1 / t; matricesWeights[a] *= recip; matricesWeights[a + 1] *= recip; matricesWeights[a + 2] *= recip; matricesWeights[a + 3] *= recip; matricesWeightsExtra[a] *= recip; matricesWeightsExtra[a + 1] *= recip; matricesWeightsExtra[a + 2] *= recip; matricesWeightsExtra[a + 3] *= recip; } } this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeights); this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsExtra); } /** * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights, * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let * the user know there was an issue with importing the mesh * @returns a validation object with skinned, valid and report string */ validateSkinning() { const matricesWeightsExtra = this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind); const matricesWeights = this.getVerticesData(VertexBuffer.MatricesWeightsKind); if (matricesWeights === null || this.skeleton == null) { return { skinned: false, valid: true, report: "not skinned" }; } const numWeights = matricesWeights.length; let numberNotSorted = 0; let missingWeights = 0; let maxUsedWeights = 0; let numberNotNormalized = 0; const numInfluences = matricesWeightsExtra === null ? 4 : 8; const usedWeightCounts = []; for (let a = 0; a <= numInfluences; a++) { usedWeightCounts[a] = 0; } const toleranceEpsilon = 1e-3; for (let a = 0; a < numWeights; a += 4) { let lastWeight = matricesWeights[a]; let t = lastWeight; let usedWeights = t === 0 ? 0 : 1; for (let b = 1; b < numInfluences; b++) { const d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4]; if (d > lastWeight) { numberNotSorted++; } if (d !== 0) { usedWeights++; } t += d; lastWeight = d; } usedWeightCounts[usedWeights]++; if (usedWeights > maxUsedWeights) { maxUsedWeights = usedWeights; } if (t === 0) { missingWeights++; } else { const recip = 1 / t; let tolerance = 0; for (let b = 0; b < numInfluences; b++) { if (b < 4) { tolerance += Math.abs(matricesWeights[a + b] - matricesWeights[a + b] * recip); } else { tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - matricesWeightsExtra[a + b - 4] * recip); } } if (tolerance > toleranceEpsilon) { numberNotNormalized++; } } } const numBones = this.skeleton.bones.length; const matricesIndices = this.getVerticesData(VertexBuffer.MatricesIndicesKind); const matricesIndicesExtra = this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind); let numBadBoneIndices = 0; for (let a = 0; a < numWeights; a += 4) { for (let b = 0; b < numInfluences; b++) { const index = b < 4 ? matricesIndices[a + b] : matricesIndicesExtra[a + b - 4]; if (index >= numBones || index < 0) { numBadBoneIndices++; } } } const output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights + "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted + "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices; return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output }; } /** @internal */ _checkDelayState() { const scene = this.getScene(); if (this._geometry) { this._geometry.load(scene); } else if (this.delayLoadState === 4) { this.delayLoadState = 2; this._queueLoad(scene); } return this; } _queueLoad(scene) { scene.addPendingData(this); const getBinaryData = this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1; Tools.LoadFile(this.delayLoadingFile, (data) => { if (data instanceof ArrayBuffer) { this._delayLoadingFunction(data, this); } else { this._delayLoadingFunction(JSON.parse(data), this); } for (const instance of this.instances) { instance.refreshBoundingInfo(); instance._syncSubMeshes(); } this.delayLoadState = 1; scene.removePendingData(this); }, () => { }, scene.offlineProvider, getBinaryData); return this; } /** * Returns `true` if the mesh is within the frustum defined by the passed array of planes. * A mesh is in the frustum if its bounding box intersects the frustum * @param frustumPlanes defines the frustum to test * @returns true if the mesh is in the frustum planes */ isInFrustum(frustumPlanes) { if (this.delayLoadState === 2) { return false; } if (!super.isInFrustum(frustumPlanes)) { return false; } this._checkDelayState(); return true; } /** * Sets the mesh material by the material or multiMaterial `id` property * @param id is a string identifying the material or the multiMaterial * @returns the current mesh */ setMaterialById(id) { const materials = this.getScene().materials; let index; for (index = materials.length - 1; index > -1; index--) { if (materials[index].id === id) { this.material = materials[index]; return this; } } const multiMaterials = this.getScene().multiMaterials; for (index = multiMaterials.length - 1; index > -1; index--) { if (multiMaterials[index].id === id) { this.material = multiMaterials[index]; return this; } } return this; } /** * Returns as a new array populated with the mesh material and/or skeleton, if any. * @returns an array of IAnimatable */ getAnimatables() { const results = []; if (this.material) { results.push(this.material); } if (this.skeleton) { results.push(this.skeleton); } return results; } /** * Modifies the mesh geometry according to the passed transformation matrix. * This method returns nothing, but it really modifies the mesh even if it's originally not set as updatable. * The mesh normals are modified using the same transformation. * Note that, under the hood, this method sets a new VertexBuffer each call. * @param transform defines the transform matrix to use * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/bakingTransforms * @returns the current mesh */ bakeTransformIntoVertices(transform) { if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) { return this; } const submeshes = this.subMeshes.splice(0); this._resetPointsArrayCache(); let data = this.getVerticesData(VertexBuffer.PositionKind); const temp = Vector3.Zero(); let index; for (index = 0; index < data.length; index += 3) { Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], transform, temp).toArray(data, index); } this.setVerticesData(VertexBuffer.PositionKind, data, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable()); if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) { data = this.getVerticesData(VertexBuffer.NormalKind); for (index = 0; index < data.length; index += 3) { Vector3.TransformNormalFromFloatsToRef(data[index], data[index + 1], data[index + 2], transform, temp).normalize().toArray(data, index); } this.setVerticesData(VertexBuffer.NormalKind, data, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable()); } if (this.isVerticesDataPresent(VertexBuffer.TangentKind)) { data = this.getVerticesData(VertexBuffer.TangentKind); for (index = 0; index < data.length; index += 4) { Vector3.TransformNormalFromFloatsToRef(data[index], data[index + 1], data[index + 2], transform, temp).normalize().toArray(data, index); } this.setVerticesData(VertexBuffer.TangentKind, data, this.getVertexBuffer(VertexBuffer.TangentKind).isUpdatable()); } if (transform.determinant() < 0) { this.flipFaces(); } this.releaseSubMeshes(); this.subMeshes = submeshes; return this; } /** * Modifies the mesh geometry according to its own current World Matrix. * The mesh World Matrix is then reset. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable. * Note that, under the hood, this method sets a new VertexBuffer each call. * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/transforms/center_origin/bakingTransforms * @param bakeIndependentlyOfChildren indicates whether to preserve all child nodes' World Matrix during baking * @param forceUnique indicates whether to force the mesh geometry to be unique * @returns the current mesh */ bakeCurrentTransformIntoVertices(bakeIndependentlyOfChildren = true, forceUnique = false) { if (forceUnique) { this.makeGeometryUnique(); } this.bakeTransformIntoVertices(this.computeWorldMatrix(true)); this.resetLocalMatrix(bakeIndependentlyOfChildren); return this; } // Cache /** @internal */ get _positions() { return this._internalAbstractMeshDataInfo._positions || this._geometry && this._geometry._positions || null; } /** @internal */ _resetPointsArrayCache() { if (this._geometry) { this._geometry._resetPointsArrayCache(); } return this; } /** @internal */ _generatePointsArray() { if (this._geometry) { return this._geometry._generatePointsArray(); } return false; } /** * Returns a new Mesh object generated from the current mesh properties. * This method must not get confused with createInstance() * @param name is a string, the name given to the new mesh * @param newParent can be any Node object (default `null`) or an instance of MeshCloneOptions. If the latter, doNotCloneChildren and clonePhysicsImpostor are unused. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`) * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`) * @returns a new mesh */ clone(name260 = "", newParent = null, doNotCloneChildren, clonePhysicsImpostor = true) { if (newParent && newParent._addToSceneRootNodes === void 0) { const cloneOptions = newParent; MeshCreationOptions.source = this; MeshCreationOptions.doNotCloneChildren = cloneOptions.doNotCloneChildren; MeshCreationOptions.clonePhysicsImpostor = cloneOptions.clonePhysicsImpostor; MeshCreationOptions.cloneThinInstances = cloneOptions.cloneThinInstances; return new _Mesh(name260, this.getScene(), MeshCreationOptions); } return new _Mesh(name260, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor); } /** * Releases resources associated with this mesh. * @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) */ dispose(doNotRecurse, disposeMaterialAndTextures = false) { this.morphTargetManager = null; if (this._geometry) { this._geometry.releaseForMesh(this, true); } const internalDataInfo = this._internalMeshDataInfo; if (internalDataInfo._onBeforeDrawObservable) { internalDataInfo._onBeforeDrawObservable.clear(); } if (internalDataInfo._onBeforeBindObservable) { internalDataInfo._onBeforeBindObservable.clear(); } if (internalDataInfo._onBeforeRenderObservable) { internalDataInfo._onBeforeRenderObservable.clear(); } if (internalDataInfo._onAfterRenderObservable) { internalDataInfo._onAfterRenderObservable.clear(); } if (internalDataInfo._onBetweenPassObservable) { internalDataInfo._onBetweenPassObservable.clear(); } if (this._scene.useClonedMeshMap) { if (internalDataInfo.meshMap) { for (const uniqueId in internalDataInfo.meshMap) { const mesh = internalDataInfo.meshMap[uniqueId]; if (mesh) { mesh._internalMeshDataInfo._source = null; internalDataInfo.meshMap[uniqueId] = void 0; } } } if (internalDataInfo._source && internalDataInfo._source._internalMeshDataInfo.meshMap) { internalDataInfo._source._internalMeshDataInfo.meshMap[this.uniqueId] = void 0; } } else { const meshes = this.getScene().meshes; for (const abstractMesh of meshes) { const mesh = abstractMesh; if (mesh._internalMeshDataInfo && mesh._internalMeshDataInfo._source && mesh._internalMeshDataInfo._source === this) { mesh._internalMeshDataInfo._source = null; } } } internalDataInfo._source = null; this._disposeInstanceSpecificData(); this._disposeThinInstanceSpecificData(); if (this._internalMeshDataInfo._checkReadinessObserver) { this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver); } super.dispose(doNotRecurse, disposeMaterialAndTextures); } /** @internal */ _disposeInstanceSpecificData() { } /** @internal */ _disposeThinInstanceSpecificData() { } /** @internal */ _invalidateInstanceVertexArrayObject() { } /** * Modifies the mesh geometry according to a displacement map. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. * @param url is a string, the URL from the image file is to be downloaded. * @param minHeight is the lower limit of the displacement. * @param maxHeight is the upper limit of the displacement. * @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing. * @param uvOffset is an optional vector2 used to offset UV. * @param uvScale is an optional vector2 used to scale UV. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance. * @param onError defines a callback called when an error occurs during the processing of the request. * @returns the Mesh. */ applyDisplacementMap(url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate = false, onError) { const scene = this.getScene(); const onload = /* @__PURE__ */ __name((img) => { const heightMapWidth = img.width; const heightMapHeight = img.height; const canvas = this.getEngine().createCanvas(heightMapWidth, heightMapHeight); const context = canvas.getContext("2d"); context.drawImage(img, 0, 0); const buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data; this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate); if (onSuccess) { onSuccess(this); } }, "onload"); Tools.LoadImage(url, onload, onError ? onError : () => { }, scene.offlineProvider); return this; } /** * Modifies the mesh geometry according to a displacementMap buffer. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel. * @param heightMapWidth is the width of the buffer image. * @param heightMapHeight is the height of the buffer image. * @param minHeight is the lower limit of the displacement. * @param maxHeight is the upper limit of the displacement. * @param uvOffset is an optional vector2 used to offset UV. * @param uvScale is an optional vector2 used to scale UV. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance. * @returns the Mesh. */ applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate = false) { if (!this.isVerticesDataPresent(VertexBuffer.PositionKind) || !this.isVerticesDataPresent(VertexBuffer.NormalKind) || !this.isVerticesDataPresent(VertexBuffer.UVKind)) { Logger.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"); return this; } const positions = this.getVerticesData(VertexBuffer.PositionKind, true, true); const normals = this.getVerticesData(VertexBuffer.NormalKind); const uvs = this.getVerticesData(VertexBuffer.UVKind); let position = Vector3.Zero(); const normal = Vector3.Zero(); const uv = Vector2.Zero(); uvOffset = uvOffset || Vector2.Zero(); uvScale = uvScale || new Vector2(1, 1); for (let index = 0; index < positions.length; index += 3) { Vector3.FromArrayToRef(positions, index, position); Vector3.FromArrayToRef(normals, index, normal); Vector2.FromArrayToRef(uvs, index / 3 * 2, uv); const u = Math.abs(uv.x * uvScale.x + uvOffset.x % 1) * (heightMapWidth - 1) % heightMapWidth | 0; const v = Math.abs(uv.y * uvScale.y + uvOffset.y % 1) * (heightMapHeight - 1) % heightMapHeight | 0; const pos = (u + v * heightMapWidth) * 4; const r = buffer[pos] / 255; const g = buffer[pos + 1] / 255; const b = buffer[pos + 2] / 255; const gradient = r * 0.3 + g * 0.59 + b * 0.11; normal.normalize(); normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient); position = position.add(normal); position.toArray(positions, index); } VertexData.ComputeNormals(positions, this.getIndices(), normals); if (forceUpdate) { this.setVerticesData(VertexBuffer.PositionKind, positions); this.setVerticesData(VertexBuffer.NormalKind, normals); this.setVerticesData(VertexBuffer.UVKind, uvs); } else { this.updateVerticesData(VertexBuffer.PositionKind, positions); this.updateVerticesData(VertexBuffer.NormalKind, normals); } return this; } _getFlattenedNormals(indices, positions) { const normals = new Float32Array(indices.length * 3); let normalsCount = 0; const flipNormalGeneration = this.sideOrientation === (this._scene.useRightHandedSystem ? 1 : 0); for (let index = 0; index < indices.length; index += 3) { const p1 = Vector3.FromArray(positions, indices[index] * 3); const p2 = Vector3.FromArray(positions, indices[index + 1] * 3); const p3 = Vector3.FromArray(positions, indices[index + 2] * 3); const p1p2 = p1.subtract(p2); const p3p2 = p3.subtract(p2); const normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2)); if (flipNormalGeneration) { normal.scaleInPlace(-1); } for (let localIndex = 0; localIndex < 3; localIndex++) { normals[normalsCount++] = normal.x; normals[normalsCount++] = normal.y; normals[normalsCount++] = normal.z; } } return normals; } _convertToUnIndexedMesh(flattenNormals = false) { const kinds = this.getVerticesDataKinds().filter((kind) => !this.getVertexBuffer(kind)?.getIsInstanced()); const indices = this.getIndices(); const data = {}; const separateVertices = /* @__PURE__ */ __name((data2, size) => { const newData = new Float32Array(indices.length * size); let count = 0; for (let index = 0; index < indices.length; index++) { for (let offset = 0; offset < size; offset++) { newData[count++] = data2[indices[index] * size + offset]; } } return newData; }, "separateVertices"); const meshBoundingInfo = this.getBoundingInfo(); const previousSubmeshes = this.geometry ? this.subMeshes.slice(0) : []; for (const kind of kinds) { data[kind] = this.getVerticesData(kind); } for (const kind of kinds) { const vertexBuffer = this.getVertexBuffer(kind); const size = vertexBuffer.getSize(); if (flattenNormals && kind === VertexBuffer.NormalKind) { const normals = this._getFlattenedNormals(indices, data[VertexBuffer.PositionKind]); this.setVerticesData(VertexBuffer.NormalKind, normals, vertexBuffer.isUpdatable(), size); } else { this.setVerticesData(kind, separateVertices(data[kind], size), vertexBuffer.isUpdatable(), size); } } if (this.morphTargetManager) { for (let targetIndex = 0; targetIndex < this.morphTargetManager.numTargets; targetIndex++) { const target = this.morphTargetManager.getTarget(targetIndex); const positions = target.getPositions(); target.setPositions(separateVertices(positions, 3)); const normals = target.getNormals(); if (normals) { target.setNormals(flattenNormals ? this._getFlattenedNormals(indices, positions) : separateVertices(normals, 3)); } const tangents = target.getTangents(); if (tangents) { target.setTangents(separateVertices(tangents, 3)); } const uvs = target.getUVs(); if (uvs) { target.setUVs(separateVertices(uvs, 2)); } const colors = target.getColors(); if (colors) { target.setColors(separateVertices(colors, 4)); } } this.morphTargetManager.synchronize(); } for (let index = 0; index < indices.length; index++) { indices[index] = index; } this.setIndices(indices); this._unIndexed = true; this.releaseSubMeshes(); for (const previousOne of previousSubmeshes) { const boundingInfo = previousOne.getBoundingInfo(); const subMesh = SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this); subMesh.setBoundingInfo(boundingInfo); } this.setBoundingInfo(meshBoundingInfo); this.synchronizeInstances(); return this; } /** * Modify the mesh to get a flat shading rendering. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated. * @returns current mesh */ convertToFlatShadedMesh() { return this._convertToUnIndexedMesh(true); } /** * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers. * In other words, more vertices, no more indices and a single bigger VBO. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated. * @returns current mesh */ convertToUnIndexedMesh() { return this._convertToUnIndexedMesh(); } /** * Inverses facet orientations. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call. * @param flipNormals will also inverts the normals * @returns current mesh */ flipFaces(flipNormals = false) { const vertexData = VertexData.ExtractFromMesh(this); let i; if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind) && vertexData.normals) { for (i = 0; i < vertexData.normals.length; i++) { vertexData.normals[i] *= -1; } this.setVerticesData(VertexBuffer.NormalKind, vertexData.normals, this.isVertexBufferUpdatable(VertexBuffer.NormalKind)); } if (vertexData.indices) { let temp; for (i = 0; i < vertexData.indices.length; i += 3) { temp = vertexData.indices[i + 1]; vertexData.indices[i + 1] = vertexData.indices[i + 2]; vertexData.indices[i + 2] = temp; } this.setIndices(vertexData.indices, null, this.isVertexBufferUpdatable(VertexBuffer.PositionKind), true); } return this; } /** * Increase the number of facets and hence vertices in a mesh * Vertex normals are interpolated from existing vertex normals * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call. * @param numberPerEdge the number of new vertices to add to each edge of a facet, optional default 1 */ increaseVertices(numberPerEdge = 1) { const vertexData = VertexData.ExtractFromMesh(this); const currentIndices = vertexData.indices && !Array.isArray(vertexData.indices) && Array.from ? Array.from(vertexData.indices) : vertexData.indices; const positions = vertexData.positions && !Array.isArray(vertexData.positions) && Array.from ? Array.from(vertexData.positions) : vertexData.positions; const uvs = vertexData.uvs && !Array.isArray(vertexData.uvs) && Array.from ? Array.from(vertexData.uvs) : vertexData.uvs; const normals = vertexData.normals && !Array.isArray(vertexData.normals) && Array.from ? Array.from(vertexData.normals) : vertexData.normals; if (!currentIndices || !positions) { Logger.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions"); } else { vertexData.indices = currentIndices; vertexData.positions = positions; if (uvs) { vertexData.uvs = uvs; } if (normals) { vertexData.normals = normals; } const segments = numberPerEdge + 1; const tempIndices = []; for (let i = 0; i < segments + 1; i++) { tempIndices[i] = []; } let a; let b; const deltaPosition = new Vector3(0, 0, 0); const deltaNormal = new Vector3(0, 0, 0); const deltaUV = new Vector2(0, 0); const indices = []; const vertexIndex = []; const side = []; let len; let positionPtr = positions.length; let uvPtr; if (uvs) { uvPtr = uvs.length; } let normalsPtr; if (normals) { normalsPtr = normals.length; } for (let i = 0; i < currentIndices.length; i += 3) { vertexIndex[0] = currentIndices[i]; vertexIndex[1] = currentIndices[i + 1]; vertexIndex[2] = currentIndices[i + 2]; for (let j = 0; j < 3; j++) { a = vertexIndex[j]; b = vertexIndex[(j + 1) % 3]; if (side[a] === void 0 && side[b] === void 0) { side[a] = []; side[b] = []; } else { if (side[a] === void 0) { side[a] = []; } if (side[b] === void 0) { side[b] = []; } } if (side[a][b] === void 0 && side[b][a] === void 0) { side[a][b] = []; deltaPosition.x = (positions[3 * b] - positions[3 * a]) / segments; deltaPosition.y = (positions[3 * b + 1] - positions[3 * a + 1]) / segments; deltaPosition.z = (positions[3 * b + 2] - positions[3 * a + 2]) / segments; if (normals) { deltaNormal.x = (normals[3 * b] - normals[3 * a]) / segments; deltaNormal.y = (normals[3 * b + 1] - normals[3 * a + 1]) / segments; deltaNormal.z = (normals[3 * b + 2] - normals[3 * a + 2]) / segments; } if (uvs) { deltaUV.x = (uvs[2 * b] - uvs[2 * a]) / segments; deltaUV.y = (uvs[2 * b + 1] - uvs[2 * a + 1]) / segments; } side[a][b].push(a); for (let k = 1; k < segments; k++) { side[a][b].push(positions.length / 3); positions[positionPtr++] = positions[3 * a] + k * deltaPosition.x; positions[positionPtr++] = positions[3 * a + 1] + k * deltaPosition.y; positions[positionPtr++] = positions[3 * a + 2] + k * deltaPosition.z; if (normals) { normals[normalsPtr++] = normals[3 * a] + k * deltaNormal.x; normals[normalsPtr++] = normals[3 * a + 1] + k * deltaNormal.y; normals[normalsPtr++] = normals[3 * a + 2] + k * deltaNormal.z; } if (uvs) { uvs[uvPtr++] = uvs[2 * a] + k * deltaUV.x; uvs[uvPtr++] = uvs[2 * a + 1] + k * deltaUV.y; } } side[a][b].push(b); side[b][a] = []; len = side[a][b].length; for (let idx = 0; idx < len; idx++) { side[b][a][idx] = side[a][b][len - 1 - idx]; } } } tempIndices[0][0] = currentIndices[i]; tempIndices[1][0] = side[currentIndices[i]][currentIndices[i + 1]][1]; tempIndices[1][1] = side[currentIndices[i]][currentIndices[i + 2]][1]; for (let k = 2; k < segments; k++) { tempIndices[k][0] = side[currentIndices[i]][currentIndices[i + 1]][k]; tempIndices[k][k] = side[currentIndices[i]][currentIndices[i + 2]][k]; deltaPosition.x = (positions[3 * tempIndices[k][k]] - positions[3 * tempIndices[k][0]]) / k; deltaPosition.y = (positions[3 * tempIndices[k][k] + 1] - positions[3 * tempIndices[k][0] + 1]) / k; deltaPosition.z = (positions[3 * tempIndices[k][k] + 2] - positions[3 * tempIndices[k][0] + 2]) / k; if (normals) { deltaNormal.x = (normals[3 * tempIndices[k][k]] - normals[3 * tempIndices[k][0]]) / k; deltaNormal.y = (normals[3 * tempIndices[k][k] + 1] - normals[3 * tempIndices[k][0] + 1]) / k; deltaNormal.z = (normals[3 * tempIndices[k][k] + 2] - normals[3 * tempIndices[k][0] + 2]) / k; } if (uvs) { deltaUV.x = (uvs[2 * tempIndices[k][k]] - uvs[2 * tempIndices[k][0]]) / k; deltaUV.y = (uvs[2 * tempIndices[k][k] + 1] - uvs[2 * tempIndices[k][0] + 1]) / k; } for (let j = 1; j < k; j++) { tempIndices[k][j] = positions.length / 3; positions[positionPtr++] = positions[3 * tempIndices[k][0]] + j * deltaPosition.x; positions[positionPtr++] = positions[3 * tempIndices[k][0] + 1] + j * deltaPosition.y; positions[positionPtr++] = positions[3 * tempIndices[k][0] + 2] + j * deltaPosition.z; if (normals) { normals[normalsPtr++] = normals[3 * tempIndices[k][0]] + j * deltaNormal.x; normals[normalsPtr++] = normals[3 * tempIndices[k][0] + 1] + j * deltaNormal.y; normals[normalsPtr++] = normals[3 * tempIndices[k][0] + 2] + j * deltaNormal.z; } if (uvs) { uvs[uvPtr++] = uvs[2 * tempIndices[k][0]] + j * deltaUV.x; uvs[uvPtr++] = uvs[2 * tempIndices[k][0] + 1] + j * deltaUV.y; } } } tempIndices[segments] = side[currentIndices[i + 1]][currentIndices[i + 2]]; indices.push(tempIndices[0][0], tempIndices[1][0], tempIndices[1][1]); for (let k = 1; k < segments; k++) { let j; for (j = 0; j < k; j++) { indices.push(tempIndices[k][j], tempIndices[k + 1][j], tempIndices[k + 1][j + 1]); indices.push(tempIndices[k][j], tempIndices[k + 1][j + 1], tempIndices[k][j + 1]); } indices.push(tempIndices[k][j], tempIndices[k + 1][j], tempIndices[k + 1][j + 1]); } } vertexData.indices = indices; vertexData.applyToMesh(this, this.isVertexBufferUpdatable(VertexBuffer.PositionKind)); } } /** * Force adjacent facets to share vertices and remove any facets that have all vertices in a line * This will undo any application of covertToFlatShadedMesh * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call. */ forceSharedVertices() { const vertexData = VertexData.ExtractFromMesh(this); const currentUVs = vertexData.uvs; const currentIndices = vertexData.indices; const currentPositions = vertexData.positions; const currentColors = vertexData.colors; const currentMatrixIndices = vertexData.matricesIndices; const currentMatrixWeights = vertexData.matricesWeights; const currentMatrixIndicesExtra = vertexData.matricesIndicesExtra; const currentMatrixWeightsExtra = vertexData.matricesWeightsExtra; if (currentIndices === void 0 || currentPositions === void 0 || currentIndices === null || currentPositions === null) { Logger.Warn("VertexData contains empty entries"); } else { const positions = []; const indices = []; const uvs = []; const colors = []; const matrixIndices = []; const matrixWeights = []; const matrixIndicesExtra = []; const matrixWeightsExtra = []; let pstring = []; let indexPtr = 0; const uniquePositions = {}; let ptr; let facet; for (let i = 0; i < currentIndices.length; i += 3) { facet = [currentIndices[i], currentIndices[i + 1], currentIndices[i + 2]]; pstring = []; for (let j = 0; j < 3; j++) { pstring[j] = ""; for (let k = 0; k < 3; k++) { if (Math.abs(currentPositions[3 * facet[j] + k]) < 1e-8) { currentPositions[3 * facet[j] + k] = 0; } pstring[j] += currentPositions[3 * facet[j] + k] + "|"; } } if (!(pstring[0] == pstring[1] || pstring[0] == pstring[2] || pstring[1] == pstring[2])) { for (let j = 0; j < 3; j++) { ptr = uniquePositions[pstring[j]]; if (ptr === void 0) { uniquePositions[pstring[j]] = indexPtr; ptr = indexPtr++; for (let k = 0; k < 3; k++) { positions.push(currentPositions[3 * facet[j] + k]); } if (currentColors !== null && currentColors !== void 0) { for (let k = 0; k < 4; k++) { colors.push(currentColors[4 * facet[j] + k]); } } if (currentUVs !== null && currentUVs !== void 0) { for (let k = 0; k < 2; k++) { uvs.push(currentUVs[2 * facet[j] + k]); } } if (currentMatrixIndices !== null && currentMatrixIndices !== void 0) { for (let k = 0; k < 4; k++) { matrixIndices.push(currentMatrixIndices[4 * facet[j] + k]); } } if (currentMatrixWeights !== null && currentMatrixWeights !== void 0) { for (let k = 0; k < 4; k++) { matrixWeights.push(currentMatrixWeights[4 * facet[j] + k]); } } if (currentMatrixIndicesExtra !== null && currentMatrixIndicesExtra !== void 0) { for (let k = 0; k < 4; k++) { matrixIndicesExtra.push(currentMatrixIndicesExtra[4 * facet[j] + k]); } } if (currentMatrixWeightsExtra !== null && currentMatrixWeightsExtra !== void 0) { for (let k = 0; k < 4; k++) { matrixWeightsExtra.push(currentMatrixWeightsExtra[4 * facet[j] + k]); } } } indices.push(ptr); } } } const normals = []; VertexData.ComputeNormals(positions, indices, normals); vertexData.positions = positions; vertexData.indices = indices; vertexData.normals = normals; if (currentUVs !== null && currentUVs !== void 0) { vertexData.uvs = uvs; } if (currentColors !== null && currentColors !== void 0) { vertexData.colors = colors; } if (currentMatrixIndices !== null && currentMatrixIndices !== void 0) { vertexData.matricesIndices = matrixIndices; } if (currentMatrixWeights !== null && currentMatrixWeights !== void 0) { vertexData.matricesWeights = matrixWeights; } if (currentMatrixIndicesExtra !== null && currentMatrixIndicesExtra !== void 0) { vertexData.matricesIndicesExtra = matrixIndicesExtra; } if (currentMatrixWeights !== null && currentMatrixWeights !== void 0) { vertexData.matricesWeightsExtra = matrixWeightsExtra; } vertexData.applyToMesh(this, this.isVertexBufferUpdatable(VertexBuffer.PositionKind)); } } // Instances /** * @internal */ // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/naming-convention static _instancedMeshFactory(name260, mesh) { throw _WarnImport("InstancedMesh"); } /** * @internal */ // eslint-disable-next-line @typescript-eslint/no-unused-vars static _PhysicsImpostorParser(scene, physicObject, jsonObject) { throw _WarnImport("PhysicsImpostor"); } /** * Creates a new InstancedMesh object from the mesh model. * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/copies/instances * @param name defines the name of the new instance * @returns a new InstancedMesh */ createInstance(name260) { const instance = _Mesh._instancedMeshFactory(name260, this); instance.parent = this.parent; return instance; } /** * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any. * After this call, all the mesh instances have the same submeshes than the current mesh. * @returns the current mesh */ synchronizeInstances() { for (let instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) { const instance = this.instances[instanceIndex]; instance._syncSubMeshes(); } return this; } /** * Optimization of the mesh's indices, in case a mesh has duplicated vertices. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes. * This should be used together with the simplification to avoid disappearing triangles. * @param successCallback an optional success callback to be called after the optimization finished. * @returns the current mesh */ optimizeIndices(successCallback) { const indices = this.getIndices(); const positions = this.getVerticesData(VertexBuffer.PositionKind); if (!positions || !indices) { return this; } const vectorPositions = []; for (let pos = 0; pos < positions.length; pos = pos + 3) { vectorPositions.push(Vector3.FromArray(positions, pos)); } const dupes = []; AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => { const realPos = vectorPositions.length - 1 - iteration; const testedPosition = vectorPositions[realPos]; for (let j = 0; j < realPos; ++j) { const againstPosition = vectorPositions[j]; if (testedPosition.equals(againstPosition)) { dupes[realPos] = j; break; } } }, () => { for (let i = 0; i < indices.length; ++i) { indices[i] = dupes[indices[i]] || indices[i]; } const originalSubMeshes = this.subMeshes.slice(0); this.setIndices(indices); this.subMeshes = originalSubMeshes; if (successCallback) { successCallback(this); } }); return this; } /** * Serialize current mesh * @param serializationObject defines the object which will receive the serialization data * @returns the serialized object */ serialize(serializationObject = {}) { serializationObject.name = this.name; serializationObject.id = this.id; serializationObject.uniqueId = this.uniqueId; serializationObject.type = this.getClassName(); if (Tags && Tags.HasTags(this)) { serializationObject.tags = Tags.GetTags(this); } serializationObject.position = this.position.asArray(); if (this.rotationQuaternion) { serializationObject.rotationQuaternion = this.rotationQuaternion.asArray(); } else if (this.rotation) { serializationObject.rotation = this.rotation.asArray(); } serializationObject.scaling = this.scaling.asArray(); if (this._postMultiplyPivotMatrix) { serializationObject.pivotMatrix = this.getPivotMatrix().asArray(); } else { serializationObject.localMatrix = this.getPivotMatrix().asArray(); } serializationObject.isEnabled = this.isEnabled(false); serializationObject.isVisible = this.isVisible; serializationObject.infiniteDistance = this.infiniteDistance; serializationObject.pickable = this.isPickable; serializationObject.receiveShadows = this.receiveShadows; serializationObject.billboardMode = this.billboardMode; serializationObject.visibility = this.visibility; serializationObject.alwaysSelectAsActiveMesh = this.alwaysSelectAsActiveMesh; serializationObject.checkCollisions = this.checkCollisions; serializationObject.ellipsoid = this.ellipsoid.asArray(); serializationObject.ellipsoidOffset = this.ellipsoidOffset.asArray(); serializationObject.doNotSyncBoundingInfo = this.doNotSyncBoundingInfo; serializationObject.isBlocker = this.isBlocker; serializationObject.sideOrientation = this.sideOrientation; if (this.parent) { this.parent._serializeAsParent(serializationObject); } serializationObject.isUnIndexed = this.isUnIndexed; const geometry = this._geometry; if (geometry && this.subMeshes) { serializationObject.geometryUniqueId = geometry.uniqueId; serializationObject.geometryId = geometry.id; serializationObject.subMeshes = []; for (let subIndex = 0; subIndex < this.subMeshes.length; subIndex++) { const subMesh = this.subMeshes[subIndex]; serializationObject.subMeshes.push({ materialIndex: subMesh.materialIndex, verticesStart: subMesh.verticesStart, verticesCount: subMesh.verticesCount, indexStart: subMesh.indexStart, indexCount: subMesh.indexCount }); } } if (this.material) { if (!this.material.doNotSerialize) { serializationObject.materialUniqueId = this.material.uniqueId; serializationObject.materialId = this.material.id; } } else { this.material = null; serializationObject.materialUniqueId = this._scene.defaultMaterial.uniqueId; serializationObject.materialId = this._scene.defaultMaterial.id; } if (this.morphTargetManager) { serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId; } if (this.skeleton) { serializationObject.skeletonId = this.skeleton.id; serializationObject.numBoneInfluencers = this.numBoneInfluencers; } if (this.getScene()._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE)) { const impostor = this.getPhysicsImpostor(); if (impostor) { serializationObject.physicsMass = impostor.getParam("mass"); serializationObject.physicsFriction = impostor.getParam("friction"); serializationObject.physicsRestitution = impostor.getParam("mass"); serializationObject.physicsImpostor = impostor.type; } } if (this.metadata) { serializationObject.metadata = this.metadata; } serializationObject.instances = []; for (let index = 0; index < this.instances.length; index++) { const instance = this.instances[index]; if (instance.doNotSerialize) { continue; } const serializationInstance = { name: instance.name, id: instance.id, isEnabled: instance.isEnabled(false), isVisible: instance.isVisible, isPickable: instance.isPickable, checkCollisions: instance.checkCollisions, position: instance.position.asArray(), scaling: instance.scaling.asArray() }; if (instance.parent) { instance.parent._serializeAsParent(serializationInstance); } if (instance.rotationQuaternion) { serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray(); } else if (instance.rotation) { serializationInstance.rotation = instance.rotation.asArray(); } if (this.getScene()._getComponent(SceneComponentConstants.NAME_PHYSICSENGINE)) { const impostor = instance.getPhysicsImpostor(); if (impostor) { serializationInstance.physicsMass = impostor.getParam("mass"); serializationInstance.physicsFriction = impostor.getParam("friction"); serializationInstance.physicsRestitution = impostor.getParam("mass"); serializationInstance.physicsImpostor = impostor.type; } } if (instance.metadata) { serializationInstance.metadata = instance.metadata; } if (instance.actionManager) { serializationInstance.actions = instance.actionManager.serialize(instance.name); } serializationObject.instances.push(serializationInstance); SerializationHelper.AppendSerializedAnimations(instance, serializationInstance); serializationInstance.ranges = instance.serializeAnimationRanges(); } if (this._thinInstanceDataStorage.instancesCount && this._thinInstanceDataStorage.matrixData) { serializationObject.thinInstances = { instancesCount: this._thinInstanceDataStorage.instancesCount, matrixData: Array.from(this._thinInstanceDataStorage.matrixData), matrixBufferSize: this._thinInstanceDataStorage.matrixBufferSize, enablePicking: this.thinInstanceEnablePicking }; if (this._userThinInstanceBuffersStorage) { const userThinInstance = { data: {}, sizes: {}, strides: {} }; for (const kind in this._userThinInstanceBuffersStorage.data) { userThinInstance.data[kind] = Array.from(this._userThinInstanceBuffersStorage.data[kind]); userThinInstance.sizes[kind] = this._userThinInstanceBuffersStorage.sizes[kind]; userThinInstance.strides[kind] = this._userThinInstanceBuffersStorage.strides[kind]; } serializationObject.thinInstances.userThinInstance = userThinInstance; } } SerializationHelper.AppendSerializedAnimations(this, serializationObject); serializationObject.ranges = this.serializeAnimationRanges(); serializationObject.layerMask = this.layerMask; serializationObject.alphaIndex = this.alphaIndex; serializationObject.hasVertexAlpha = this.hasVertexAlpha; serializationObject.overlayAlpha = this.overlayAlpha; serializationObject.overlayColor = this.overlayColor.asArray(); serializationObject.renderOverlay = this.renderOverlay; serializationObject.applyFog = this.applyFog; if (this.actionManager) { serializationObject.actions = this.actionManager.serialize(this.name); } return serializationObject; } /** @internal */ _syncGeometryWithMorphTargetManager() { if (!this.geometry) { return; } this._markSubMeshesAsAttributesDirty(); const morphTargetManager = this._internalAbstractMeshDataInfo._morphTargetManager; if (morphTargetManager && morphTargetManager.vertexCount) { if (morphTargetManager.vertexCount !== this.getTotalVertices()) { Logger.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."); this.morphTargetManager = null; return; } if (morphTargetManager.isUsingTextureForTargets) { return; } for (let index = 0; index < morphTargetManager.numInfluencers; index++) { const morphTarget = morphTargetManager.getActiveTarget(index); const positions = morphTarget.getPositions(); if (!positions) { Logger.Error("Invalid morph target. Target must have positions."); return; } this.geometry.setVerticesData(VertexBuffer.PositionKind + index, positions, false, 3); const normals = morphTarget.getNormals(); if (normals) { this.geometry.setVerticesData(VertexBuffer.NormalKind + index, normals, false, 3); } const tangents = morphTarget.getTangents(); if (tangents) { this.geometry.setVerticesData(VertexBuffer.TangentKind + index, tangents, false, 3); } const uvs = morphTarget.getUVs(); if (uvs) { this.geometry.setVerticesData(VertexBuffer.UVKind + "_" + index, uvs, false, 2); } const uv2s = morphTarget.getUV2s(); if (uv2s) { this.geometry.setVerticesData(VertexBuffer.UV2Kind + "_" + index, uv2s, false, 2); } const colors = morphTarget.getColors(); if (colors) { this.geometry.setVerticesData(VertexBuffer.ColorKind + index, colors, false, 4); } } } else { let index = 0; while (this.geometry.isVerticesDataPresent(VertexBuffer.PositionKind + index)) { this.geometry.removeVerticesData(VertexBuffer.PositionKind + index); if (this.geometry.isVerticesDataPresent(VertexBuffer.NormalKind + index)) { this.geometry.removeVerticesData(VertexBuffer.NormalKind + index); } if (this.geometry.isVerticesDataPresent(VertexBuffer.TangentKind + index)) { this.geometry.removeVerticesData(VertexBuffer.TangentKind + index); } if (this.geometry.isVerticesDataPresent(VertexBuffer.UVKind + index)) { this.geometry.removeVerticesData(VertexBuffer.UVKind + "_" + index); } if (this.geometry.isVerticesDataPresent(VertexBuffer.UV2Kind + index)) { this.geometry.removeVerticesData(VertexBuffer.UV2Kind + "_" + index); } if (this.geometry.isVerticesDataPresent(VertexBuffer.ColorKind + index)) { this.geometry.removeVerticesData(VertexBuffer.ColorKind + index); } index++; } } } /** * Returns a new Mesh object parsed from the source provided. * @param parsedMesh is the source * @param scene defines the hosting scene * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with * @returns a new Mesh */ static Parse(parsedMesh, scene, rootUrl) { let mesh; if (parsedMesh.type && parsedMesh.type === "LinesMesh") { mesh = _Mesh._LinesMeshParser(parsedMesh, scene); } else if (parsedMesh.type && parsedMesh.type === "GroundMesh") { mesh = _Mesh._GroundMeshParser(parsedMesh, scene); } else if (parsedMesh.type && parsedMesh.type === "GoldbergMesh") { mesh = _Mesh._GoldbergMeshParser(parsedMesh, scene); } else if (parsedMesh.type && parsedMesh.type === "GreasedLineMesh") { mesh = _Mesh._GreasedLineMeshParser(parsedMesh, scene); } else if (parsedMesh.type && parsedMesh.type === "TrailMesh") { mesh = _Mesh._TrailMeshParser(parsedMesh, scene); } else { mesh = new _Mesh(parsedMesh.name, scene); } mesh.id = parsedMesh.id; mesh._waitingParsedUniqueId = parsedMesh.uniqueId; if (Tags) { Tags.AddTagsTo(mesh, parsedMesh.tags); } mesh.position = Vector3.FromArray(parsedMesh.position); if (parsedMesh.metadata !== void 0) { mesh.metadata = parsedMesh.metadata; } if (parsedMesh.rotationQuaternion) { mesh.rotationQuaternion = Quaternion.FromArray(parsedMesh.rotationQuaternion); } else if (parsedMesh.rotation) { mesh.rotation = Vector3.FromArray(parsedMesh.rotation); } mesh.scaling = Vector3.FromArray(parsedMesh.scaling); if (parsedMesh.localMatrix) { mesh.setPreTransformMatrix(Matrix.FromArray(parsedMesh.localMatrix)); } else if (parsedMesh.pivotMatrix) { mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.pivotMatrix)); } mesh.setEnabled(parsedMesh.isEnabled); mesh.isVisible = parsedMesh.isVisible; mesh.infiniteDistance = parsedMesh.infiniteDistance; mesh.alwaysSelectAsActiveMesh = !!parsedMesh.alwaysSelectAsActiveMesh; mesh.showBoundingBox = parsedMesh.showBoundingBox; mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox; if (parsedMesh.applyFog !== void 0) { mesh.applyFog = parsedMesh.applyFog; } if (parsedMesh.pickable !== void 0) { mesh.isPickable = parsedMesh.pickable; } if (parsedMesh.alphaIndex !== void 0) { mesh.alphaIndex = parsedMesh.alphaIndex; } mesh.receiveShadows = parsedMesh.receiveShadows; if (parsedMesh.billboardMode !== void 0) { mesh.billboardMode = parsedMesh.billboardMode; } if (parsedMesh.visibility !== void 0) { mesh.visibility = parsedMesh.visibility; } mesh.checkCollisions = parsedMesh.checkCollisions; mesh.doNotSyncBoundingInfo = !!parsedMesh.doNotSyncBoundingInfo; if (parsedMesh.ellipsoid) { mesh.ellipsoid = Vector3.FromArray(parsedMesh.ellipsoid); } if (parsedMesh.ellipsoidOffset) { mesh.ellipsoidOffset = Vector3.FromArray(parsedMesh.ellipsoidOffset); } if (parsedMesh.overrideMaterialSideOrientation != null) { mesh.sideOrientation = parsedMesh.overrideMaterialSideOrientation; } if (parsedMesh.sideOrientation !== void 0) { mesh.sideOrientation = parsedMesh.sideOrientation; } if (parsedMesh.isBlocker !== void 0) { mesh.isBlocker = parsedMesh.isBlocker; } mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading; if (parsedMesh.freezeWorldMatrix) { mesh._waitingData.freezeWorldMatrix = parsedMesh.freezeWorldMatrix; } if (parsedMesh.parentId !== void 0) { mesh._waitingParentId = parsedMesh.parentId; } if (parsedMesh.parentInstanceIndex !== void 0) { mesh._waitingParentInstanceIndex = parsedMesh.parentInstanceIndex; } if (parsedMesh.actions !== void 0) { mesh._waitingData.actions = parsedMesh.actions; } if (parsedMesh.overlayAlpha !== void 0) { mesh.overlayAlpha = parsedMesh.overlayAlpha; } if (parsedMesh.overlayColor !== void 0) { mesh.overlayColor = Color3.FromArray(parsedMesh.overlayColor); } if (parsedMesh.renderOverlay !== void 0) { mesh.renderOverlay = parsedMesh.renderOverlay; } mesh.isUnIndexed = !!parsedMesh.isUnIndexed; mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha; if (parsedMesh.delayLoadingFile) { mesh.delayLoadState = 4; mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile; mesh.buildBoundingInfo(Vector3.FromArray(parsedMesh.boundingBoxMinimum), Vector3.FromArray(parsedMesh.boundingBoxMaximum)); if (parsedMesh._binaryInfo) { mesh._binaryInfo = parsedMesh._binaryInfo; } mesh._delayInfo = []; if (parsedMesh.hasUVs) { mesh._delayInfo.push(VertexBuffer.UVKind); } if (parsedMesh.hasUVs2) { mesh._delayInfo.push(VertexBuffer.UV2Kind); } if (parsedMesh.hasUVs3) { mesh._delayInfo.push(VertexBuffer.UV3Kind); } if (parsedMesh.hasUVs4) { mesh._delayInfo.push(VertexBuffer.UV4Kind); } if (parsedMesh.hasUVs5) { mesh._delayInfo.push(VertexBuffer.UV5Kind); } if (parsedMesh.hasUVs6) { mesh._delayInfo.push(VertexBuffer.UV6Kind); } if (parsedMesh.hasColors) { mesh._delayInfo.push(VertexBuffer.ColorKind); } if (parsedMesh.hasMatricesIndices) { mesh._delayInfo.push(VertexBuffer.MatricesIndicesKind); } if (parsedMesh.hasMatricesWeights) { mesh._delayInfo.push(VertexBuffer.MatricesWeightsKind); } mesh._delayLoadingFunction = Geometry._ImportGeometry; if (SceneLoaderFlags.ForceFullSceneLoadingForIncremental) { mesh._checkDelayState(); } } else { Geometry._ImportGeometry(parsedMesh, mesh); } if (parsedMesh.materialUniqueId) { mesh._waitingMaterialId = parsedMesh.materialUniqueId; } else if (parsedMesh.materialId) { mesh._waitingMaterialId = parsedMesh.materialId; } if (parsedMesh.morphTargetManagerId > -1) { mesh._waitingMorphTargetManagerId = parsedMesh.morphTargetManagerId; } if (parsedMesh.skeletonId !== void 0 && parsedMesh.skeletonId !== null) { mesh.skeleton = scene.getLastSkeletonById(parsedMesh.skeletonId); if (parsedMesh.numBoneInfluencers) { mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers; } } if (parsedMesh.animations) { for (let animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) { const parsedAnimation = parsedMesh.animations[animationIndex]; const internalClass = GetClass("BABYLON.Animation"); if (internalClass) { mesh.animations.push(internalClass.Parse(parsedAnimation)); } } Node.ParseAnimationRanges(mesh, parsedMesh, scene); } if (parsedMesh.autoAnimate) { scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1); } if (parsedMesh.layerMask && !isNaN(parsedMesh.layerMask)) { mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask)); } else { mesh.layerMask = 268435455; } if (parsedMesh.physicsImpostor) { mesh.physicsImpostor = _Mesh._PhysicsImpostorParser(scene, mesh, parsedMesh); } if (parsedMesh.lodMeshIds) { mesh._waitingData.lods = { ids: parsedMesh.lodMeshIds, distances: parsedMesh.lodDistances ? parsedMesh.lodDistances : null, coverages: parsedMesh.lodCoverages ? parsedMesh.lodCoverages : null }; } if (parsedMesh.instances) { for (let index = 0; index < parsedMesh.instances.length; index++) { const parsedInstance = parsedMesh.instances[index]; const instance = mesh.createInstance(parsedInstance.name); if (parsedInstance.id) { instance.id = parsedInstance.id; } if (Tags) { if (parsedInstance.tags) { Tags.AddTagsTo(instance, parsedInstance.tags); } else { Tags.AddTagsTo(instance, parsedMesh.tags); } } instance.position = Vector3.FromArray(parsedInstance.position); if (parsedInstance.metadata !== void 0) { instance.metadata = parsedInstance.metadata; } if (parsedInstance.parentId !== void 0) { instance._waitingParentId = parsedInstance.parentId; } if (parsedInstance.parentInstanceIndex !== void 0) { instance._waitingParentInstanceIndex = parsedInstance.parentInstanceIndex; } if (parsedInstance.isEnabled !== void 0 && parsedInstance.isEnabled !== null) { instance.setEnabled(parsedInstance.isEnabled); } if (parsedInstance.isVisible !== void 0 && parsedInstance.isVisible !== null) { instance.isVisible = parsedInstance.isVisible; } if (parsedInstance.isPickable !== void 0 && parsedInstance.isPickable !== null) { instance.isPickable = parsedInstance.isPickable; } if (parsedInstance.rotationQuaternion) { instance.rotationQuaternion = Quaternion.FromArray(parsedInstance.rotationQuaternion); } else if (parsedInstance.rotation) { instance.rotation = Vector3.FromArray(parsedInstance.rotation); } instance.scaling = Vector3.FromArray(parsedInstance.scaling); if (parsedInstance.checkCollisions != void 0 && parsedInstance.checkCollisions != null) { instance.checkCollisions = parsedInstance.checkCollisions; } if (parsedInstance.pickable != void 0 && parsedInstance.pickable != null) { instance.isPickable = parsedInstance.pickable; } if (parsedInstance.showBoundingBox != void 0 && parsedInstance.showBoundingBox != null) { instance.showBoundingBox = parsedInstance.showBoundingBox; } if (parsedInstance.showSubMeshesBoundingBox != void 0 && parsedInstance.showSubMeshesBoundingBox != null) { instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox; } if (parsedInstance.alphaIndex != void 0 && parsedInstance.showSubMeshesBoundingBox != null) { instance.alphaIndex = parsedInstance.alphaIndex; } if (parsedInstance.physicsImpostor) { instance.physicsImpostor = _Mesh._PhysicsImpostorParser(scene, instance, parsedInstance); } if (parsedInstance.actions !== void 0) { instance._waitingData.actions = parsedInstance.actions; } if (parsedInstance.animations) { for (let animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) { const parsedAnimation = parsedInstance.animations[animationIndex]; const internalClass = GetClass("BABYLON.Animation"); if (internalClass) { instance.animations.push(internalClass.Parse(parsedAnimation)); } } Node.ParseAnimationRanges(instance, parsedInstance, scene); if (parsedInstance.autoAnimate) { scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1); } } } } if (parsedMesh.thinInstances) { const thinInstances = parsedMesh.thinInstances; mesh.thinInstanceEnablePicking = !!thinInstances.enablePicking; if (thinInstances.matrixData) { mesh.thinInstanceSetBuffer("matrix", new Float32Array(thinInstances.matrixData), 16, false); mesh._thinInstanceDataStorage.matrixBufferSize = thinInstances.matrixBufferSize; mesh._thinInstanceDataStorage.instancesCount = thinInstances.instancesCount; } else { mesh._thinInstanceDataStorage.matrixBufferSize = thinInstances.matrixBufferSize; } if (parsedMesh.thinInstances.userThinInstance) { const userThinInstance = parsedMesh.thinInstances.userThinInstance; for (const kind in userThinInstance.data) { mesh.thinInstanceSetBuffer(kind, new Float32Array(userThinInstance.data[kind]), userThinInstance.strides[kind], false); mesh._userThinInstanceBuffersStorage.sizes[kind] = userThinInstance.sizes[kind]; } } } return mesh; } // Skeletons /** * Prepare internal position array for software CPU skinning * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh */ setPositionsForCPUSkinning() { const internalDataInfo = this._internalMeshDataInfo; if (!internalDataInfo._sourcePositions) { const source = this.getVerticesData(VertexBuffer.PositionKind); if (!source) { return internalDataInfo._sourcePositions; } internalDataInfo._sourcePositions = new Float32Array(source); if (!this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) { this.setVerticesData(VertexBuffer.PositionKind, source, true); } } return internalDataInfo._sourcePositions; } /** * Prepare internal normal array for software CPU skinning * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh. */ setNormalsForCPUSkinning() { const internalDataInfo = this._internalMeshDataInfo; if (!internalDataInfo._sourceNormals) { const source = this.getVerticesData(VertexBuffer.NormalKind); if (!source) { return internalDataInfo._sourceNormals; } internalDataInfo._sourceNormals = new Float32Array(source); if (!this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) { this.setVerticesData(VertexBuffer.NormalKind, source, true); } } return internalDataInfo._sourceNormals; } /** * Updates the vertex buffer by applying transformation from the bones * @param skeleton defines the skeleton to apply to current mesh * @returns the current mesh */ applySkeleton(skeleton) { if (!this.geometry) { return this; } if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) { return this; } this.geometry._softwareSkinningFrameId = this.getScene().getFrameId(); if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) { return this; } if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) { return this; } if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) { return this; } const hasNormals = this.isVerticesDataPresent(VertexBuffer.NormalKind); const internalDataInfo = this._internalMeshDataInfo; if (!internalDataInfo._sourcePositions) { const submeshes = this.subMeshes.slice(); this.setPositionsForCPUSkinning(); this.subMeshes = submeshes; } if (hasNormals && !internalDataInfo._sourceNormals) { this.setNormalsForCPUSkinning(); } let positionsData = this.getVerticesData(VertexBuffer.PositionKind); if (!positionsData) { return this; } if (!(positionsData instanceof Float32Array)) { positionsData = new Float32Array(positionsData); } let normalsData = this.getVerticesData(VertexBuffer.NormalKind); if (hasNormals) { if (!normalsData) { return this; } if (!(normalsData instanceof Float32Array)) { normalsData = new Float32Array(normalsData); } } const matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind); const matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind); if (!matricesWeightsData || !matricesIndicesData) { return this; } const needExtras = this.numBoneInfluencers > 4; const matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null; const matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null; const skeletonMatrices = skeleton.getTransformMatrices(this); const tempVector3 = Vector3.Zero(); const finalMatrix = new Matrix(); const tempMatrix = new Matrix(); let matWeightIdx = 0; let inf; for (let index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) { let weight; for (inf = 0; inf < 4; inf++) { weight = matricesWeightsData[matWeightIdx + inf]; if (weight > 0) { Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix); finalMatrix.addToSelf(tempMatrix); } } if (needExtras) { for (inf = 0; inf < 4; inf++) { weight = matricesWeightsExtraData[matWeightIdx + inf]; if (weight > 0) { Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix); finalMatrix.addToSelf(tempMatrix); } } } Vector3.TransformCoordinatesFromFloatsToRef(internalDataInfo._sourcePositions[index], internalDataInfo._sourcePositions[index + 1], internalDataInfo._sourcePositions[index + 2], finalMatrix, tempVector3); tempVector3.toArray(positionsData, index); if (hasNormals) { Vector3.TransformNormalFromFloatsToRef(internalDataInfo._sourceNormals[index], internalDataInfo._sourceNormals[index + 1], internalDataInfo._sourceNormals[index + 2], finalMatrix, tempVector3); tempVector3.toArray(normalsData, index); } finalMatrix.reset(); } this.updateVerticesData(VertexBuffer.PositionKind, positionsData); if (hasNormals) { this.updateVerticesData(VertexBuffer.NormalKind, normalsData); } return this; } // Tools /** * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates * @param meshes defines the list of meshes to scan * @returns an object `{min:` Vector3`, max:` Vector3`}` */ static MinMax(meshes) { let minVector = null; let maxVector = null; for (const mesh of meshes) { const boundingInfo = mesh.getBoundingInfo(); const boundingBox = boundingInfo.boundingBox; if (!minVector || !maxVector) { minVector = boundingBox.minimumWorld.clone(); maxVector = boundingBox.maximumWorld.clone(); } else { minVector.minimizeInPlace(boundingBox.minimumWorld); maxVector.maximizeInPlace(boundingBox.maximumWorld); } } if (!minVector || !maxVector) { return { min: Vector3.Zero(), max: Vector3.Zero() }; } return { min: minVector, max: maxVector }; } /** * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object * @returns a vector3 */ static Center(meshesOrMinMaxVector) { const minMaxVector = meshesOrMinMaxVector instanceof Array ? _Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector; return Vector3.Center(minMaxVector.min, minMaxVector.max); } /** * Merge the array of meshes into a single mesh for performance reasons. * @param meshes array of meshes with the vertices to merge. Entries cannot be empty meshes. * @param disposeSource when true (default), dispose of the vertices from the source meshes. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true. * @param meshSubclass (optional) can be set to a Mesh where the merged vertices will be inserted. * @param subdivideWithSubMeshes when true (false default), subdivide mesh into subMeshes. * @param multiMultiMaterials when true (false default), subdivide mesh into subMeshes with multiple materials, ignores subdivideWithSubMeshes. * @returns a new mesh */ static MergeMeshes(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials) { return runCoroutineSync(_Mesh._MergeMeshesCoroutine(meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, false)); } /** * Merge the array of meshes into a single mesh for performance reasons. * @param meshes array of meshes with the vertices to merge. Entries cannot be empty meshes. * @param disposeSource when true (default), dispose of the vertices from the source meshes. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true. * @param meshSubclass (optional) can be set to a Mesh where the merged vertices will be inserted. * @param subdivideWithSubMeshes when true (false default), subdivide mesh into subMeshes. * @param multiMultiMaterials when true (false default), subdivide mesh into subMeshes with multiple materials, ignores subdivideWithSubMeshes. * @returns a new mesh */ static async MergeMeshesAsync(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials) { return await runCoroutineAsync(_Mesh._MergeMeshesCoroutine(meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, true), createYieldingScheduler()); } static *_MergeMeshesCoroutine(meshes, disposeSource = true, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes, multiMultiMaterials, isAsync) { meshes = meshes.filter(Boolean); if (meshes.length === 0) { return null; } let index; if (!allow32BitsIndices) { let totalVertices = 0; for (index = 0; index < meshes.length; index++) { totalVertices += meshes[index].getTotalVertices(); if (totalVertices >= 65536) { Logger.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"); return null; } } } if (multiMultiMaterials) { subdivideWithSubMeshes = false; } const materialArray = new Array(); const materialIndexArray = new Array(); const indiceArray = new Array(); const currentsideOrientation = meshes[0].sideOrientation; for (index = 0; index < meshes.length; index++) { const mesh = meshes[index]; if (mesh.isAnInstance) { Logger.Warn("Cannot merge instance meshes."); return null; } if (currentsideOrientation !== mesh.sideOrientation) { Logger.Warn("Cannot merge meshes with different sideOrientation values."); return null; } if (subdivideWithSubMeshes) { indiceArray.push({ start: 0, count: mesh.getTotalIndices() }); } if (multiMultiMaterials) { const indexOffset = indiceArray.reduce((accumulator, currentValue) => { return Math.max(accumulator, currentValue.start + currentValue.count); }, 0); if (mesh.material) { const material = mesh.material; if (material instanceof MultiMaterial) { for (let matIndex = 0; matIndex < material.subMaterials.length; matIndex++) { if (materialArray.indexOf(material.subMaterials[matIndex]) < 0) { materialArray.push(material.subMaterials[matIndex]); } } for (let subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) { materialIndexArray.push(materialArray.indexOf(material.subMaterials[mesh.subMeshes[subIndex].materialIndex])); indiceArray.push({ start: indexOffset + mesh.subMeshes[subIndex].indexStart, count: mesh.subMeshes[subIndex].indexCount }); } } else { if (materialArray.indexOf(material) < 0) { materialArray.push(material); } for (let subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) { materialIndexArray.push(materialArray.indexOf(material)); indiceArray.push({ start: indexOffset + mesh.subMeshes[subIndex].indexStart, count: mesh.subMeshes[subIndex].indexCount }); } } } else { for (let subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) { materialIndexArray.push(0); indiceArray.push({ start: indexOffset + mesh.subMeshes[subIndex].indexStart, count: mesh.subMeshes[subIndex].indexCount }); } } } } const source = meshes[0]; const getVertexDataFromMesh = /* @__PURE__ */ __name((mesh) => { const wm = mesh.computeWorldMatrix(true); const vertexData2 = VertexData.ExtractFromMesh(mesh, false, false); return { vertexData: vertexData2, transform: wm }; }, "getVertexDataFromMesh"); const { vertexData: sourceVertexData, transform: sourceTransform } = getVertexDataFromMesh(source); if (isAsync) { yield; } const meshVertexDatas = new Array(meshes.length - 1); for (let i = 1; i < meshes.length; i++) { meshVertexDatas[i - 1] = getVertexDataFromMesh(meshes[i]); if (isAsync) { yield; } } const mergeCoroutine = sourceVertexData._mergeCoroutine(sourceTransform, meshVertexDatas, allow32BitsIndices, isAsync, !disposeSource); let mergeCoroutineStep = mergeCoroutine.next(); while (!mergeCoroutineStep.done) { if (isAsync) { yield; } mergeCoroutineStep = mergeCoroutine.next(); } const vertexData = mergeCoroutineStep.value; if (!meshSubclass) { meshSubclass = new _Mesh(source.name + "_merged", source.getScene()); } const applyToCoroutine = vertexData._applyToCoroutine(meshSubclass, void 0, isAsync); let applyToCoroutineStep = applyToCoroutine.next(); while (!applyToCoroutineStep.done) { if (isAsync) { yield; } applyToCoroutineStep = applyToCoroutine.next(); } meshSubclass.checkCollisions = source.checkCollisions; meshSubclass.sideOrientation = source.sideOrientation; if (disposeSource) { for (index = 0; index < meshes.length; index++) { meshes[index].dispose(); } } if (subdivideWithSubMeshes || multiMultiMaterials) { meshSubclass.releaseSubMeshes(); index = 0; while (index < indiceArray.length) { SubMesh.CreateFromIndices(0, indiceArray[index].start, indiceArray[index].count, meshSubclass, void 0, false); index++; } for (const subMesh of meshSubclass.subMeshes) { subMesh.refreshBoundingInfo(); } meshSubclass.computeWorldMatrix(true); } if (multiMultiMaterials) { const newMultiMaterial = new MultiMaterial(source.name + "_merged", source.getScene()); newMultiMaterial.subMaterials = materialArray; for (let subIndex = 0; subIndex < meshSubclass.subMeshes.length; subIndex++) { meshSubclass.subMeshes[subIndex].materialIndex = materialIndexArray[subIndex]; } meshSubclass.material = newMultiMaterial; } else { meshSubclass.material = source.material; } return meshSubclass; } /** * @internal */ addInstance(instance) { instance._indexInSourceMeshInstanceArray = this.instances.length; this.instances.push(instance); } /** * @internal */ removeInstance(instance) { const index = instance._indexInSourceMeshInstanceArray; if (index != -1) { if (index !== this.instances.length - 1) { const last = this.instances[this.instances.length - 1]; this.instances[index] = last; last._indexInSourceMeshInstanceArray = index; } instance._indexInSourceMeshInstanceArray = -1; this.instances.pop(); } } /** @internal */ _shouldConvertRHS() { return this._scene.useRightHandedSystem && this.sideOrientation === Material.CounterClockWiseSideOrientation; } /** @internal */ _getRenderingFillMode(fillMode) { const scene = this.getScene(); if (scene.forcePointsCloud) { return Material.PointFillMode; } if (scene.forceWireframe) { return Material.WireFrameFillMode; } return this.overrideRenderingFillMode ?? fillMode; } // deprecated methods /** * Sets the mesh material by the material or multiMaterial `id` property * @param id is a string identifying the material or the multiMaterial * @returns the current mesh * @deprecated Please use MeshBuilder instead Please use setMaterialById instead */ // eslint-disable-next-line @typescript-eslint/naming-convention setMaterialByID(id) { return this.setMaterialById(id); } /** * Creates a ribbon mesh. * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param * @param name defines the name of the mesh to create * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry. * @param closeArray creates a seam between the first and the last paths of the path array (default is false) * @param closePath creates a seam between the first and the last points of each path of the path array * @param offset is taken in account only if the `pathArray` is containing a single path * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon) * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateRibbon(name260, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a plane polygonal mesh. By default, this is a disc. * @param name defines the name of the mesh to create * @param radius sets the radius size (float) of the polygon (default 0.5) * @param tessellation sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateDisc(name260, radius, tessellation, scene, updatable, sideOrientation) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a box mesh. * @param name defines the name of the mesh to create * @param size sets the size (float) of each box side (default 1) * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateBox(name260, size, scene, updatable, sideOrientation) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a sphere mesh. * @param name defines the name of the mesh to create * @param segments sets the sphere number of horizontal stripes (positive integer, default 32) * @param diameter sets the diameter size (float) of the sphere (default 1) * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateSphere(name260, segments, diameter, scene, updatable, sideOrientation) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a hemisphere mesh. * @param name defines the name of the mesh to create * @param segments sets the sphere number of horizontal stripes (positive integer, default 32) * @param diameter sets the diameter size (float) of the sphere (default 1) * @param scene defines the hosting scene * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateHemisphere(name260, segments, diameter, scene) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a cylinder or a cone mesh. * @param name defines the name of the mesh to create * @param height sets the height size (float) of the cylinder/cone (float, default 2) * @param diameterTop set the top cap diameter (floats, default 1) * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1) * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateCylinder(name260, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) { throw new Error("Import MeshBuilder to populate this function"); } // Torus (Code from SharpDX.org) /** * Creates a torus mesh. * @param name defines the name of the mesh to create * @param diameter sets the diameter size (float) of the torus (default 1) * @param thickness sets the diameter size of the tube of the torus (float, default 0.5) * @param tessellation sets the number of torus sides (positive integer, default 16) * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateTorus(name260, diameter, thickness, tessellation, scene, updatable, sideOrientation) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a torus knot mesh. * @param name defines the name of the mesh to create * @param radius sets the global radius size (float) of the torus knot (default 2) * @param tube sets the diameter size of the tube of the torus (float, default 0.5) * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32) * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32) * @param p the number of windings on X axis (positive integers, default 2) * @param q the number of windings on Y axis (positive integers, default 3) * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateTorusKnot(name260, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a line mesh.. * @param name defines the name of the mesh to create * @param points is an array successive Vector3 * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines). * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateLines(name260, points, scene, updatable, instance) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a dashed line mesh. * @param name defines the name of the mesh to create * @param points is an array successive Vector3 * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3) * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1) * @param dashNb is the intended total number of dashes (positive integer, default 200) * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines) * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateDashedLines(name260, points, dashSize, gapSize, dashNb, scene, updatable, instance) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors. * You can set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created. * Remember you can only change the shape positions, not their number when updating a polygon. * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#non-regular-polygon * @param name defines the name of the mesh to create * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors * @param scene defines the hosting scene * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon * @param updatable defines if the mesh must be flagged as updatable * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) * @param earcutInjection can be used to inject your own earcut reference * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreatePolygon(name260, shape, scene, holes, updatable, sideOrientation, earcutInjection) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates an extruded polygon mesh, with depth in the Y direction.. * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-non-regular-polygon * @param name defines the name of the mesh to create * @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors * @param depth defines the height of extrusion * @param scene defines the hosting scene * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon * @param updatable defines if the mesh must be flagged as updatable * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) * @param earcutInjection can be used to inject your own earcut reference * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static ExtrudePolygon(name260, shape, depth, scene, holes, updatable, sideOrientation, earcutInjection) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates an extruded shape mesh. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes * @param name defines the name of the mesh to create * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along * @param scale is the value to scale the shape * @param rotation is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#extruded-shape) * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static ExtrudeShape(name260, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates an custom extruded shape mesh. * The custom extrusion is a parametric shape. * It has no predefined shape. Its final shape will depend on the input parameters. * * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param#extruded-shapes * @param name defines the name of the mesh to create * @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along * @param scaleFunction is a custom Javascript function called on each path point * @param rotationFunction is a custom Javascript function called on each path point * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray` * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray` * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) * @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (https://doc.babylonjs.com/features/featuresDeepDive/mesh/dynamicMeshMorph#extruded-shape) * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static ExtrudeShapeCustom(name260, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates lathe mesh. * The lathe is a shape with a symmetry axis : a 2D model shape is rotated around this axis to design the lathe. * @param name defines the name of the mesh to create * @param shape is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero * @param radius is the radius value of the lathe * @param tessellation is the side number of the lathe. * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateLathe(name260, shape, radius, tessellation, scene, updatable, sideOrientation) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a plane mesh. * @param name defines the name of the mesh to create * @param size sets the size (float) of both sides of the plane at once (default 1) * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreatePlane(name260, size, scene, updatable, sideOrientation) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a ground mesh. * @param name defines the name of the mesh to create * @param width set the width of the ground * @param height set the height of the ground * @param subdivisions sets the number of subdivisions per side * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateGround(name260, width, height, subdivisions, scene, updatable) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a tiled ground mesh. * @param name defines the name of the mesh to create * @param xmin set the ground minimum X coordinate * @param zmin set the ground minimum Y coordinate * @param xmax set the ground maximum X coordinate * @param zmax set the ground maximum Z coordinate * @param subdivisions is an object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile * @param precision is an object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateTiledGround(name260, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a ground mesh from a height map. * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set/height_map * @param name defines the name of the mesh to create * @param url sets the URL of the height map image resource * @param width set the ground width size * @param height set the ground height size * @param subdivisions sets the number of subdivision per side * @param minHeight is the minimum altitude on the ground * @param maxHeight is the maximum altitude on the ground * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time) * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible) * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateGroundFromHeightMap(name260, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a tube mesh. * The tube is a parametric shape. * It has no predefined shape. Its final shape will depend on the input parameters. * * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/param * @param name defines the name of the mesh to create * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube * @param radius sets the tube radius size * @param tessellation is the number of sides on the tubular surface * @param radiusFunction is a custom function. If it is not null, it overrides the parameter `radius`. This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL * @param scene defines the hosting scene * @param updatable defines if the mesh must be flagged as updatable * @param sideOrientation defines the mesh side orientation (https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation) * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (https://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube) * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateTube(name260, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a polyhedron mesh. *. * * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embedded types. Please refer to the type sheet in the tutorial to choose the wanted type * * The parameter `size` (positive float, default 1) sets the polygon size * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value) * * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type` * * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron * * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`) * * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : https://doc.babylonjs.com/features/featuresDeepDive/materials/using/texturePerBoxFace * * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored * * You can also set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @param name defines the name of the mesh to create * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreatePolyhedron(name260, options, scene) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided * * The parameter `radius` sets the radius size (float) of the icosphere (default 1) * * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`) * * The parameter `subdivisions` sets the number of subdivisions (positive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size * * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface * * You can also set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/set#side-orientation * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created * @see https://doc.babylonjs.com/features/featuresDeepDive/mesh/creation/polyhedra#icosphere * @param name defines the name of the mesh * @param options defines the options used to create the mesh * @param scene defines the hosting scene * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateIcoSphere(name260, options, scene) { throw new Error("Import MeshBuilder to populate this function"); } /** * Creates a decal mesh. *. * A decal is a mesh usually applied as a model onto the surface of another mesh * @param name defines the name of the mesh * @param sourceMesh defines the mesh receiving the decal * @param position sets the position of the decal in world coordinates * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates * @param size sets the decal scaling * @param angle sets the angle to rotate the decal * @returns a new Mesh * @deprecated Please use MeshBuilder instead */ static CreateDecal(name260, sourceMesh, position, normal, size, angle) { throw new Error("Import MeshBuilder to populate this function"); } /** Creates a Capsule Mesh * @param name defines the name of the mesh. * @param options the constructors options used to shape the mesh. * @param scene defines the scene the mesh is scoped to. * @returns the capsule mesh * @see https://doc.babylonjs.com/how_to/capsule_shape * @deprecated Please use MeshBuilder instead */ static CreateCapsule(name260, options, scene) { throw new Error("Import MeshBuilder to populate this function"); } /** * Extends a mesh to a Goldberg mesh * Warning the mesh to convert MUST be an import of a perviously exported Goldberg mesh * @param mesh the mesh to convert * @returns the extended mesh * @deprecated Please use ExtendMeshToGoldberg instead */ static ExtendToGoldberg(mesh) { throw new Error("Import MeshBuilder to populate this function"); } }; Mesh.FRONTSIDE = VertexData.FRONTSIDE; Mesh.BACKSIDE = VertexData.BACKSIDE; Mesh.DOUBLESIDE = VertexData.DOUBLESIDE; Mesh.DEFAULTSIDE = VertexData.DEFAULTSIDE; Mesh.NO_CAP = 0; Mesh.CAP_START = 1; Mesh.CAP_END = 2; Mesh.CAP_ALL = 3; Mesh.NO_FLIP = 0; Mesh.FLIP_TILE = 1; Mesh.ROTATE_TILE = 2; Mesh.FLIP_ROW = 3; Mesh.ROTATE_ROW = 4; Mesh.FLIP_N_ROTATE_TILE = 5; Mesh.FLIP_N_ROTATE_ROW = 6; Mesh.CENTER = 0; Mesh.LEFT = 1; Mesh.RIGHT = 2; Mesh.TOP = 3; Mesh.BOTTOM = 4; Mesh.INSTANCEDMESH_SORT_TRANSPARENT = false; Mesh._GroundMeshParser = (parsedMesh, scene) => { throw _WarnImport("GroundMesh"); }; Mesh._GoldbergMeshParser = (parsedMesh, scene) => { throw _WarnImport("GoldbergMesh"); }; Mesh._LinesMeshParser = (parsedMesh, scene) => { throw _WarnImport("LinesMesh"); }; Mesh._GreasedLineMeshParser = (parsedMesh, scene) => { throw _WarnImport("GreasedLineMesh"); }; Mesh._GreasedLineRibbonMeshParser = (parsedMesh, scene) => { throw _WarnImport("GreasedLineRibbonMesh"); }; Mesh._TrailMeshParser = (parsedMesh, scene) => { throw _WarnImport("TrailMesh"); }; RegisterClass("BABYLON.Mesh", Mesh); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/Builders/planeBuilder.js init_compatibilityOptions(); function CreatePlaneVertexData(options) { const indices = []; const positions = []; const normals = []; const uvs = []; const width = options.width !== void 0 ? options.width : options.size !== void 0 ? options.size : 1; const height = options.height !== void 0 ? options.height : options.size !== void 0 ? options.size : 1; const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; const halfWidth = width / 2; const halfHeight = height / 2; positions.push(-halfWidth, -halfHeight, 0); normals.push(0, 0, -1); uvs.push(0, useOpenGLOrientationForUV ? 1 : 0); positions.push(halfWidth, -halfHeight, 0); normals.push(0, 0, -1); uvs.push(1, useOpenGLOrientationForUV ? 1 : 0); positions.push(halfWidth, halfHeight, 0); normals.push(0, 0, -1); uvs.push(1, useOpenGLOrientationForUV ? 0 : 1); positions.push(-halfWidth, halfHeight, 0); normals.push(0, 0, -1); uvs.push(0, useOpenGLOrientationForUV ? 0 : 1); indices.push(0); indices.push(1); indices.push(2); indices.push(0); indices.push(2); indices.push(3); VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); const vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; return vertexData; } __name(CreatePlaneVertexData, "CreatePlaneVertexData"); function CreatePlane(name260, options = {}, scene = null) { const plane = new Mesh(name260, scene); options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); plane._originalBuilderSideOrientation = options.sideOrientation; const vertexData = CreatePlaneVertexData(options); vertexData.applyToMesh(plane, options.updatable); if (options.sourcePlane) { plane.translate(options.sourcePlane.normal, -options.sourcePlane.d); plane.setDirection(options.sourcePlane.normal.scale(-1)); } return plane; } __name(CreatePlane, "CreatePlane"); var PlaneBuilder = { // eslint-disable-next-line @typescript-eslint/naming-convention CreatePlane }; VertexData.CreatePlane = CreatePlaneVertexData; Mesh.CreatePlane = (name260, size, scene, updatable, sideOrientation) => { const options = { size, width: size, height: size, sideOrientation, updatable }; return CreatePlane(name260, options, scene); }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/volumetricLightScattering.fragment.js init_shaderStore(); var name184 = "volumetricLightScatteringPixelShader"; var shader184 = `uniform sampler2D textureSampler;uniform sampler2D lightScatteringSampler;uniform float decay;uniform float exposure;uniform float weight;uniform float density;uniform vec2 meshPositionOnScreen;varying vec2 vUV; #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #define CUSTOM_FRAGMENT_MAIN_BEGIN vec2 tc=vUV;vec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);deltaTexCoord*=1.0/float(NUM_SAMPLES)*density;float illuminationDecay=1.0;vec4 color=texture2D(lightScatteringSampler,tc)*0.4;for(int i=0; i #include #include #include[0..maxSimultaneousMorphTargets] #include uniform mat4 viewProjection;uniform vec2 depthValues; #if defined(ALPHATEST) || defined(NEED_UV) varying vec2 vUV;uniform mat4 diffuseMatrix; #ifdef UV1 attribute vec2 uv; #endif #ifdef UV2 attribute vec2 uv2; #endif #endif #define CUSTOM_VERTEX_DEFINITIONS void main(void) {vec3 positionUpdated=position; #if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV1) vec2 uvUpdated=uv; #endif #if (defined(ALPHATEST) || defined(NEED_UV)) && defined(UV2) vec2 uv2Updated=uv2; #endif #include #include[0..maxSimultaneousMorphTargets] #include #include #include gl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0); #if defined(ALPHATEST) || defined(BASIC_RENDER) #ifdef UV1 vUV=vec2(diffuseMatrix*vec4(uvUpdated,1.0,0.0)); #endif #ifdef UV2 vUV=vec2(diffuseMatrix*vec4(uv2Updated,1.0,0.0)); #endif #endif } `; if (!ShaderStore.ShadersStore[name185]) { ShaderStore.ShadersStore[name185] = shader185; } var volumetricLightScatteringPassVertexShader = { name: name185, shader: shader185 }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/volumetricLightScatteringPass.fragment.js init_shaderStore(); var name186 = "volumetricLightScatteringPassPixelShader"; var shader186 = `#if defined(ALPHATEST) || defined(NEED_UV) varying vec2 vUV; #endif #if defined(ALPHATEST) uniform sampler2D diffuseSampler; #endif #define CUSTOM_FRAGMENT_DEFINITIONS void main(void) { #if defined(ALPHATEST) vec4 diffuseColor=texture2D(diffuseSampler,vUV);if (diffuseColor.a<0.4) discard; #endif gl_FragColor=vec4(0.0,0.0,0.0,1.0);} `; if (!ShaderStore.ShadersStore[name186]) { ShaderStore.ShadersStore[name186] = shader186; } var volumetricLightScatteringPassPixelShader = { name: name186, shader: shader186 }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/volumetricLightScatteringPostProcess.js init_tslib_es6(); init_decorators(); init_logger(); init_math_vector(); init_buffer(); init_texture(); init_renderTargetTexture(); init_postProcess(); init_depth_vertex2(); init_math_color(); init_math_viewport(); init_typeStore(); init_materialHelper_functions(); init_effectFallbacks(); var VolumetricLightScatteringPostProcess = class _VolumetricLightScatteringPostProcess extends PostProcess { static { __name(this, "VolumetricLightScatteringPostProcess"); } /** * @internal * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead */ get useDiffuseColor() { Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"); return false; } set useDiffuseColor(useDiffuseColor) { Logger.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead"); } /** * @constructor * @param name The post-process name * @param ratio The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) * @param camera The camera that the post-process will be attached to * @param mesh The mesh used to create the light scattering * @param samples The post-process quality, default 100 * @param samplingMode The post-process filtering mode * @param engine The babylon engine * @param reusable If the post-process is reusable * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided */ constructor(name260, ratio, camera, mesh, samples = 100, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine, reusable, scene) { super(name260, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples); this._screenCoordinates = Vector2.Zero(); this.customMeshPosition = Vector3.Zero(); this.useCustomMeshPosition = false; this.invert = true; this.excludedMeshes = []; this.includedMeshes = []; this.exposure = 0.3; this.decay = 0.96815; this.weight = 0.58767; this.density = 0.926; scene = camera?.getScene() ?? scene ?? this._scene; engine = scene.getEngine(); this._viewPort = new Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight()); this.mesh = mesh ?? _VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene); this._createPass(scene, ratio.passRatio || ratio); this.onActivate = (camera2) => { if (!this.isSupported) { this.dispose(camera2); } this.onActivate = null; }; this.onApplyObservable.add((effect) => { this._updateMeshScreenCoordinates(scene); effect.setTexture("lightScatteringSampler", this._volumetricLightScatteringRTT); effect.setFloat("exposure", this.exposure); effect.setFloat("decay", this.decay); effect.setFloat("weight", this.weight); effect.setFloat("density", this.density); effect.setVector2("meshPositionOnScreen", this._screenCoordinates); }); } /** * Returns the string "VolumetricLightScatteringPostProcess" * @returns "VolumetricLightScatteringPostProcess" */ getClassName() { return "VolumetricLightScatteringPostProcess"; } _isReady(subMesh, useInstances) { const mesh = subMesh.getMesh(); if (mesh === this.mesh && mesh.material) { return mesh.material.isReady(mesh); } const renderingMaterial = mesh._internalAbstractMeshDataInfo._materialForRenderPass?.[this._scene.getEngine().currentRenderPassId]; if (renderingMaterial) { return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances); } const defines = []; const attribs = [VertexBuffer.PositionKind]; const material = subMesh.getMaterial(); let uv1 = false; let uv2 = false; const color = false; if (material) { const needAlphaTesting = material.needAlphaTestingForMesh(mesh); if (needAlphaTesting) { defines.push("#define ALPHATEST"); } if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { attribs.push(VertexBuffer.UVKind); defines.push("#define UV1"); uv1 = needAlphaTesting; } if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) { attribs.push(VertexBuffer.UV2Kind); defines.push("#define UV2"); uv2 = needAlphaTesting; } } const fallbacks = new EffectFallbacks(); if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { attribs.push(VertexBuffer.MatricesIndicesKind); attribs.push(VertexBuffer.MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(VertexBuffer.MatricesIndicesExtraKind); attribs.push(VertexBuffer.MatricesWeightsExtraKind); } defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); if (mesh.numBoneInfluencers > 0) { fallbacks.addCPUSkinningFallback(0, mesh); } const skeleton = mesh.skeleton; if (skeleton.isUsingTextureForMatrices) { defines.push("#define BONETEXTURE"); } else { defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1)); } } else { defines.push("#define NUM_BONE_INFLUENCERS 0"); } const numMorphInfluencers = mesh.morphTargetManager ? PrepareDefinesAndAttributesForMorphTargets( mesh.morphTargetManager, defines, attribs, mesh, true, // usePositionMorph false, // useNormalMorph false, // useTangentMorph uv1, // useUVMorph uv2, // useUV2Morph color // useColorMorph ) : 0; if (useInstances) { defines.push("#define INSTANCES"); PushAttributesForInstances(attribs); if (subMesh.getRenderingMesh().hasThinInstances) { defines.push("#define THIN_INSTANCES"); } } const bvaManager = mesh.bakedVertexAnimationManager; if (bvaManager && bvaManager.isEnabled) { defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"); if (useInstances) { attribs.push("bakedVertexAnimationSettingsInstanced"); } } const drawWrapper = subMesh._getDrawWrapper(void 0, true); const cachedDefines = drawWrapper.defines; const join = defines.join("\n"); if (cachedDefines !== join) { const uniforms = [ "world", "mBones", "boneTextureWidth", "viewProjection", "diffuseMatrix", "morphTargetInfluences", "morphTargetCount", "morphTargetTextureInfo", "morphTargetTextureIndices", "bakedVertexAnimationSettings", "bakedVertexAnimationTextureSizeInverted", "bakedVertexAnimationTime", "bakedVertexAnimationTexture" ]; const samplers = ["diffuseSampler", "morphTargets", "boneSampler", "bakedVertexAnimationTexture"]; drawWrapper.setEffect(mesh.getScene().getEngine().createEffect("volumetricLightScatteringPass", { attributes: attribs, uniformsNames: uniforms, uniformBuffersNames: [], samplers, defines: join, fallbacks, onCompiled: null, onError: null, indexParameters: { maxSimultaneousMorphTargets: numMorphInfluencers } }, mesh.getScene().getEngine()), join); } return drawWrapper.effect.isReady(); } /** * Sets the new light position for light scattering effect * @param position The new custom light position */ setCustomMeshPosition(position) { this.customMeshPosition = position; } /** * Returns the light position for light scattering effect * @returns Vector3 The custom light position */ getCustomMeshPosition() { return this.customMeshPosition; } /** * Disposes the internal assets and detaches the post-process from the camera * @param camera The camera from which to detach the post-process */ dispose(camera) { const rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT); if (rttIndex !== -1) { camera.getScene().customRenderTargets.splice(rttIndex, 1); } this._volumetricLightScatteringRTT.dispose(); super.dispose(camera); } /** * Returns the render target texture used by the post-process * @returns the render target texture used by the post-process */ getPass() { return this._volumetricLightScatteringRTT; } // Private methods _meshExcluded(mesh) { if (this.includedMeshes.length > 0 && this.includedMeshes.indexOf(mesh) === -1 || this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) { return true; } return false; } _createPass(scene, ratio) { const engine = scene.getEngine(); this._volumetricLightScatteringRTT = new RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, 0); this._volumetricLightScatteringRTT.wrapU = Texture.CLAMP_ADDRESSMODE; this._volumetricLightScatteringRTT.wrapV = Texture.CLAMP_ADDRESSMODE; this._volumetricLightScatteringRTT.renderList = null; this._volumetricLightScatteringRTT.renderParticles = false; this._volumetricLightScatteringRTT.ignoreCameraViewport = true; const camera = this.getCamera(); if (camera) { camera.customRenderTargets.push(this._volumetricLightScatteringRTT); } else { scene.customRenderTargets.push(this._volumetricLightScatteringRTT); } const renderSubMesh = /* @__PURE__ */ __name((subMesh) => { const renderingMesh = subMesh.getRenderingMesh(); const effectiveMesh = subMesh.getEffectiveMesh(); if (this._meshExcluded(renderingMesh)) { return; } effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; const material = subMesh.getMaterial(); if (!material) { return; } const scene2 = renderingMesh.getScene(); const engine2 = scene2.getEngine(); engine2.setState(material.backFaceCulling, void 0, void 0, void 0, material.cullBackFaces); const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); if (batch.mustReturn) { return; } const hardwareInstancedRendering = engine2.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances); if (this._isReady(subMesh, hardwareInstancedRendering)) { const renderingMaterial = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine2.currentRenderPassId]; let drawWrapper = subMesh._getDrawWrapper(); if (renderingMesh === this.mesh && !drawWrapper) { drawWrapper = material._getDrawWrapper(); } if (!drawWrapper) { return; } const effect = drawWrapper.effect; engine2.enableEffect(drawWrapper); if (!hardwareInstancedRendering) { renderingMesh._bind(subMesh, effect, material.fillMode); } if (renderingMesh === this.mesh) { material.bind(effectiveMesh.getWorldMatrix(), renderingMesh); } else if (renderingMaterial) { renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh); } else { effect.setMatrix("viewProjection", scene2.getTransformMatrix()); if (material.needAlphaTestingForMesh(effectiveMesh)) { const alphaTexture = material.getAlphaTestTexture(); if (alphaTexture) { effect.setTexture("diffuseSampler", alphaTexture); effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); } } BindBonesParameters(renderingMesh, effect); BindMorphTargetParameters(renderingMesh, effect); if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { renderingMesh.morphTargetManager._bind(effect); } const bvaManager = subMesh.getMesh().bakedVertexAnimationManager; if (bvaManager && bvaManager.isEnabled) { bvaManager.bind(effect, hardwareInstancedRendering); } } if (hardwareInstancedRendering && renderingMesh.hasThinInstances) { effect.setMatrix("world", effectiveMesh.getWorldMatrix()); } renderingMesh._processRendering(effectiveMesh, subMesh, effect, Material.TriangleFillMode, batch, hardwareInstancedRendering, (isInstance, world) => { if (!isInstance) { effect.setMatrix("world", world); } }); } }, "renderSubMesh"); let savedSceneClearColor; const sceneClearColor = new Color4(0, 0, 0, 1); this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(() => { savedSceneClearColor = scene.clearColor; scene.clearColor = sceneClearColor; }); this._volumetricLightScatteringRTT.onAfterRenderObservable.add(() => { scene.clearColor = savedSceneClearColor; }); this._volumetricLightScatteringRTT.customIsReadyFunction = (mesh, refreshRate, preWarm) => { if ((preWarm || refreshRate === 0) && mesh.subMeshes) { for (let i = 0; i < mesh.subMeshes.length; ++i) { const subMesh = mesh.subMeshes[i]; const material = subMesh.getMaterial(); const renderingMesh = subMesh.getRenderingMesh(); if (!material) { continue; } const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances); if (!this._isReady(subMesh, hardwareInstancedRendering)) { return false; } } } return true; }; this._volumetricLightScatteringRTT.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => { const engine2 = scene.getEngine(); let index; if (depthOnlySubMeshes.length) { engine2.setColorWrite(false); for (index = 0; index < depthOnlySubMeshes.length; index++) { renderSubMesh(depthOnlySubMeshes.data[index]); } engine2.setColorWrite(true); } for (index = 0; index < opaqueSubMeshes.length; index++) { renderSubMesh(opaqueSubMeshes.data[index]); } for (index = 0; index < alphaTestSubMeshes.length; index++) { renderSubMesh(alphaTestSubMeshes.data[index]); } if (transparentSubMeshes.length) { for (index = 0; index < transparentSubMeshes.length; index++) { const submesh = transparentSubMeshes.data[index]; const boundingInfo = submesh.getBoundingInfo(); if (boundingInfo && scene.activeCamera) { submesh._alphaIndex = submesh.getMesh().alphaIndex; submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length(); } } const sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length); sortedArray.sort((a, b) => { if (a._alphaIndex > b._alphaIndex) { return 1; } if (a._alphaIndex < b._alphaIndex) { return -1; } if (a._distanceToCamera < b._distanceToCamera) { return 1; } if (a._distanceToCamera > b._distanceToCamera) { return -1; } return 0; }); engine2.setAlphaMode(2); for (index = 0; index < sortedArray.length; index++) { renderSubMesh(sortedArray[index]); } engine2.setAlphaMode(0); } }; } _updateMeshScreenCoordinates(scene) { const transform = scene.getTransformMatrix(); let meshPosition; if (this.useCustomMeshPosition) { meshPosition = this.customMeshPosition; } else if (this.attachedNode) { meshPosition = this.attachedNode.position; } else { meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position; } const pos = Vector3.Project(meshPosition, Matrix.Identity(), transform, this._viewPort); this._screenCoordinates.x = pos.x / this._viewPort.width; this._screenCoordinates.y = pos.y / this._viewPort.height; if (this.invert) { this._screenCoordinates.y = 1 - this._screenCoordinates.y; } } // Static methods /** * Creates a default mesh for the Volumeric Light Scattering post-process * @param name The mesh name * @param scene The scene where to create the mesh * @returns the default mesh */ static CreateDefaultMesh(name260, scene) { const mesh = CreatePlane(name260, { size: 1 }, scene); mesh.billboardMode = AbstractMesh.BILLBOARDMODE_ALL; const material = new StandardMaterial(name260 + "Material", scene); material.emissiveColor = new Color3(1, 1, 1); mesh.material = material; return mesh; } }; __decorate([ serializeAsVector3() ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0); __decorate([ serialize() ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0); __decorate([ serialize() ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0); __decorate([ serializeAsMeshReference() ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0); __decorate([ serialize() ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0); __decorate([ serialize() ], VolumetricLightScatteringPostProcess.prototype, "includedMeshes", void 0); __decorate([ serialize() ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0); __decorate([ serialize() ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0); __decorate([ serialize() ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0); __decorate([ serialize() ], VolumetricLightScatteringPostProcess.prototype, "density", void 0); RegisterClass("BABYLON.VolumetricLightScatteringPostProcess", VolumetricLightScatteringPostProcess); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/rendering/vls.js init_math_vector(); init_texture(); var vlsPostProcess = null; var vlsPostProcessCameraConfigurations = /* @__PURE__ */ new Map(); function getVLSPostProcess() { return vlsPostProcess; } __name(getVLSPostProcess, "getVLSPostProcess"); function setVLSPostProcessRef(postProcess) { vlsPostProcess = postProcess; } __name(setVLSPostProcessRef, "setVLSPostProcessRef"); function disposeVLSPostProcess(scene) { if (vlsPostProcess && scene.activeCamera) { vlsPostProcess.dispose(scene.activeCamera); vlsPostProcess = null; } } __name(disposeVLSPostProcess, "disposeVLSPostProcess"); function createVLSPostProcess(scene, mesh) { mesh ??= scene.meshes.find((mesh2) => isMesh(mesh2)); vlsPostProcess = new VolumetricLightScatteringPostProcess("VolumetricLightScatteringPostProcess", 1, scene.activeCamera, mesh, 100, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false); return vlsPostProcess; } __name(createVLSPostProcess, "createVLSPostProcess"); function serializeVLSPostProcess() { if (!vlsPostProcess) { return null; } return { meshId: vlsPostProcess.mesh?.id, exposure: vlsPostProcess.exposure, decay: vlsPostProcess.decay, weight: vlsPostProcess.weight, density: vlsPostProcess.density, invert: vlsPostProcess.invert, useCustomMeshPosition: vlsPostProcess.useCustomMeshPosition, customMeshPosition: vlsPostProcess.customMeshPosition.asArray() }; } __name(serializeVLSPostProcess, "serializeVLSPostProcess"); function parseVLSPostProcess(scene, data) { let mesh = null; if (data.meshId) { const result = scene.getMeshById(data.meshId); if (result && isMesh(result)) { mesh = result; } } const vlsPostProcess2 = createVLSPostProcess(scene, mesh); vlsPostProcess2.exposure = data.exposure; vlsPostProcess2.decay = data.decay; vlsPostProcess2.weight = data.weight; vlsPostProcess2.density = data.density; vlsPostProcess2.invert = data.invert; vlsPostProcess2.useCustomMeshPosition = data.useCustomMeshPosition; vlsPostProcess2.customMeshPosition.copyFrom(Vector3.FromArray(data.customMeshPosition)); return vlsPostProcess2; } __name(parseVLSPostProcess, "parseVLSPostProcess"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderPipeline.js init_tslib_es6(); init_tools(); init_decorators(); init_uniqueIdGenerator(); var PostProcessRenderPipeline = class { static { __name(this, "PostProcessRenderPipeline"); } /** * Gets pipeline name */ get name() { return this._name; } /** Gets the list of attached cameras */ get cameras() { return this._cameras; } /** * Gets the active engine */ get engine() { return this._engine; } /** * Initializes a PostProcessRenderPipeline * @param _engine engine to add the pipeline to * @param name name of the pipeline */ constructor(_engine, name260) { this._engine = _engine; this.uniqueId = UniqueIdGenerator.UniqueId; this._name = name260; this._renderEffects = {}; this._renderEffectsForIsolatedPass = new Array(); this._cameras = []; } /** * Gets the class name * @returns "PostProcessRenderPipeline" */ getClassName() { return "PostProcessRenderPipeline"; } /** * If all the render effects in the pipeline are supported */ get isSupported() { for (const renderEffectName in this._renderEffects) { if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) { if (!this._renderEffects[renderEffectName].isSupported) { return false; } } } return true; } /** * Adds an effect to the pipeline * @param renderEffect the effect to add */ addEffect(renderEffect) { this._renderEffects[renderEffect._name] = renderEffect; } // private /** @internal */ _rebuild() { } /** * @internal */ _enableEffect(renderEffectName, cameras) { const renderEffects = this._renderEffects[renderEffectName]; if (!renderEffects) { return; } renderEffects._enable(Tools.MakeArray(cameras || this._cameras)); } /** * @internal */ _disableEffect(renderEffectName, cameras) { const renderEffects = this._renderEffects[renderEffectName]; if (!renderEffects) { return; } renderEffects._disable(Tools.MakeArray(cameras || this._cameras)); } /** * @internal */ _attachCameras(cameras, unique) { const cams = Tools.MakeArray(cameras || this._cameras); if (!cams) { return; } const indicesToDelete = []; let i; for (i = 0; i < cams.length; i++) { const camera = cams[i]; if (!camera) { continue; } if (this._cameras.indexOf(camera) === -1) { this._cameras.push(camera); } else if (unique) { indicesToDelete.push(i); } } for (i = 0; i < indicesToDelete.length; i++) { cams.splice(indicesToDelete[i], 1); } for (const renderEffectName in this._renderEffects) { if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) { this._renderEffects[renderEffectName]._attachCameras(cams); } } } /** * @internal */ _detachCameras(cameras) { const cams = Tools.MakeArray(cameras || this._cameras); if (!cams) { return; } for (const renderEffectName in this._renderEffects) { if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) { this._renderEffects[renderEffectName]._detachCameras(cams); } } for (let i = 0; i < cams.length; i++) { this._cameras.splice(this._cameras.indexOf(cams[i]), 1); } } /** @internal */ _update() { for (const renderEffectName in this._renderEffects) { if (Object.prototype.hasOwnProperty.call(this._renderEffects, renderEffectName)) { this._renderEffects[renderEffectName]._update(); } } for (let i = 0; i < this._cameras.length; i++) { if (!this._cameras[i]) { continue; } const cameraName = this._cameras[i].name; if (this._renderEffectsForIsolatedPass[cameraName]) { this._renderEffectsForIsolatedPass[cameraName]._update(); } } } /** @internal */ _reset() { this._renderEffects = {}; this._renderEffectsForIsolatedPass = new Array(); } _enableMSAAOnFirstPostProcess(sampleCount) { if (!this._engine._features.supportMSAA) { return false; } const effectKeys = Object.keys(this._renderEffects); if (effectKeys.length > 0) { const postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses(); if (postProcesses) { postProcesses[0].samples = sampleCount; } } return true; } /** * Ensures that all post processes in the pipeline are the correct size according to the * the viewport's required size */ _adaptPostProcessesToViewPort() { const effectKeys = Object.keys(this._renderEffects); for (const effectKey of effectKeys) { const postProcesses = this._renderEffects[effectKey].getPostProcesses(); if (postProcesses) { for (const postProcess of postProcesses) { postProcess.adaptScaleToCurrentViewport = true; } } } } /** * Sets the required values to the prepass renderer. * @param prePassRenderer defines the prepass renderer to setup. * @returns true if the pre pass is needed. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars setPrePassRenderer(prePassRenderer) { return false; } /** * Disposes of the pipeline */ dispose() { } }; __decorate([ serialize() ], PostProcessRenderPipeline.prototype, "_name", void 0); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderEffect.js init_tools(); var PostProcessRenderEffect = class { static { __name(this, "PostProcessRenderEffect"); } /** * Instantiates a post process render effect. * A post process can be used to apply a shader to a texture after it is rendered. * @param engine The engine the effect is tied to * @param name The name of the effect * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run. * @param singleInstance False if this post process can be run on multiple cameras. (default: true) */ constructor(engine, name260, getPostProcesses, singleInstance = true) { this._name = name260; this._singleInstance = singleInstance; this._getPostProcesses = getPostProcesses; this._cameras = {}; this._indicesForCamera = {}; this._postProcesses = {}; } /** * Checks if all the post processes in the effect are supported. */ get isSupported() { for (const index in this._postProcesses) { if (Object.prototype.hasOwnProperty.call(this._postProcesses, index)) { const pps = this._postProcesses[index]; for (let ppIndex = 0; ppIndex < pps.length; ppIndex++) { if (!pps[ppIndex].isSupported) { return false; } } } } return true; } /** * Updates the current state of the effect * @internal */ _update() { } /** * Attaches the effect on cameras * @param cameras The camera to attach to. * @internal */ _attachCameras(cameras) { let cameraKey; const cams = Tools.MakeArray(cameras || this._cameras); if (!cams) { return; } for (let i = 0; i < cams.length; i++) { const camera = cams[i]; if (!camera) { continue; } const cameraName = camera.name; if (this._singleInstance) { cameraKey = 0; } else { cameraKey = cameraName; } if (!this._postProcesses[cameraKey]) { const postProcess = this._getPostProcesses(); if (postProcess) { this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess]; } } if (!this._indicesForCamera[cameraName]) { this._indicesForCamera[cameraName] = []; } const pps = this._postProcesses[cameraKey]; for (const postProcess of pps) { const index = camera.attachPostProcess(postProcess); this._indicesForCamera[cameraName].push(index); } if (!this._cameras[cameraName]) { this._cameras[cameraName] = camera; } } } /** * Detaches the effect on cameras * @param cameras The camera to detach from. * @internal */ _detachCameras(cameras) { const cams = Tools.MakeArray(cameras || this._cameras); if (!cams) { return; } for (let i = 0; i < cams.length; i++) { const camera = cams[i]; const cameraName = camera.name; const postProcesses = this._postProcesses[this._singleInstance ? 0 : cameraName]; if (postProcesses) { for (const postProcess of postProcesses) { camera.detachPostProcess(postProcess); } } if (this._cameras[cameraName]) { this._cameras[cameraName] = null; } delete this._indicesForCamera[cameraName]; } } /** * Enables the effect on given cameras * @param cameras The camera to enable. * @internal */ _enable(cameras) { const cams = Tools.MakeArray(cameras || this._cameras); if (!cams) { return; } for (let i = 0; i < cams.length; i++) { const camera = cams[i]; const cameraName = camera.name; const cameraKey = this._singleInstance ? 0 : cameraName; for (let j = 0; j < this._indicesForCamera[cameraName].length; j++) { const index = this._indicesForCamera[cameraName][j]; const postProcess = camera._postProcesses[index]; if (postProcess === void 0 || postProcess === null) { cams[i].attachPostProcess(this._postProcesses[cameraKey][j], index); } } } } /** * Disables the effect on the given cameras * @param cameras The camera to disable. * @internal */ _disable(cameras) { const cams = Tools.MakeArray(cameras || this._cameras); if (!cams) { return; } for (let i = 0; i < cams.length; i++) { const camera = cams[i]; const cameraName = camera.name; const pps = this._postProcesses[this._singleInstance ? 0 : cameraName]; for (const postProcess of pps) { camera.detachPostProcess(postProcess); } } } /** * Gets a list of the post processes contained in the effect. * @param camera The camera to get the post processes on. * @returns The list of the post processes in the effect. */ getPostProcesses(camera) { if (this._singleInstance) { return this._postProcesses[0]; } else { if (!camera) { return null; } return this._postProcesses[camera.name]; } } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/screenSpaceReflections2Configuration.js var ScreenSpaceReflections2Configuration = class { static { __name(this, "ScreenSpaceReflections2Configuration"); } /** * @param useScreenspaceDepth If the effect should use the screenspace depth texture instead of a linear one */ constructor(useScreenspaceDepth = false) { this.enabled = false; this.name = "screenSpaceReflections2"; this.texturesRequired = [6, 3]; this.texturesRequired.push(useScreenspaceDepth ? 10 : 5); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.multiRender.js init_internalTexture(); init_logger(); init_thinEngine(); ThinEngine.prototype.restoreSingleAttachment = function() { const gl = this._gl; this.bindAttachments([gl.BACK]); }; ThinEngine.prototype.restoreSingleAttachmentForRenderTarget = function() { const gl = this._gl; this.bindAttachments([gl.COLOR_ATTACHMENT0]); }; ThinEngine.prototype.buildTextureLayout = function(textureStatus, backBufferLayout = false) { const gl = this._gl; const result = []; if (backBufferLayout) { result.push(gl.BACK); } else { for (let i = 0; i < textureStatus.length; i++) { if (textureStatus[i]) { result.push(gl["COLOR_ATTACHMENT" + i]); } else { result.push(gl.NONE); } } } return result; }; ThinEngine.prototype.bindAttachments = function(attachments) { const gl = this._gl; gl.drawBuffers(attachments); }; ThinEngine.prototype.unBindMultiColorAttachmentFramebuffer = function(rtWrapper, disableGenerateMipMaps = false, onBeforeUnbind) { this._currentRenderTarget = null; if (!rtWrapper.disableAutomaticMSAAResolve) { this.resolveMultiFramebuffer(rtWrapper); } if (!disableGenerateMipMaps) { this.generateMipMapsMultiFramebuffer(rtWrapper); } if (onBeforeUnbind) { if (rtWrapper._MSAAFramebuffer) { this._bindUnboundFramebuffer(rtWrapper._framebuffer); } onBeforeUnbind(); } this._bindUnboundFramebuffer(null); }; ThinEngine.prototype.createMultipleRenderTarget = function(size, options, initializeBuffers = true) { let generateMipMaps = false; let generateDepthBuffer = true; let generateStencilBuffer = false; let generateDepthTexture = false; let depthTextureFormat = void 0; let textureCount = 1; let samples = 1; const defaultType = 0; const defaultSamplingMode = 3; const defaultUseSRGBBuffer = false; const defaultFormat = 5; const defaultTarget = 3553; let types = []; let samplingModes = []; let useSRGBBuffers = []; let formats = []; let targets = []; let faceIndex = []; let layerIndex = []; let layers = []; let labels = []; let dontCreateTextures = false; const rtWrapper = this._createHardwareRenderTargetWrapper(true, false, size); if (options !== void 0) { generateMipMaps = options.generateMipMaps === void 0 ? false : options.generateMipMaps; generateDepthBuffer = options.generateDepthBuffer === void 0 ? true : options.generateDepthBuffer; generateStencilBuffer = options.generateStencilBuffer === void 0 ? false : options.generateStencilBuffer; generateDepthTexture = options.generateDepthTexture === void 0 ? false : options.generateDepthTexture; textureCount = options.textureCount ?? 1; samples = options.samples ?? samples; types = options.types || types; samplingModes = options.samplingModes || samplingModes; useSRGBBuffers = options.useSRGBBuffers || useSRGBBuffers; formats = options.formats || formats; targets = options.targetTypes || targets; faceIndex = options.faceIndex || faceIndex; layerIndex = options.layerIndex || layerIndex; layers = options.layerCounts || layers; labels = options.labels || labels; dontCreateTextures = options.dontCreateTextures ?? false; if (this.webGLVersion > 1 && (options.depthTextureFormat === 13 || options.depthTextureFormat === 17 || options.depthTextureFormat === 16 || options.depthTextureFormat === 14 || options.depthTextureFormat === 18)) { depthTextureFormat = options.depthTextureFormat; } } if (depthTextureFormat === void 0) { depthTextureFormat = generateStencilBuffer ? 13 : 14; } const gl = this._gl; const currentFramebuffer = this._currentFramebuffer; const framebuffer = gl.createFramebuffer(); this._bindUnboundFramebuffer(framebuffer); const width = size.width ?? size; const height = size.height ?? size; const textures = []; const attachments = []; const useStencilTexture = this.webGLVersion > 1 && (depthTextureFormat === 13 || depthTextureFormat === 17 || depthTextureFormat === 18); rtWrapper.label = options?.label ?? "MultiRenderTargetWrapper"; rtWrapper._framebuffer = framebuffer; rtWrapper._generateDepthBuffer = generateDepthTexture || generateDepthBuffer; rtWrapper._generateStencilBuffer = generateDepthTexture ? useStencilTexture : generateStencilBuffer; rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, width, height, 1, depthTextureFormat); rtWrapper._attachments = attachments; for (let i = 0; i < textureCount; i++) { let samplingMode = samplingModes[i] || defaultSamplingMode; let type = types[i] || defaultType; let useSRGBBuffer = useSRGBBuffers[i] || defaultUseSRGBBuffer; const format = formats[i] || defaultFormat; const target = targets[i] || defaultTarget; const layerCount = layers[i] ?? 1; if (type === 1 && !this._caps.textureFloatLinearFiltering) { samplingMode = 1; } else if (type === 2 && !this._caps.textureHalfFloatLinearFiltering) { samplingMode = 1; } const filters = this._getSamplingParameters(samplingMode, generateMipMaps); if (type === 1 && !this._caps.textureFloat) { type = 0; Logger.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type"); } useSRGBBuffer = useSRGBBuffer && this._caps.supportSRGBBuffers && (this.webGLVersion > 1 || this.isWebGPU); const isWebGL2 = this.webGLVersion > 1; const attachment = gl[isWebGL2 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; attachments.push(attachment); if (target === -1 || dontCreateTextures) { continue; } const texture = new InternalTexture( this, 6 /* InternalTextureSource.MultiRenderTarget */ ); textures[i] = texture; gl.activeTexture(gl["TEXTURE" + i]); gl.bindTexture(target, texture._hardwareTexture.underlyingResource); 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); const internalSizedFormat = this._getRGBABufferInternalSizedFormat(type, format, useSRGBBuffer); const internalFormat = this._getInternalFormat(format); const webGLTextureType = this._getWebGLTextureType(type); if (isWebGL2 && (target === 35866 || target === 32879)) { if (target === 35866) { texture.is2DArray = true; } else { texture.is3D = true; } texture.baseDepth = texture.depth = layerCount; gl.texImage3D(target, 0, internalSizedFormat, width, height, layerCount, 0, internalFormat, webGLTextureType, null); } else if (target === 34067) { for (let i2 = 0; i2 < 6; i2++) { gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i2, 0, internalSizedFormat, width, height, 0, internalFormat, webGLTextureType, null); } texture.isCube = true; } else { gl.texImage2D(gl.TEXTURE_2D, 0, internalSizedFormat, width, height, 0, internalFormat, webGLTextureType, null); } if (generateMipMaps) { gl.generateMipmap(target); } this._bindTextureDirectly(target, null); 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._useSRGBBuffer = useSRGBBuffer; texture.format = format; texture.label = labels[i] ?? rtWrapper.label + "-Texture" + i; this._internalTexturesCache.push(texture); } if (generateDepthTexture && this._caps.depthTextureExtension && !dontCreateTextures) { const depthTexture = new InternalTexture( this, 14 /* InternalTextureSource.Depth */ ); let depthTextureType = 5; let glDepthTextureInternalFormat = gl.DEPTH_COMPONENT16; let glDepthTextureFormat = gl.DEPTH_COMPONENT; let glDepthTextureType = gl.UNSIGNED_SHORT; let glDepthTextureAttachment = gl.DEPTH_ATTACHMENT; if (this.webGLVersion < 2) { glDepthTextureInternalFormat = gl.DEPTH_COMPONENT; } else { if (depthTextureFormat === 14) { depthTextureType = 1; glDepthTextureType = gl.FLOAT; glDepthTextureInternalFormat = gl.DEPTH_COMPONENT32F; } else if (depthTextureFormat === 18) { depthTextureType = 0; glDepthTextureType = gl.FLOAT_32_UNSIGNED_INT_24_8_REV; glDepthTextureInternalFormat = gl.DEPTH32F_STENCIL8; glDepthTextureFormat = gl.DEPTH_STENCIL; glDepthTextureAttachment = gl.DEPTH_STENCIL_ATTACHMENT; } else if (depthTextureFormat === 16) { depthTextureType = 0; glDepthTextureType = gl.UNSIGNED_INT; glDepthTextureInternalFormat = gl.DEPTH_COMPONENT24; glDepthTextureAttachment = gl.DEPTH_ATTACHMENT; } else if (depthTextureFormat === 13 || depthTextureFormat === 17) { depthTextureType = 12; glDepthTextureType = gl.UNSIGNED_INT_24_8; glDepthTextureInternalFormat = gl.DEPTH24_STENCIL8; glDepthTextureFormat = gl.DEPTH_STENCIL; glDepthTextureAttachment = gl.DEPTH_STENCIL_ATTACHMENT; } } this._bindTextureDirectly(gl.TEXTURE_2D, depthTexture, true); 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, glDepthTextureInternalFormat, width, height, 0, glDepthTextureFormat, glDepthTextureType, null); gl.framebufferTexture2D(gl.FRAMEBUFFER, glDepthTextureAttachment, gl.TEXTURE_2D, depthTexture._hardwareTexture.underlyingResource, 0); this._bindTextureDirectly(gl.TEXTURE_2D, null); rtWrapper._depthStencilTexture = depthTexture; rtWrapper._depthStencilTextureWithStencil = useStencilTexture; depthTexture.baseWidth = width; depthTexture.baseHeight = height; depthTexture.width = width; depthTexture.height = height; depthTexture.isReady = true; depthTexture.samples = 1; depthTexture.generateMipMaps = generateMipMaps; depthTexture.samplingMode = 1; depthTexture.format = depthTextureFormat; depthTexture.type = depthTextureType; depthTexture.label = rtWrapper.label + "-DepthStencil"; textures[textureCount] = depthTexture; this._internalTexturesCache.push(depthTexture); } rtWrapper.setTextures(textures); if (initializeBuffers) { gl.drawBuffers(attachments); } this._bindUnboundFramebuffer(currentFramebuffer); rtWrapper.setLayerAndFaceIndices(layerIndex, faceIndex); this.resetTextureCache(); if (!dontCreateTextures) { this.updateMultipleRenderTargetTextureSampleCount(rtWrapper, samples, initializeBuffers); } else if (samples > 1) { const framebuffer2 = gl.createFramebuffer(); if (!framebuffer2) { throw new Error("Unable to create multi sampled framebuffer"); } rtWrapper._samples = samples; rtWrapper._MSAAFramebuffer = framebuffer2; if (textureCount > 0 && initializeBuffers) { this._bindUnboundFramebuffer(framebuffer2); gl.drawBuffers(attachments); this._bindUnboundFramebuffer(currentFramebuffer); } } return rtWrapper; }; ThinEngine.prototype.updateMultipleRenderTargetTextureSampleCount = function(rtWrapper, samples, initializeBuffers = true) { if (this.webGLVersion < 2 || !rtWrapper) { return 1; } if (rtWrapper.samples === samples) { return samples; } const gl = this._gl; samples = Math.min(samples, this.getCaps().maxMSAASamples); if (rtWrapper._depthStencilBuffer) { gl.deleteRenderbuffer(rtWrapper._depthStencilBuffer); rtWrapper._depthStencilBuffer = null; } if (rtWrapper._MSAAFramebuffer) { gl.deleteFramebuffer(rtWrapper._MSAAFramebuffer); rtWrapper._MSAAFramebuffer = null; } const count = rtWrapper._attachments.length; for (let i = 0; i < count; i++) { const texture = rtWrapper.textures[i]; const hardwareTexture = texture._hardwareTexture; hardwareTexture?.releaseMSAARenderBuffers(); } if (samples > 1 && typeof gl.renderbufferStorageMultisample === "function") { const framebuffer = gl.createFramebuffer(); if (!framebuffer) { throw new Error("Unable to create multi sampled framebuffer"); } rtWrapper._MSAAFramebuffer = framebuffer; this._bindUnboundFramebuffer(framebuffer); const attachments = []; for (let i = 0; i < count; i++) { const texture = rtWrapper.textures[i]; const hardwareTexture = texture._hardwareTexture; const attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; const colorRenderbuffer = this._createRenderBuffer(texture.width, texture.height, samples, -1, this._getRGBABufferInternalSizedFormat(texture.type, texture.format, texture._useSRGBBuffer), attachment); if (!colorRenderbuffer) { throw new Error("Unable to create multi sampled framebuffer"); } hardwareTexture.addMSAARenderBuffer(colorRenderbuffer); texture.samples = samples; attachments.push(attachment); } if (initializeBuffers) { gl.drawBuffers(attachments); } } else { this._bindUnboundFramebuffer(rtWrapper._framebuffer); } const depthFormat = rtWrapper._depthStencilTexture ? rtWrapper._depthStencilTexture.format : void 0; rtWrapper._depthStencilBuffer = this._setupFramebufferDepthAttachments(rtWrapper._generateStencilBuffer, rtWrapper._generateDepthBuffer, rtWrapper.width, rtWrapper.height, samples, depthFormat); this._bindUnboundFramebuffer(null); rtWrapper._samples = samples; return samples; }; ThinEngine.prototype.generateMipMapsMultiFramebuffer = function(texture) { const rtWrapper = texture; const gl = this._gl; if (!rtWrapper.isMulti) { return; } for (let i = 0; i < rtWrapper._attachments.length; i++) { const texture2 = rtWrapper.textures[i]; if (texture2?.generateMipMaps && !texture2?.isCube && !texture2?.is3D) { this._bindTextureDirectly(gl.TEXTURE_2D, texture2, true); gl.generateMipmap(gl.TEXTURE_2D); this._bindTextureDirectly(gl.TEXTURE_2D, null); } } }; ThinEngine.prototype.resolveMultiFramebuffer = function(texture) { const rtWrapper = texture; const gl = this._gl; if (!rtWrapper._MSAAFramebuffer || !rtWrapper.isMulti) { return; } let bufferBits = rtWrapper.resolveMSAAColors ? gl.COLOR_BUFFER_BIT : 0; bufferBits |= rtWrapper._generateDepthBuffer && rtWrapper.resolveMSAADepth ? gl.DEPTH_BUFFER_BIT : 0; bufferBits |= rtWrapper._generateStencilBuffer && rtWrapper.resolveMSAAStencil ? gl.STENCIL_BUFFER_BIT : 0; const attachments = rtWrapper._attachments; const count = attachments.length; gl.bindFramebuffer(gl.READ_FRAMEBUFFER, rtWrapper._MSAAFramebuffer); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, rtWrapper._framebuffer); for (let i = 0; i < count; i++) { const texture2 = rtWrapper.textures[i]; for (let 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, texture2.width, texture2.height, 0, 0, texture2.width, texture2.height, bufferBits, gl.NEAREST); } for (let i = 0; i < count; i++) { attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"]; } gl.drawBuffers(attachments); gl.bindFramebuffer(this._gl.FRAMEBUFFER, rtWrapper._MSAAFramebuffer); }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/multiRenderTarget.js init_texture(); init_renderTargetTexture(); var MultiRenderTarget = class extends RenderTargetTexture { static { __name(this, "MultiRenderTarget"); } /** * Get if draw buffers (render textures) are currently supported by the used hardware and browser. */ get isSupported() { return this._engine?.getCaps().drawBuffersExtension ?? false; } /** * Get the list of textures generated by the multi render target. */ get textures() { return this._textures; } /** * Gets the number of textures in this MRT. This number can be different from `_textures.length` in case a depth texture is generated. */ get count() { return this._count; } /** * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set */ get depthTexture() { return this._textures[this._textures.length - 1]; } /** * Set the wrapping mode on U of all the textures we are rendering to. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE) */ set wrapU(wrap) { if (this._textures) { for (let i = 0; i < this._textures.length; i++) { this._textures[i].wrapU = wrap; } } } /** * Set the wrapping mode on V of all the textures we are rendering to. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE) */ set wrapV(wrap) { if (this._textures) { for (let i = 0; i < this._textures.length; i++) { this._textures[i].wrapV = wrap; } } } /** * Instantiate a new multi render target texture. * A multi render target, like a render target provides the ability to render to a texture. * Unlike the render target, it can render to several draw buffers (render textures) in one draw. * This is specially interesting in deferred rendering or for any effects requiring more than * just one color from a single pass. * @param name Define the name of the texture * @param size Define the size of the buffers to render to * @param count Define the number of target we are rendering into * @param scene Define the scene the texture belongs to * @param options Define the options used to create the multi render target * @param textureNames Define the names to set to the textures (if count \> 0 - optional) */ constructor(name260, size, count, scene, options, textureNames) { const generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false; const generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false; const depthTextureFormat = options && options.depthTextureFormat ? options.depthTextureFormat : 15; const doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === void 0 ? true : options.doNotChangeAspectRatio; const drawOnlyOnFirstAttachmentByDefault = options && options.drawOnlyOnFirstAttachmentByDefault ? options.drawOnlyOnFirstAttachmentByDefault : false; super(name260, size, scene, generateMipMaps, doNotChangeAspectRatio, void 0, void 0, void 0, void 0, void 0, void 0, void 0, true); if (!this.isSupported) { this.dispose(); return; } this._textureNames = textureNames; const types = []; const samplingModes = []; const useSRGBBuffers = []; const formats = []; const targetTypes = []; const faceIndex = []; const layerIndex = []; const layerCounts = []; this._initTypes(count, types, samplingModes, useSRGBBuffers, formats, targetTypes, faceIndex, layerIndex, layerCounts, options); const generateDepthBuffer = !options || options.generateDepthBuffer === void 0 ? true : options.generateDepthBuffer; const generateStencilBuffer = !options || options.generateStencilBuffer === void 0 ? false : options.generateStencilBuffer; const samples = options && options.samples ? options.samples : 1; this._multiRenderTargetOptions = { samplingModes, generateMipMaps, generateDepthBuffer, generateStencilBuffer, generateDepthTexture, depthTextureFormat, types, textureCount: count, useSRGBBuffers, samples, formats, targetTypes, faceIndex, layerIndex, layerCounts, labels: textureNames, label: name260 }; this._count = count; this._drawOnlyOnFirstAttachmentByDefault = drawOnlyOnFirstAttachmentByDefault; if (count > 0) { this._createInternalTextures(); this._createTextures(textureNames); } } _initTypes(count, types, samplingModes, useSRGBBuffers, formats, targets, faceIndex, layerIndex, layerCounts, options) { for (let i = 0; i < count; i++) { if (options && options.types && options.types[i] !== void 0) { types.push(options.types[i]); } else { types.push(options && options.defaultType ? options.defaultType : 0); } if (options && options.samplingModes && options.samplingModes[i] !== void 0) { samplingModes.push(options.samplingModes[i]); } else { samplingModes.push(Texture.BILINEAR_SAMPLINGMODE); } if (options && options.useSRGBBuffers && options.useSRGBBuffers[i] !== void 0) { useSRGBBuffers.push(options.useSRGBBuffers[i]); } else { useSRGBBuffers.push(false); } if (options && options.formats && options.formats[i] !== void 0) { formats.push(options.formats[i]); } else { formats.push(5); } if (options && options.targetTypes && options.targetTypes[i] !== void 0) { targets.push(options.targetTypes[i]); } else { targets.push(3553); } if (options && options.faceIndex && options.faceIndex[i] !== void 0) { faceIndex.push(options.faceIndex[i]); } else { faceIndex.push(0); } if (options && options.layerIndex && options.layerIndex[i] !== void 0) { layerIndex.push(options.layerIndex[i]); } else { layerIndex.push(0); } if (options && options.layerCounts && options.layerCounts[i] !== void 0) { layerCounts.push(options.layerCounts[i]); } else { layerCounts.push(1); } } } _createInternaTextureIndexMapping() { const mapMainInternalTexture2Index = {}; const mapInternalTexture2MainIndex = []; if (!this._renderTarget) { return mapInternalTexture2MainIndex; } const internalTextures = this._renderTarget.textures; for (let i = 0; i < internalTextures.length; i++) { const texture = internalTextures[i]; if (!texture) { continue; } const mainIndex = mapMainInternalTexture2Index[texture.uniqueId]; if (mainIndex !== void 0) { mapInternalTexture2MainIndex[i] = mainIndex; } else { mapMainInternalTexture2Index[texture.uniqueId] = i; } } return mapInternalTexture2MainIndex; } /** * @internal */ _rebuild(fromContextLost = false, forceFullRebuild = false, textureNames) { if (this._count < 1 || fromContextLost) { return; } const mapInternalTexture2MainIndex = this._createInternaTextureIndexMapping(); this.releaseInternalTextures(); this._createInternalTextures(); if (forceFullRebuild) { this._releaseTextures(); this._createTextures(textureNames); } const internalTextures = this._renderTarget.textures; for (let i = 0; i < internalTextures.length; i++) { const texture = this._textures[i]; if (mapInternalTexture2MainIndex[i] !== void 0) { this._renderTarget.setTexture(internalTextures[mapInternalTexture2MainIndex[i]], i); } texture._texture = internalTextures[i]; if (texture._texture) { texture._noMipmap = !texture._texture.useMipMaps; texture._useSRGBBuffer = texture._texture._useSRGBBuffer; } } if (this.samples !== 1) { this._renderTarget.setSamples(this.samples, !this._drawOnlyOnFirstAttachmentByDefault, true); } } _createInternalTextures() { this._renderTarget = this._getEngine().createMultipleRenderTarget(this._size, this._multiRenderTargetOptions, !this._drawOnlyOnFirstAttachmentByDefault); this._texture = this._renderTarget.texture; } _releaseTextures() { if (this._textures) { for (let i = 0; i < this._textures.length; i++) { this._textures[i]._texture = null; this._textures[i].dispose(); } } } _createTextures(textureNames) { const internalTextures = this._renderTarget.textures; this._textures = []; for (let i = 0; i < internalTextures.length; i++) { const texture = new Texture(null, this.getScene()); if (textureNames?.[i]) { texture.name = textureNames[i]; } texture._texture = internalTextures[i]; if (texture._texture) { texture._noMipmap = !texture._texture.useMipMaps; texture._useSRGBBuffer = texture._texture._useSRGBBuffer; } this._textures.push(texture); } } /** * Replaces an internal texture within the MRT. Useful to share textures between MultiRenderTarget. * @param texture The new texture to set in the MRT * @param index The index of the texture to replace * @param disposePrevious Set to true if the previous internal texture should be disposed */ setInternalTexture(texture, index, disposePrevious = true) { if (!this.renderTarget) { return; } if (index === 0) { this._texture = texture; } this.renderTarget.setTexture(texture, index, disposePrevious); if (!this.textures[index]) { this.textures[index] = new Texture(null, this.getScene()); this.textures[index].name = this._textureNames?.[index] ?? this.textures[index].name; } this.textures[index]._texture = texture; this.textures[index]._noMipmap = !texture.useMipMaps; this.textures[index]._useSRGBBuffer = texture._useSRGBBuffer; this._count = this.renderTarget.textures ? this.renderTarget.textures.length : 0; if (this._multiRenderTargetOptions.types) { this._multiRenderTargetOptions.types[index] = texture.type; } if (this._multiRenderTargetOptions.samplingModes) { this._multiRenderTargetOptions.samplingModes[index] = texture.samplingMode; } if (this._multiRenderTargetOptions.useSRGBBuffers) { this._multiRenderTargetOptions.useSRGBBuffers[index] = texture._useSRGBBuffer; } if (this._multiRenderTargetOptions.targetTypes && this._multiRenderTargetOptions.targetTypes[index] !== -1) { let target = 0; if (texture.is2DArray) { target = 35866; } else if (texture.isCube) { target = 34067; } else if (texture.is3D) { target = 32879; } else { target = 3553; } this._multiRenderTargetOptions.targetTypes[index] = target; } } /** * Changes an attached texture's face index or layer. * @param index The index of the texture to modify the attachment of * @param layerIndex The layer index of the texture to be attached to the framebuffer * @param faceIndex The face index of the texture to be attached to the framebuffer */ setLayerAndFaceIndex(index, layerIndex = -1, faceIndex = -1) { if (!this.textures[index] || !this.renderTarget) { return; } if (this._multiRenderTargetOptions.layerIndex) { this._multiRenderTargetOptions.layerIndex[index] = layerIndex; } if (this._multiRenderTargetOptions.faceIndex) { this._multiRenderTargetOptions.faceIndex[index] = faceIndex; } this.renderTarget.setLayerAndFaceIndex(index, layerIndex, faceIndex); } /** * Changes every attached texture's face index or layer. * @param layerIndices The layer indices of the texture to be attached to the framebuffer * @param faceIndices The face indices of the texture to be attached to the framebuffer */ setLayerAndFaceIndices(layerIndices, faceIndices) { if (!this.renderTarget) { return; } this._multiRenderTargetOptions.layerIndex = layerIndices; this._multiRenderTargetOptions.faceIndex = faceIndices; this.renderTarget.setLayerAndFaceIndices(layerIndices, faceIndices); } /** * Define the number of samples used if MSAA is enabled. */ get samples() { return this._samples; } set samples(value) { if (this._renderTarget) { this._samples = this._renderTarget.setSamples(value); } else { this._samples = value; } } /** * Resize all the textures in the multi render target. * Be careful as it will recreate all the data in the new texture. * @param size Define the new size */ resize(size) { this._processSizeParameter(size); this._rebuild(false, void 0, this._textureNames); } /** * Changes the number of render targets in this MRT * Be careful as it will recreate all the data in the new texture. * @param count new texture count * @param options Specifies texture types and sampling modes for new textures * @param textureNames Specifies the names of the textures (optional) */ updateCount(count, options, textureNames) { this._multiRenderTargetOptions.textureCount = count; this._count = count; const types = []; const samplingModes = []; const useSRGBBuffers = []; const formats = []; const targetTypes = []; const faceIndex = []; const layerIndex = []; const layerCounts = []; this._textureNames = textureNames; this._initTypes(count, types, samplingModes, useSRGBBuffers, formats, targetTypes, faceIndex, layerIndex, layerCounts, options); this._multiRenderTargetOptions.types = types; this._multiRenderTargetOptions.samplingModes = samplingModes; this._multiRenderTargetOptions.useSRGBBuffers = useSRGBBuffers; this._multiRenderTargetOptions.formats = formats; this._multiRenderTargetOptions.targetTypes = targetTypes; this._multiRenderTargetOptions.faceIndex = faceIndex; this._multiRenderTargetOptions.layerIndex = layerIndex; this._multiRenderTargetOptions.layerCounts = layerCounts; this._multiRenderTargetOptions.labels = textureNames; this._rebuild(false, true, textureNames); } _unbindFrameBuffer(engine, faceIndex) { if (this._renderTarget) { engine.unBindMultiColorAttachmentFramebuffer(this._renderTarget, this.isCube, () => { this.onAfterRenderObservable.notifyObservers(faceIndex); }); } } /** * Dispose the render targets and their associated resources * @param doNotDisposeInternalTextures if set to true, internal textures won't be disposed (default: false). */ dispose(doNotDisposeInternalTextures = false) { this._releaseTextures(); if (!doNotDisposeInternalTextures) { this.releaseInternalTextures(); } else { this._texture = null; } super.dispose(); } /** * Release all the underlying texture used as draw buffers (render textures). */ releaseInternalTextures() { const internalTextures = this._renderTarget?.textures; if (!internalTextures) { return; } for (let i = internalTextures.length - 1; i >= 0; i--) { this._textures[i]._texture = null; } this._renderTarget?.dispose(); this._renderTarget = null; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/geometryBufferRenderer.js init_math_vector(); init_buffer(); init_texture(); init_math_color(); init_devTools(); init_geometry_fragment2(); init_geometry_vertex2(); init_materialFlags(); init_clipPlaneMaterialHelper(); init_materialHelper_functions(); var Uniforms = [ "world", "mBones", "viewProjection", "diffuseMatrix", "view", "previousWorld", "previousViewProjection", "mPreviousBones", "bumpMatrix", "reflectivityMatrix", "albedoMatrix", "reflectivityColor", "albedoColor", "metallic", "glossiness", "vTangentSpaceParams", "vBumpInfos", "morphTargetInfluences", "morphTargetCount", "morphTargetTextureInfo", "morphTargetTextureIndices", "boneTextureWidth" ]; AddClipPlaneUniforms(Uniforms); var GeometryBufferRenderer = class _GeometryBufferRenderer { static { __name(this, "GeometryBufferRenderer"); } /** * Gets a boolean indicating if normals are encoded in the [0,1] range in the render target. If true, you should do `normal = normal_rt * 2.0 - 1.0` to get the right normal */ get normalsAreUnsigned() { return this._normalsAreUnsigned; } /** * @internal * Sets up internal structures to share outputs with PrePassRenderer * This method should only be called by the PrePassRenderer itself */ _linkPrePassRenderer(prePassRenderer) { this._linkedWithPrePass = true; this._prePassRenderer = prePassRenderer; if (this._multiRenderTarget) { this._multiRenderTarget.onClearObservable.clear(); this._multiRenderTarget.onClearObservable.add(() => { }); } } /** * @internal * Separates internal structures from PrePassRenderer so the geometry buffer can now operate by itself. * This method should only be called by the PrePassRenderer itself */ _unlinkPrePassRenderer() { this._linkedWithPrePass = false; this._createRenderTargets(); } /** * @internal * Resets the geometry buffer layout */ _resetLayout() { this._enableDepth = true; this._enableNormal = true; this._enablePosition = false; this._enableReflectivity = false; this._enableVelocity = false; this._enableVelocityLinear = false; this._enableScreenspaceDepth = false; this._attachmentsFromPrePass = []; } /** * @internal * Replaces a texture in the geometry buffer renderer * Useful when linking textures of the prepass renderer */ _forceTextureType(geometryBufferType, index) { if (geometryBufferType === _GeometryBufferRenderer.POSITION_TEXTURE_TYPE) { this._positionIndex = index; this._enablePosition = true; } else if (geometryBufferType === _GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE) { this._velocityIndex = index; this._enableVelocity = true; } else if (geometryBufferType === _GeometryBufferRenderer.VELOCITY_LINEAR_TEXTURE_TYPE) { this._velocityLinearIndex = index; this._enableVelocityLinear = true; } else if (geometryBufferType === _GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE) { this._reflectivityIndex = index; this._enableReflectivity = true; } else if (geometryBufferType === _GeometryBufferRenderer.DEPTH_TEXTURE_TYPE) { this._depthIndex = index; this._enableDepth = true; } else if (geometryBufferType === _GeometryBufferRenderer.NORMAL_TEXTURE_TYPE) { this._normalIndex = index; this._enableNormal = true; } else if (geometryBufferType === _GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE) { this._screenspaceDepthIndex = index; this._enableScreenspaceDepth = true; } } /** * @internal * Sets texture attachments * Useful when linking textures of the prepass renderer */ _setAttachments(attachments) { this._attachmentsFromPrePass = attachments; } /** * @internal * Replaces the first texture which is hard coded as a depth texture in the geometry buffer * Useful when linking textures of the prepass renderer */ _linkInternalTexture(internalTexture) { this._multiRenderTarget.setInternalTexture(internalTexture, 0, false); } /** * Gets the render list (meshes to be rendered) used in the G buffer. */ get renderList() { return this._multiRenderTarget.renderList; } /** * Set the render list (meshes to be rendered) used in the G buffer. */ set renderList(meshes) { this._multiRenderTarget.renderList = meshes; } /** * Gets whether or not G buffer are supported by the running hardware. * This requires draw buffer supports */ get isSupported() { return this._multiRenderTarget.isSupported; } /** * Returns the index of the given texture type in the G-Buffer textures array * @param textureType The texture type constant. For example GeometryBufferRenderer.POSITION_TEXTURE_INDEX * @returns the index of the given texture type in the G-Buffer textures array */ getTextureIndex(textureType) { switch (textureType) { case _GeometryBufferRenderer.POSITION_TEXTURE_TYPE: return this._positionIndex; case _GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE: return this._velocityIndex; case _GeometryBufferRenderer.VELOCITY_LINEAR_TEXTURE_TYPE: return this._velocityLinearIndex; case _GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE: return this._reflectivityIndex; case _GeometryBufferRenderer.DEPTH_TEXTURE_TYPE: return this._depthIndex; case _GeometryBufferRenderer.NORMAL_TEXTURE_TYPE: return this._normalIndex; case _GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE: return this._screenspaceDepthIndex; default: return -1; } } /** * @returns a boolean indicating if object's depths are enabled for the G buffer. */ get enableDepth() { return this._enableDepth; } /** * Sets whether or not object's depths are enabled for the G buffer. */ set enableDepth(enable) { this._enableDepth = enable; if (!this._linkedWithPrePass) { this.dispose(); this._createRenderTargets(); } } /** * @returns a boolean indicating if object's normals are enabled for the G buffer. */ get enableNormal() { return this._enableNormal; } /** * Sets whether or not object's normals are enabled for the G buffer. */ set enableNormal(enable) { this._enableNormal = enable; if (!this._linkedWithPrePass) { this.dispose(); this._createRenderTargets(); } } /** * @returns a boolean indicating if objects positions are enabled for the G buffer. */ get enablePosition() { return this._enablePosition; } /** * Sets whether or not objects positions are enabled for the G buffer. */ set enablePosition(enable) { this._enablePosition = enable; if (!this._linkedWithPrePass) { this.dispose(); this._createRenderTargets(); } } /** * @returns a boolean indicating if objects velocities are enabled for the G buffer. */ get enableVelocity() { return this._enableVelocity; } /** * Sets whether or not objects velocities are enabled for the G buffer. */ set enableVelocity(enable) { this._enableVelocity = enable; if (!enable) { this._previousTransformationMatrices = {}; } if (!this._linkedWithPrePass) { this.dispose(); this._createRenderTargets(); } this._scene.needsPreviousWorldMatrices = enable; } /** * @returns a boolean indicating if object's linear velocities are enabled for the G buffer. */ get enableVelocityLinear() { return this._enableVelocityLinear; } /** * Sets whether or not object's linear velocities are enabled for the G buffer. */ set enableVelocityLinear(enable) { this._enableVelocityLinear = enable; if (!this._linkedWithPrePass) { this.dispose(); this._createRenderTargets(); } } /** * Gets a boolean indicating if objects reflectivity are enabled in the G buffer. */ get enableReflectivity() { return this._enableReflectivity; } /** * Sets whether or not objects reflectivity are enabled for the G buffer. * For Metallic-Roughness workflow with ORM texture, we assume that ORM texture is defined according to the default layout: * pbr.useRoughnessFromMetallicTextureAlpha = false; * pbr.useRoughnessFromMetallicTextureGreen = true; * pbr.useMetallnessFromMetallicTextureBlue = true; */ set enableReflectivity(enable) { this._enableReflectivity = enable; if (!this._linkedWithPrePass) { this.dispose(); this._createRenderTargets(); } } /** * Sets whether or not objects screenspace depth are enabled for the G buffer. */ get enableScreenspaceDepth() { return this._enableScreenspaceDepth; } set enableScreenspaceDepth(enable) { this._enableScreenspaceDepth = enable; if (!this._linkedWithPrePass) { this.dispose(); this._createRenderTargets(); } } /** * Gets the scene associated with the buffer. */ get scene() { return this._scene; } /** * Gets the ratio used by the buffer during its creation. * How big is the buffer related to the main canvas. */ get ratio() { return typeof this._ratioOrDimensions === "object" ? 1 : this._ratioOrDimensions; } /** * Gets the shader language used in this material. */ get shaderLanguage() { return this._shaderLanguage; } /** * Creates a new G Buffer for the scene * @param scene The scene the buffer belongs to * @param ratioOrDimensions How big is the buffer related to the main canvas (default: 1). You can also directly pass a width and height for the generated textures * @param depthFormat Format of the depth texture (default: 15) * @param textureTypesAndFormats The types and formats of textures to create as render targets. If not provided, all textures will be RGBA and float or half float, depending on the engine capabilities. */ constructor(scene, ratioOrDimensions = 1, depthFormat = 15, textureTypesAndFormats) { this._previousTransformationMatrices = {}; this._previousBonesTransformationMatrices = {}; this.excludedSkinnedMeshesFromVelocity = []; this.renderTransparentMeshes = true; this.generateNormalsInWorldSpace = false; this._normalsAreUnsigned = false; this._resizeObserver = null; this._enableDepth = true; this._enableNormal = true; this._enablePosition = false; this._enableVelocity = false; this._enableVelocityLinear = false; this._enableReflectivity = false; this._enableScreenspaceDepth = false; this._clearColor = new Color4(0, 0, 0, 0); this._clearDepthColor = new Color4(0, 0, 0, 1); this._positionIndex = -1; this._velocityIndex = -1; this._velocityLinearIndex = -1; this._reflectivityIndex = -1; this._depthIndex = -1; this._normalIndex = -1; this._screenspaceDepthIndex = -1; this._linkedWithPrePass = false; this.useSpecificClearForDepthTexture = false; this._shaderLanguage = 0; this._shadersLoaded = false; this._scene = scene; this._ratioOrDimensions = ratioOrDimensions; this._useUbo = scene.getEngine().supportsUniformBuffers; this._depthFormat = depthFormat; this._textureTypesAndFormats = textureTypesAndFormats || {}; this._initShaderSourceAsync(); _GeometryBufferRenderer._SceneComponentInitialization(this._scene); this._createRenderTargets(); } async _initShaderSourceAsync() { const engine = this._scene.getEngine(); if (engine.isWebGPU && !_GeometryBufferRenderer.ForceGLSL) { this._shaderLanguage = 1; await Promise.all([Promise.resolve().then(() => (init_geometry_vertex(), geometry_vertex_exports)), Promise.resolve().then(() => (init_geometry_fragment(), geometry_fragment_exports))]); } else { await Promise.all([Promise.resolve().then(() => (init_geometry_vertex2(), geometry_vertex_exports2)), Promise.resolve().then(() => (init_geometry_fragment2(), geometry_fragment_exports2))]); } this._shadersLoaded = true; } /** * Checks whether everything is ready to render a submesh to the G buffer. * @param subMesh the submesh to check readiness for * @param useInstances is the mesh drawn using instance or not * @returns true if ready otherwise false */ isReady(subMesh, useInstances) { if (!this._shadersLoaded) { return false; } const material = subMesh.getMaterial(); if (material && material.disableDepthWrite) { return false; } const defines = []; const attribs = [VertexBuffer.PositionKind]; const mesh = subMesh.getMesh(); const hasNormals = mesh.isVerticesDataPresent(VertexBuffer.NormalKind); if (hasNormals) { defines.push("#define HAS_NORMAL_ATTRIBUTE"); attribs.push(VertexBuffer.NormalKind); } let uv1 = false; let uv2 = false; const color = false; if (material) { let needUv = false; if (material.needAlphaTestingForMesh(mesh) && material.getAlphaTestTexture()) { defines.push("#define ALPHATEST"); defines.push(`#define ALPHATEST_UV${material.getAlphaTestTexture().coordinatesIndex + 1}`); needUv = true; } if ((material.bumpTexture || material.normalTexture || material.geometryNormalTexture) && MaterialFlags.BumpTextureEnabled) { const texture = material.bumpTexture || material.normalTexture || material.geometryNormalTexture; defines.push("#define BUMP"); defines.push(`#define BUMP_UV${texture.coordinatesIndex + 1}`); needUv = true; } if (this._enableReflectivity) { let metallicWorkflow = false; if (material.getClassName() === "PBRMetallicRoughnessMaterial") { if (material.metallicRoughnessTexture) { defines.push("#define ORMTEXTURE"); defines.push(`#define REFLECTIVITY_UV${material.metallicRoughnessTexture.coordinatesIndex + 1}`); defines.push("#define METALLICWORKFLOW"); needUv = true; metallicWorkflow = true; } if (material.metallic != null) { defines.push("#define METALLIC"); defines.push("#define METALLICWORKFLOW"); metallicWorkflow = true; } if (material.roughness != null) { defines.push("#define ROUGHNESS"); defines.push("#define METALLICWORKFLOW"); metallicWorkflow = true; } if (metallicWorkflow) { if (material.baseTexture) { defines.push("#define ALBEDOTEXTURE"); defines.push(`#define ALBEDO_UV${material.baseTexture.coordinatesIndex + 1}`); if (material.baseTexture.gammaSpace) { defines.push("#define GAMMAALBEDO"); } needUv = true; } if (material.baseColor) { defines.push("#define ALBEDOCOLOR"); } } } else if (material.getClassName() === "PBRSpecularGlossinessMaterial") { if (material.specularGlossinessTexture) { defines.push("#define SPECULARGLOSSINESSTEXTURE"); defines.push(`#define REFLECTIVITY_UV${material.specularGlossinessTexture.coordinatesIndex + 1}`); needUv = true; if (material.specularGlossinessTexture.gammaSpace) { defines.push("#define GAMMAREFLECTIVITYTEXTURE"); } } else { if (material.specularColor) { defines.push("#define REFLECTIVITYCOLOR"); } } if (material.glossiness != null) { defines.push("#define GLOSSINESS"); } } else if (material.getClassName() === "PBRMaterial") { if (material.metallicTexture) { defines.push("#define ORMTEXTURE"); defines.push(`#define REFLECTIVITY_UV${material.metallicTexture.coordinatesIndex + 1}`); defines.push("#define METALLICWORKFLOW"); needUv = true; metallicWorkflow = true; } if (material.metallic != null) { defines.push("#define METALLIC"); defines.push("#define METALLICWORKFLOW"); metallicWorkflow = true; } if (material.roughness != null) { defines.push("#define ROUGHNESS"); defines.push("#define METALLICWORKFLOW"); metallicWorkflow = true; } if (metallicWorkflow) { if (material.albedoTexture) { defines.push("#define ALBEDOTEXTURE"); defines.push(`#define ALBEDO_UV${material.albedoTexture.coordinatesIndex + 1}`); if (material.albedoTexture.gammaSpace) { defines.push("#define GAMMAALBEDO"); } needUv = true; } if (material.albedoColor) { defines.push("#define ALBEDOCOLOR"); } } else { if (material.reflectivityTexture) { defines.push("#define SPECULARGLOSSINESSTEXTURE"); defines.push(`#define REFLECTIVITY_UV${material.reflectivityTexture.coordinatesIndex + 1}`); if (material.reflectivityTexture.gammaSpace) { defines.push("#define GAMMAREFLECTIVITYTEXTURE"); } needUv = true; } else if (material.reflectivityColor) { defines.push("#define REFLECTIVITYCOLOR"); } if (material.microSurface != null) { defines.push("#define GLOSSINESS"); } } } else if (material.getClassName() === "StandardMaterial") { if (material.specularTexture) { defines.push("#define REFLECTIVITYTEXTURE"); defines.push(`#define REFLECTIVITY_UV${material.specularTexture.coordinatesIndex + 1}`); if (material.specularTexture.gammaSpace) { defines.push("#define GAMMAREFLECTIVITYTEXTURE"); } needUv = true; } if (material.specularColor) { defines.push("#define REFLECTIVITYCOLOR"); } } else if (material.getClassName() === "OpenPBRMaterial") { const pbrMaterial = material; defines.push("#define METALLICWORKFLOW"); metallicWorkflow = true; defines.push("#define METALLIC"); defines.push("#define ROUGHNESS"); if (pbrMaterial._useRoughnessFromMetallicTextureGreen && pbrMaterial.baseMetalnessTexture) { defines.push("#define ORMTEXTURE"); defines.push(`#define REFLECTIVITY_UV${pbrMaterial.baseMetalnessTexture.coordinatesIndex + 1}`); needUv = true; } else if (pbrMaterial.baseMetalnessTexture) { defines.push("#define METALLIC_TEXTURE"); defines.push(`#define METALLIC_UV${pbrMaterial.baseMetalnessTexture.coordinatesIndex + 1}`); needUv = true; } else if (pbrMaterial.specularRoughnessTexture) { defines.push("#define ROUGHNESS_TEXTURE"); defines.push(`#define ROUGHNESS_UV${pbrMaterial.specularRoughnessTexture.coordinatesIndex + 1}`); needUv = true; } if (pbrMaterial.baseColorTexture) { defines.push("#define ALBEDOTEXTURE"); defines.push(`#define ALBEDO_UV${pbrMaterial.baseColorTexture.coordinatesIndex + 1}`); if (pbrMaterial.baseColorTexture.gammaSpace) { defines.push("#define GAMMAALBEDO"); } needUv = true; } if (pbrMaterial.baseColor) { defines.push("#define ALBEDOCOLOR"); } } } if (needUv) { defines.push("#define NEED_UV"); if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { attribs.push(VertexBuffer.UVKind); defines.push("#define UV1"); uv1 = true; } if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind)) { attribs.push(VertexBuffer.UV2Kind); defines.push("#define UV2"); uv2 = true; } } } if (this._enableDepth) { defines.push("#define DEPTH"); defines.push("#define DEPTH_INDEX " + this._depthIndex); } if (this._enableNormal) { defines.push("#define NORMAL"); defines.push("#define NORMAL_INDEX " + this._normalIndex); } if (this._enablePosition) { defines.push("#define POSITION"); defines.push("#define POSITION_INDEX " + this._positionIndex); } if (this._enableVelocity) { defines.push("#define VELOCITY"); defines.push("#define VELOCITY_INDEX " + this._velocityIndex); if (this.excludedSkinnedMeshesFromVelocity.indexOf(mesh) === -1) { defines.push("#define BONES_VELOCITY_ENABLED"); } } if (this._enableVelocityLinear) { defines.push("#define VELOCITY_LINEAR"); defines.push("#define VELOCITY_LINEAR_INDEX " + this._velocityLinearIndex); if (this.excludedSkinnedMeshesFromVelocity.indexOf(mesh) === -1) { defines.push("#define BONES_VELOCITY_ENABLED"); } } if (this._enableReflectivity) { defines.push("#define REFLECTIVITY"); defines.push("#define REFLECTIVITY_INDEX " + this._reflectivityIndex); } if (this._enableScreenspaceDepth) { if (this._screenspaceDepthIndex !== -1) { defines.push("#define SCREENSPACE_DEPTH_INDEX " + this._screenspaceDepthIndex); defines.push("#define SCREENSPACE_DEPTH"); } } if (this.generateNormalsInWorldSpace) { defines.push("#define NORMAL_WORLDSPACE"); } if (this._normalsAreUnsigned) { defines.push("#define ENCODE_NORMAL"); } if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { attribs.push(VertexBuffer.MatricesIndicesKind); attribs.push(VertexBuffer.MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(VertexBuffer.MatricesIndicesExtraKind); attribs.push(VertexBuffer.MatricesWeightsExtraKind); } defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); defines.push("#define BONETEXTURE " + mesh.skeleton.isUsingTextureForMatrices); defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1)); } else { defines.push("#define NUM_BONE_INFLUENCERS 0"); defines.push("#define BONETEXTURE false"); defines.push("#define BonesPerMesh 0"); } const numMorphInfluencers = mesh.morphTargetManager ? PrepareDefinesAndAttributesForMorphTargets( mesh.morphTargetManager, defines, attribs, mesh, true, // usePositionMorph true, // useNormalMorph false, // useTangentMorph uv1, // useUVMorph uv2, // useUV2Morph color // useColorMorph ) : 0; if (useInstances) { defines.push("#define INSTANCES"); PushAttributesForInstances(attribs, this._enableVelocity || this._enableVelocityLinear); if (subMesh.getRenderingMesh().hasThinInstances) { defines.push("#define THIN_INSTANCES"); } } if (this._linkedWithPrePass) { defines.push("#define SCENE_MRT_COUNT " + this._attachmentsFromPrePass.length); } else { defines.push("#define SCENE_MRT_COUNT " + this._multiRenderTarget.textures.length); } PrepareStringDefinesForClipPlanes(material, this._scene, defines); const engine = this._scene.getEngine(); const drawWrapper = subMesh._getDrawWrapper(void 0, true); const cachedDefines = drawWrapper.defines; const join = defines.join("\n"); if (cachedDefines !== join) { drawWrapper.setEffect(engine.createEffect("geometry", { attributes: attribs, uniformsNames: Uniforms, samplers: ["diffuseSampler", "bumpSampler", "reflectivitySampler", "albedoSampler", "morphTargets", "boneSampler"], defines: join, onCompiled: null, fallbacks: null, onError: null, uniformBuffersNames: ["Scene"], indexParameters: { buffersCount: this._multiRenderTarget.textures.length - 1, maxSimultaneousMorphTargets: numMorphInfluencers }, shaderLanguage: this.shaderLanguage }, engine), join); } return drawWrapper.effect.isReady(); } /** * Gets the current underlying G Buffer. * @returns the buffer */ getGBuffer() { return this._multiRenderTarget; } /** * Gets the number of samples used to render the buffer (anti aliasing). */ get samples() { return this._multiRenderTarget.samples; } /** * Sets the number of samples used to render the buffer (anti aliasing). */ set samples(value) { this._multiRenderTarget.samples = value; } /** * Disposes the renderer and frees up associated resources. */ dispose() { if (this._resizeObserver) { const engine = this._scene.getEngine(); engine.onResizeObservable.remove(this._resizeObserver); this._resizeObserver = null; } this.getGBuffer().dispose(); } _assignRenderTargetIndices() { const textureNames = []; const textureTypesAndFormats = []; let count = 0; if (this._enableDepth) { this._depthIndex = count; count++; textureNames.push("gBuffer_Depth"); textureTypesAndFormats.push(this._textureTypesAndFormats[_GeometryBufferRenderer.DEPTH_TEXTURE_TYPE]); } if (this._enableNormal) { this._normalIndex = count; count++; textureNames.push("gBuffer_Normal"); textureTypesAndFormats.push(this._textureTypesAndFormats[_GeometryBufferRenderer.NORMAL_TEXTURE_TYPE]); } if (this._enablePosition) { this._positionIndex = count; count++; textureNames.push("gBuffer_Position"); textureTypesAndFormats.push(this._textureTypesAndFormats[_GeometryBufferRenderer.POSITION_TEXTURE_TYPE]); } if (this._enableVelocity) { this._velocityIndex = count; count++; textureNames.push("gBuffer_Velocity"); textureTypesAndFormats.push(this._textureTypesAndFormats[_GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE]); } if (this._enableVelocityLinear) { this._velocityLinearIndex = count; count++; textureNames.push("gBuffer_VelocityLinear"); textureTypesAndFormats.push(this._textureTypesAndFormats[_GeometryBufferRenderer.VELOCITY_LINEAR_TEXTURE_TYPE]); } if (this._enableReflectivity) { this._reflectivityIndex = count; count++; textureNames.push("gBuffer_Reflectivity"); textureTypesAndFormats.push(this._textureTypesAndFormats[_GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE]); } if (this._enableScreenspaceDepth) { this._screenspaceDepthIndex = count; count++; textureNames.push("gBuffer_ScreenspaceDepth"); textureTypesAndFormats.push(this._textureTypesAndFormats[_GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE]); } return [count, textureNames, textureTypesAndFormats]; } _createRenderTargets() { const engine = this._scene.getEngine(); const [count, textureNames, textureTypesAndFormat] = this._assignRenderTargetIndices(); let type = 0; if (engine._caps.textureFloat && engine._caps.textureFloatLinearFiltering) { type = 1; } else if (engine._caps.textureHalfFloat && engine._caps.textureHalfFloatLinearFiltering) { type = 2; } const dimensions = this._ratioOrDimensions.width !== void 0 ? this._ratioOrDimensions : { width: engine.getRenderWidth() * this._ratioOrDimensions, height: engine.getRenderHeight() * this._ratioOrDimensions }; const textureTypes = []; const textureFormats = []; for (const typeAndFormat of textureTypesAndFormat) { if (typeAndFormat) { textureTypes.push(typeAndFormat.textureType); textureFormats.push(typeAndFormat.textureFormat); } else { textureTypes.push(type); textureFormats.push(5); } } this._normalsAreUnsigned = textureTypes[_GeometryBufferRenderer.NORMAL_TEXTURE_TYPE] === 11 || textureTypes[_GeometryBufferRenderer.NORMAL_TEXTURE_TYPE] === 13; this._multiRenderTarget = new MultiRenderTarget("gBuffer", dimensions, count, this._scene, { generateMipMaps: false, generateDepthTexture: true, types: textureTypes, formats: textureFormats, depthTextureFormat: this._depthFormat }, textureNames.concat("gBuffer_DepthBuffer")); if (!this.isSupported) { return; } this._multiRenderTarget.wrapU = Texture.CLAMP_ADDRESSMODE; this._multiRenderTarget.wrapV = Texture.CLAMP_ADDRESSMODE; this._multiRenderTarget.refreshRate = 1; this._multiRenderTarget.renderParticles = false; this._multiRenderTarget.renderList = null; const layoutAttachmentsAll = [true]; const layoutAttachmentsAllButDepth = [false]; const layoutAttachmentsDepthOnly = [true]; for (let i = 1; i < count; ++i) { layoutAttachmentsAll.push(true); layoutAttachmentsDepthOnly.push(false); layoutAttachmentsAllButDepth.push(true); } const attachmentsAll = engine.buildTextureLayout(layoutAttachmentsAll); const attachmentsAllButDepth = engine.buildTextureLayout(layoutAttachmentsAllButDepth); const attachmentsDepthOnly = engine.buildTextureLayout(layoutAttachmentsDepthOnly); this._multiRenderTarget.onClearObservable.add((engine2) => { engine2.bindAttachments(this.useSpecificClearForDepthTexture ? attachmentsAllButDepth : attachmentsAll); engine2.clear(this._clearColor, true, true, true); if (this.useSpecificClearForDepthTexture) { engine2.bindAttachments(attachmentsDepthOnly); engine2.clear(this._clearDepthColor, true, true, true); } engine2.bindAttachments(attachmentsAll); }); this._resizeObserver = engine.onResizeObservable.add(() => { if (this._multiRenderTarget) { const dimensions2 = this._ratioOrDimensions.width !== void 0 ? this._ratioOrDimensions : { width: engine.getRenderWidth() * this._ratioOrDimensions, height: engine.getRenderHeight() * this._ratioOrDimensions }; this._multiRenderTarget.resize(dimensions2); } }); const renderSubMesh = /* @__PURE__ */ __name((subMesh) => { const renderingMesh = subMesh.getRenderingMesh(); const effectiveMesh = subMesh.getEffectiveMesh(); const scene = this._scene; const engine2 = scene.getEngine(); const material = subMesh.getMaterial(); if (!material) { return; } effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; if ((this._enableVelocity || this._enableVelocityLinear) && !this._previousTransformationMatrices[effectiveMesh.uniqueId]) { this._previousTransformationMatrices[effectiveMesh.uniqueId] = { world: Matrix.Identity(), viewProjection: scene.getTransformMatrix() }; if (renderingMesh.skeleton) { const bonesTransformations = renderingMesh.skeleton.getTransformMatrices(renderingMesh); this._previousBonesTransformationMatrices[renderingMesh.uniqueId] = this._copyBonesTransformationMatrices(bonesTransformations, new Float32Array(bonesTransformations.length)); } } const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); if (batch.mustReturn) { return; } const hardwareInstancedRendering = engine2.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances); const world = effectiveMesh.getWorldMatrix(); if (this.isReady(subMesh, hardwareInstancedRendering)) { const drawWrapper = subMesh._getDrawWrapper(); if (!drawWrapper) { return; } const effect = drawWrapper.effect; engine2.enableEffect(drawWrapper); if (!hardwareInstancedRendering) { renderingMesh._bind(subMesh, effect, material.fillMode); } if (!this._useUbo) { effect.setMatrix("viewProjection", scene.getTransformMatrix()); effect.setMatrix("view", scene.getViewMatrix()); } else { BindSceneUniformBuffer(effect, this._scene.getSceneUniformBuffer()); this._scene.finalizeSceneUbo(); } let sideOrientation; const instanceDataStorage = renderingMesh._instanceDataStorage; if (!instanceDataStorage.isFrozen && (material.backFaceCulling || material.sideOrientation !== null)) { const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant(); sideOrientation = material._getEffectiveOrientation(renderingMesh); if (mainDeterminant < 0) { sideOrientation = sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation; } } else { sideOrientation = renderingMesh._effectiveSideOrientation; } material._preBind(drawWrapper, sideOrientation); if (material.needAlphaTestingForMesh(effectiveMesh)) { const alphaTexture = material.getAlphaTestTexture(); if (alphaTexture) { effect.setTexture("diffuseSampler", alphaTexture); effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix()); } } if ((material.bumpTexture || material.normalTexture || material.geometryNormalTexture) && scene.getEngine().getCaps().standardDerivatives && MaterialFlags.BumpTextureEnabled) { const texture = material.bumpTexture || material.normalTexture || material.geometryNormalTexture; effect.setFloat3("vBumpInfos", texture.coordinatesIndex, 1 / texture.level, material.parallaxScaleBias); effect.setMatrix("bumpMatrix", texture.getTextureMatrix()); effect.setTexture("bumpSampler", texture); effect.setFloat2("vTangentSpaceParams", material.invertNormalMapX ? -1 : 1, material.invertNormalMapY ? -1 : 1); } if (this._enableReflectivity) { if (material.getClassName() === "PBRMetallicRoughnessMaterial") { if (material.metallicRoughnessTexture !== null) { effect.setTexture("reflectivitySampler", material.metallicRoughnessTexture); effect.setMatrix("reflectivityMatrix", material.metallicRoughnessTexture.getTextureMatrix()); } if (material.metallic !== null) { effect.setFloat("metallic", material.metallic); } if (material.roughness !== null) { effect.setFloat("glossiness", 1 - material.roughness); } if (material.baseTexture !== null) { effect.setTexture("albedoSampler", material.baseTexture); effect.setMatrix("albedoMatrix", material.baseTexture.getTextureMatrix()); } if (material.baseColor !== null) { effect.setColor3("albedoColor", material.baseColor); } } else if (material.getClassName() === "PBRSpecularGlossinessMaterial") { if (material.specularGlossinessTexture !== null) { effect.setTexture("reflectivitySampler", material.specularGlossinessTexture); effect.setMatrix("reflectivityMatrix", material.specularGlossinessTexture.getTextureMatrix()); } else { if (material.specularColor !== null) { effect.setColor3("reflectivityColor", material.specularColor); } } if (material.glossiness !== null) { effect.setFloat("glossiness", material.glossiness); } } else if (material.getClassName() === "PBRMaterial") { if (material.metallicTexture !== null) { effect.setTexture("reflectivitySampler", material.metallicTexture); effect.setMatrix("reflectivityMatrix", material.metallicTexture.getTextureMatrix()); } if (material.metallic !== null) { effect.setFloat("metallic", material.metallic); } if (material.roughness !== null) { effect.setFloat("glossiness", 1 - material.roughness); } if (material.roughness !== null || material.metallic !== null || material.metallicTexture !== null) { if (material.albedoTexture !== null) { effect.setTexture("albedoSampler", material.albedoTexture); effect.setMatrix("albedoMatrix", material.albedoTexture.getTextureMatrix()); } if (material.albedoColor !== null) { effect.setColor3("albedoColor", material.albedoColor); } } else { if (material.reflectivityTexture !== null) { effect.setTexture("reflectivitySampler", material.reflectivityTexture); effect.setMatrix("reflectivityMatrix", material.reflectivityTexture.getTextureMatrix()); } else if (material.reflectivityColor !== null) { effect.setColor3("reflectivityColor", material.reflectivityColor); } if (material.microSurface !== null) { effect.setFloat("glossiness", material.microSurface); } } } else if (material.getClassName() === "StandardMaterial") { if (material.specularTexture !== null) { effect.setTexture("reflectivitySampler", material.specularTexture); effect.setMatrix("reflectivityMatrix", material.specularTexture.getTextureMatrix()); } if (material.specularColor !== null) { effect.setColor3("reflectivityColor", material.specularColor); } } else if (material.getClassName() === "OpenPBRMaterial") { const openpbrMaterial = material; if (openpbrMaterial._useRoughnessFromMetallicTextureGreen && openpbrMaterial.baseMetalnessTexture) { effect.setTexture("reflectivitySampler", openpbrMaterial.baseMetalnessTexture); effect.setMatrix("reflectivityMatrix", openpbrMaterial.baseMetalnessTexture.getTextureMatrix()); } else if (openpbrMaterial.baseMetalnessTexture) { effect.setTexture("metallicSampler", openpbrMaterial.baseMetalnessTexture); effect.setMatrix("metallicMatrix", openpbrMaterial.baseMetalnessTexture.getTextureMatrix()); } else if (openpbrMaterial.specularRoughnessTexture) { effect.setTexture("roughnessSampler", openpbrMaterial.specularRoughnessTexture); effect.setMatrix("roughnessMatrix", openpbrMaterial.specularRoughnessTexture.getTextureMatrix()); } effect.setFloat("metallic", openpbrMaterial.baseMetalness); effect.setFloat("glossiness", 1 - openpbrMaterial.specularRoughness); if (openpbrMaterial.baseColorTexture !== null) { effect.setTexture("albedoSampler", openpbrMaterial.baseColorTexture); effect.setMatrix("albedoMatrix", openpbrMaterial.baseColorTexture.getTextureMatrix()); } if (openpbrMaterial.baseColor !== null) { effect.setColor3("albedoColor", openpbrMaterial.baseColor); } } } BindClipPlane(effect, material, this._scene); if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) { const skeleton = renderingMesh.skeleton; if (skeleton.isUsingTextureForMatrices && effect.getUniformIndex("boneTextureWidth") > -1) { const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh); effect.setTexture("boneSampler", boneTexture); effect.setFloat("boneTextureWidth", 4 * (skeleton.bones.length + 1)); } else { effect.setMatrices("mBones", renderingMesh.skeleton.getTransformMatrices(renderingMesh)); } if (this._enableVelocity || this._enableVelocityLinear) { effect.setMatrices("mPreviousBones", this._previousBonesTransformationMatrices[renderingMesh.uniqueId]); } } BindMorphTargetParameters(renderingMesh, effect); if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { renderingMesh.morphTargetManager._bind(effect); } if (this._enableVelocity || this._enableVelocityLinear) { effect.setMatrix("previousWorld", this._previousTransformationMatrices[effectiveMesh.uniqueId].world); effect.setMatrix("previousViewProjection", this._previousTransformationMatrices[effectiveMesh.uniqueId].viewProjection); } if (hardwareInstancedRendering && renderingMesh.hasThinInstances) { effect.setMatrix("world", world); } renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, w) => { if (!isInstance) { effect.setMatrix("world", w); } }); } if (this._enableVelocity || this._enableVelocityLinear) { this._previousTransformationMatrices[effectiveMesh.uniqueId].world = world.clone(); this._previousTransformationMatrices[effectiveMesh.uniqueId].viewProjection = this._scene.getTransformMatrix().clone(); if (renderingMesh.skeleton) { this._copyBonesTransformationMatrices(renderingMesh.skeleton.getTransformMatrices(renderingMesh), this._previousBonesTransformationMatrices[effectiveMesh.uniqueId]); } } }, "renderSubMesh"); this._multiRenderTarget.customIsReadyFunction = (mesh, refreshRate, preWarm) => { if ((preWarm || refreshRate === 0) && mesh.subMeshes) { for (let i = 0; i < mesh.subMeshes.length; ++i) { const subMesh = mesh.subMeshes[i]; const material = subMesh.getMaterial(); const renderingMesh = subMesh.getRenderingMesh(); if (!material) { continue; } const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); const hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null || renderingMesh.hasThinInstances); if (!this.isReady(subMesh, hardwareInstancedRendering)) { return false; } } } return true; }; this._multiRenderTarget.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => { let index; if (this._linkedWithPrePass) { if (!this._prePassRenderer.enabled) { return; } this._scene.getEngine().bindAttachments(this._attachmentsFromPrePass); } if (depthOnlySubMeshes.length) { engine.setColorWrite(false); for (index = 0; index < depthOnlySubMeshes.length; index++) { renderSubMesh(depthOnlySubMeshes.data[index]); } engine.setColorWrite(true); } for (index = 0; index < opaqueSubMeshes.length; index++) { renderSubMesh(opaqueSubMeshes.data[index]); } engine.setDepthWrite(false); for (index = 0; index < alphaTestSubMeshes.length; index++) { renderSubMesh(alphaTestSubMeshes.data[index]); } if (this.renderTransparentMeshes) { for (index = 0; index < transparentSubMeshes.length; index++) { renderSubMesh(transparentSubMeshes.data[index]); } } engine.setDepthWrite(true); }; } // Copies the bones transformation matrices into the target array and returns the target's reference _copyBonesTransformationMatrices(source, target) { for (let i = 0; i < source.length; i++) { target[i] = source[i]; } return target; } }; GeometryBufferRenderer.ForceGLSL = false; GeometryBufferRenderer.DEPTH_TEXTURE_TYPE = 0; GeometryBufferRenderer.NORMAL_TEXTURE_TYPE = 1; GeometryBufferRenderer.POSITION_TEXTURE_TYPE = 2; GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE = 3; GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE = 4; GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE = 5; GeometryBufferRenderer.VELOCITY_LINEAR_TEXTURE_TYPE = 6; GeometryBufferRenderer._SceneComponentInitialization = (_) => { throw _WarnImport("GeometryBufferRendererSceneComponent"); }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinSSRPostProcess.js init_effectRenderer(); init_math_vector(); var Trs = Matrix.Compose(new Vector3(0.5, 0.5, 0.5), Quaternion.Identity(), new Vector3(0.5, 0.5, 0.5)); var TrsWebGPU = Matrix.Compose(new Vector3(0.5, 0.5, 1), Quaternion.Identity(), new Vector3(0.5, 0.5, 0)); var ThinSSRPostProcess = class _ThinSSRPostProcess extends EffectWrapper { static { __name(this, "ThinSSRPostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_screenSpaceReflection2_fragment(), screenSpaceReflection2_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_screenSpaceReflection2_fragment2(), screenSpaceReflection2_fragment_exports2))); } } get reflectivityThreshold() { return this._reflectivityThreshold; } set reflectivityThreshold(threshold) { if (threshold === this._reflectivityThreshold) { return; } if (threshold === 0 && this._reflectivityThreshold !== 0 || threshold !== 0 && this._reflectivityThreshold === 0) { this._reflectivityThreshold = threshold; this._updateEffectDefines(); } else { this._reflectivityThreshold = threshold; } } get useBlur() { return this._useBlur; } set useBlur(blur) { if (this._useBlur === blur) { return; } this._useBlur = blur; this._updateEffectDefines(); } get enableSmoothReflections() { return this._enableSmoothReflections; } set enableSmoothReflections(enabled) { if (enabled === this._enableSmoothReflections) { return; } this._enableSmoothReflections = enabled; this._updateEffectDefines(); } get environmentTexture() { return this._environmentTexture; } set environmentTexture(texture) { this._environmentTexture = texture; this._updateEffectDefines(); } get environmentTextureIsProbe() { return this._environmentTextureIsProbe; } set environmentTextureIsProbe(isProbe) { this._environmentTextureIsProbe = isProbe; this._updateEffectDefines(); } get attenuateScreenBorders() { return this._attenuateScreenBorders; } set attenuateScreenBorders(attenuate) { if (this._attenuateScreenBorders === attenuate) { return; } this._attenuateScreenBorders = attenuate; this._updateEffectDefines(); } get attenuateIntersectionDistance() { return this._attenuateIntersectionDistance; } set attenuateIntersectionDistance(attenuate) { if (this._attenuateIntersectionDistance === attenuate) { return; } this._attenuateIntersectionDistance = attenuate; this._updateEffectDefines(); } get attenuateIntersectionIterations() { return this._attenuateIntersectionIterations; } set attenuateIntersectionIterations(attenuate) { if (this._attenuateIntersectionIterations === attenuate) { return; } this._attenuateIntersectionIterations = attenuate; this._updateEffectDefines(); } get attenuateFacingCamera() { return this._attenuateFacingCamera; } set attenuateFacingCamera(attenuate) { if (this._attenuateFacingCamera === attenuate) { return; } this._attenuateFacingCamera = attenuate; this._updateEffectDefines(); } get attenuateBackfaceReflection() { return this._attenuateBackfaceReflection; } set attenuateBackfaceReflection(attenuate) { if (this._attenuateBackfaceReflection === attenuate) { return; } this._attenuateBackfaceReflection = attenuate; this._updateEffectDefines(); } get clipToFrustum() { return this._clipToFrustum; } set clipToFrustum(clip) { if (this._clipToFrustum === clip) { return; } this._clipToFrustum = clip; this._updateEffectDefines(); } get useFresnel() { return this._useFresnel; } set useFresnel(fresnel) { if (this._useFresnel === fresnel) { return; } this._useFresnel = fresnel; this._updateEffectDefines(); } get enableAutomaticThicknessComputation() { return this._enableAutomaticThicknessComputation; } set enableAutomaticThicknessComputation(automatic) { if (this._enableAutomaticThicknessComputation === automatic) { return; } this._enableAutomaticThicknessComputation = automatic; this._updateEffectDefines(); } get inputTextureColorIsInGammaSpace() { return this._inputTextureColorIsInGammaSpace; } set inputTextureColorIsInGammaSpace(gammaSpace) { if (this._inputTextureColorIsInGammaSpace === gammaSpace) { return; } this._inputTextureColorIsInGammaSpace = gammaSpace; this._updateEffectDefines(); } get generateOutputInGammaSpace() { return this._generateOutputInGammaSpace; } set generateOutputInGammaSpace(gammaSpace) { if (this._generateOutputInGammaSpace === gammaSpace) { return; } this._generateOutputInGammaSpace = gammaSpace; this._updateEffectDefines(); } get debug() { return this._debug; } set debug(value) { if (this._debug === value) { return; } this._debug = value; this._updateEffectDefines(); } get textureWidth() { return this._textureWidth; } set textureWidth(width) { if (this._textureWidth === width) { return; } this._textureWidth = width; } get textureHeight() { return this._textureHeight; } set textureHeight(height) { if (this._textureHeight === height) { return; } this._textureHeight = height; } get useScreenspaceDepth() { return this._useScreenspaceDepth; } set useScreenspaceDepth(value) { if (this._useScreenspaceDepth === value) { return; } this._useScreenspaceDepth = value; this._updateEffectDefines(); } get normalsAreInWorldSpace() { return this._normalsAreInWorldSpace; } set normalsAreInWorldSpace(value) { if (this._normalsAreInWorldSpace === value) { return; } this._normalsAreInWorldSpace = value; this._updateEffectDefines(); } get normalsAreUnsigned() { return this._normalsAreUnsigned; } set normalsAreUnsigned(value) { if (this._normalsAreUnsigned === value) { return; } this._normalsAreUnsigned = value; this._updateEffectDefines(); } constructor(name260, scene, options) { super({ ...options, name: name260, engine: scene.getEngine(), useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinSSRPostProcess.FragmentUrl, uniforms: _ThinSSRPostProcess.Uniforms, samplers: _ThinSSRPostProcess.Samplers, shaderLanguage: scene.getEngine().isWebGPU ? 1 : 0 }); this.isSSRSupported = true; this.maxDistance = 1e3; this.step = 1; this.thickness = 0.5; this.strength = 1; this.reflectionSpecularFalloffExponent = 1; this.maxSteps = 1e3; this.roughnessFactor = 0.2; this.selfCollisionNumSkip = 1; this._reflectivityThreshold = 0.04; this._useBlur = false; this._enableSmoothReflections = false; this._environmentTextureIsProbe = false; this._attenuateScreenBorders = true; this._attenuateIntersectionDistance = true; this._attenuateIntersectionIterations = true; this._attenuateFacingCamera = false; this._attenuateBackfaceReflection = false; this._clipToFrustum = true; this._useFresnel = false; this._enableAutomaticThicknessComputation = false; this._inputTextureColorIsInGammaSpace = true; this._generateOutputInGammaSpace = true; this._debug = false; this._textureWidth = 0; this._textureHeight = 0; this.camera = null; this._useScreenspaceDepth = false; this._normalsAreInWorldSpace = false; this._normalsAreUnsigned = false; this._scene = scene; this._updateEffectDefines(); } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); const effect = this._drawWrapper.effect; const camera = this.camera; if (!camera) { return; } const viewMatrix = camera.getViewMatrix(); const projectionMatrix = camera.getProjectionMatrix(); projectionMatrix.invertToRef(TmpVectors.Matrix[0]); viewMatrix.invertToRef(TmpVectors.Matrix[1]); effect.setMatrix("projection", projectionMatrix); effect.setMatrix("view", viewMatrix); effect.setMatrix("invView", TmpVectors.Matrix[1]); effect.setMatrix("invProjectionMatrix", TmpVectors.Matrix[0]); effect.setFloat("thickness", this.thickness); effect.setFloat("reflectionSpecularFalloffExponent", this.reflectionSpecularFalloffExponent); effect.setFloat("strength", this.strength); effect.setFloat("stepSize", this.step); effect.setFloat("maxSteps", this.maxSteps); effect.setFloat("roughnessFactor", this.roughnessFactor); effect.setFloat("nearPlaneZ", camera.minZ); effect.setFloat("farPlaneZ", camera.maxZ); effect.setFloat("maxDistance", this.maxDistance); effect.setFloat("selfCollisionNumSkip", this.selfCollisionNumSkip); effect.setFloat("reflectivityThreshold", this._reflectivityThreshold); Matrix.ScalingToRef(this.textureWidth, this.textureHeight, 1, TmpVectors.Matrix[2]); projectionMatrix.multiplyToRef(this._scene.getEngine().isWebGPU ? TrsWebGPU : Trs, TmpVectors.Matrix[3]); TmpVectors.Matrix[3].multiplyToRef(TmpVectors.Matrix[2], TmpVectors.Matrix[4]); effect.setMatrix("projectionPixel", TmpVectors.Matrix[4]); if (this._environmentTexture) { effect.setTexture("envCubeSampler", this._environmentTexture); if (this._environmentTexture.boundingBoxSize) { effect.setVector3("vReflectionPosition", this._environmentTexture.boundingBoxPosition); effect.setVector3("vReflectionSize", this._environmentTexture.boundingBoxSize); } } } _updateEffectDefines() { const defines = []; if (this.isSSRSupported) { defines.push("#define SSR_SUPPORTED"); } if (this._enableSmoothReflections) { defines.push("#define SSRAYTRACE_ENABLE_REFINEMENT"); } if (this._scene.useRightHandedSystem) { defines.push("#define SSRAYTRACE_RIGHT_HANDED_SCENE"); } if (this._useScreenspaceDepth) { defines.push("#define SSRAYTRACE_SCREENSPACE_DEPTH"); } if (this._environmentTexture) { defines.push("#define SSR_USE_ENVIRONMENT_CUBE"); if (this._environmentTexture.boundingBoxSize) { defines.push("#define SSR_USE_LOCAL_REFLECTIONMAP_CUBIC"); } if (this._environmentTexture.gammaSpace) { defines.push("#define SSR_ENVIRONMENT_CUBE_IS_GAMMASPACE"); } } if (this._environmentTextureIsProbe) { defines.push("#define SSR_INVERTCUBICMAP"); } if (this._enableAutomaticThicknessComputation) { defines.push("#define SSRAYTRACE_USE_BACK_DEPTHBUFFER"); } if (this._attenuateScreenBorders) { defines.push("#define SSR_ATTENUATE_SCREEN_BORDERS"); } if (this._attenuateIntersectionDistance) { defines.push("#define SSR_ATTENUATE_INTERSECTION_DISTANCE"); } if (this._attenuateIntersectionIterations) { defines.push("#define SSR_ATTENUATE_INTERSECTION_NUMITERATIONS"); } if (this._attenuateFacingCamera) { defines.push("#define SSR_ATTENUATE_FACING_CAMERA"); } if (this._attenuateBackfaceReflection) { defines.push("#define SSR_ATTENUATE_BACKFACE_REFLECTION"); } if (this._clipToFrustum) { defines.push("#define SSRAYTRACE_CLIP_TO_FRUSTUM"); } if (this.useBlur) { defines.push("#define SSR_USE_BLUR"); } if (this._debug) { defines.push("#define SSRAYTRACE_DEBUG"); } if (this._inputTextureColorIsInGammaSpace) { defines.push("#define SSR_INPUT_IS_GAMMA_SPACE"); } if (this._generateOutputInGammaSpace) { defines.push("#define SSR_OUTPUT_IS_GAMMA_SPACE"); } if (this._useFresnel) { defines.push("#define SSR_BLEND_WITH_FRESNEL"); } if (this._reflectivityThreshold === 0) { defines.push("#define SSR_DISABLE_REFLECTIVITY_TEST"); } if (this._normalsAreInWorldSpace) { defines.push("#define SSR_NORMAL_IS_IN_WORLDSPACE"); } if (this._normalsAreUnsigned) { defines.push("#define SSR_DECODE_NORMAL"); } if (this.camera && this.camera.mode === 1) { defines.push("#define ORTHOGRAPHIC_CAMERA"); } this.updateEffect(defines.join("\n")); } }; ThinSSRPostProcess.FragmentUrl = "screenSpaceReflection2"; ThinSSRPostProcess.Uniforms = [ "projection", "invProjectionMatrix", "view", "invView", "thickness", "reflectionSpecularFalloffExponent", "strength", "stepSize", "maxSteps", "roughnessFactor", "projectionPixel", "nearPlaneZ", "farPlaneZ", "maxDistance", "selfCollisionNumSkip", "vReflectionPosition", "vReflectionSize", "backSizeFactor", "reflectivityThreshold" ]; ThinSSRPostProcess.Samplers = ["textureSampler", "normalSampler", "reflectivitySampler", "depthSampler", "envCubeSampler", "backDepthSampler"]; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinSSRBlurPostProcess.js init_effectRenderer(); init_engine(); init_math_vector(); var ThinSSRBlurPostProcess = class _ThinSSRBlurPostProcess extends EffectWrapper { static { __name(this, "ThinSSRBlurPostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_screenSpaceReflection2Blur_fragment(), screenSpaceReflection2Blur_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_screenSpaceReflection2Blur_fragment2(), screenSpaceReflection2Blur_fragment_exports2))); } } constructor(name260, engine = null, direction, blurStrength, options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinSSRBlurPostProcess.FragmentUrl, uniforms: _ThinSSRBlurPostProcess.Uniforms, samplers: _ThinSSRBlurPostProcess.Samplers }); this.textureWidth = 0; this.textureHeight = 0; this.direction = new Vector2(1, 0); this.blurStrength = 0.03; if (direction !== void 0) { this.direction = direction; } if (blurStrength !== void 0) { this.blurStrength = blurStrength; } } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); this._drawWrapper.effect.setFloat2("texelOffsetScale", 1 / this.textureWidth * this.direction.x * this.blurStrength, 1 / this.textureHeight * this.direction.y * this.blurStrength); } }; ThinSSRBlurPostProcess.FragmentUrl = "screenSpaceReflection2Blur"; ThinSSRBlurPostProcess.Uniforms = ["texelOffsetScale"]; ThinSSRBlurPostProcess.Samplers = ["textureSampler"]; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinSSRBlurCombinerPostProcess.js init_effectRenderer(); init_engine(); init_math_vector(); var ThinSSRBlurCombinerPostProcess = class _ThinSSRBlurCombinerPostProcess extends EffectWrapper { static { __name(this, "ThinSSRBlurCombinerPostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_screenSpaceReflection2BlurCombiner_fragment(), screenSpaceReflection2BlurCombiner_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_screenSpaceReflection2BlurCombiner_fragment2(), screenSpaceReflection2BlurCombiner_fragment_exports2))); } } constructor(name260, engine = null, options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinSSRBlurCombinerPostProcess.FragmentUrl, uniforms: _ThinSSRBlurCombinerPostProcess.Uniforms, samplers: _ThinSSRBlurCombinerPostProcess.Samplers }); this.strength = 1; this.reflectionSpecularFalloffExponent = 1; this.camera = null; this._useFresnel = false; this._useScreenspaceDepth = false; this._inputTextureColorIsInGammaSpace = true; this._generateOutputInGammaSpace = true; this._debug = false; this._reflectivityThreshold = 0.04; this._normalsAreInWorldSpace = false; this._normalsAreUnsigned = false; this._updateEffectDefines(); } get useFresnel() { return this._useFresnel; } set useFresnel(fresnel) { if (this._useFresnel === fresnel) { return; } this._useFresnel = fresnel; this._updateEffectDefines(); } get useScreenspaceDepth() { return this._useScreenspaceDepth; } set useScreenspaceDepth(value) { if (this._useScreenspaceDepth === value) { return; } this._useScreenspaceDepth = value; this._updateEffectDefines(); } get inputTextureColorIsInGammaSpace() { return this._inputTextureColorIsInGammaSpace; } set inputTextureColorIsInGammaSpace(gammaSpace) { if (this._inputTextureColorIsInGammaSpace === gammaSpace) { return; } this._inputTextureColorIsInGammaSpace = gammaSpace; this._updateEffectDefines(); } get generateOutputInGammaSpace() { return this._generateOutputInGammaSpace; } set generateOutputInGammaSpace(gammaSpace) { if (this._generateOutputInGammaSpace === gammaSpace) { return; } this._generateOutputInGammaSpace = gammaSpace; this._updateEffectDefines(); } get debug() { return this._debug; } set debug(value) { if (this._debug === value) { return; } this._debug = value; this._updateEffectDefines(); } get reflectivityThreshold() { return this._reflectivityThreshold; } set reflectivityThreshold(threshold) { if (threshold === this._reflectivityThreshold) { return; } if (threshold === 0 && this._reflectivityThreshold !== 0 || threshold !== 0 && this._reflectivityThreshold === 0) { this._reflectivityThreshold = threshold; this._updateEffectDefines(); } else { this._reflectivityThreshold = threshold; } } get normalsAreInWorldSpace() { return this._normalsAreInWorldSpace; } set normalsAreInWorldSpace(value) { if (this._normalsAreInWorldSpace === value) { return; } this._normalsAreInWorldSpace = value; this._updateEffectDefines(); } get normalsAreUnsigned() { return this._normalsAreUnsigned; } set normalsAreUnsigned(value) { if (this._normalsAreUnsigned === value) { return; } this._normalsAreUnsigned = value; this._updateEffectDefines(); } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); const effect = this._drawWrapper.effect; effect.setFloat("strength", this.strength); effect.setFloat("reflectionSpecularFalloffExponent", this.reflectionSpecularFalloffExponent); effect.setFloat("reflectivityThreshold", this.reflectivityThreshold); if (this.useFresnel && this.camera) { const projectionMatrix = this.camera.getProjectionMatrix(); projectionMatrix.invertToRef(TmpVectors.Matrix[0]); effect.setMatrix("projection", projectionMatrix); effect.setMatrix("invProjectionMatrix", TmpVectors.Matrix[0]); effect.setMatrix("view", this.camera.getViewMatrix()); if (this.useScreenspaceDepth) { effect.setFloat("nearPlaneZ", this.camera.minZ); effect.setFloat("farPlaneZ", this.camera.maxZ); } } } _updateEffectDefines() { let defines = ""; if (this._debug) { defines += "#define SSRAYTRACE_DEBUG\n"; } if (this._inputTextureColorIsInGammaSpace) { defines += "#define SSR_INPUT_IS_GAMMA_SPACE\n"; } if (this._generateOutputInGammaSpace) { defines += "#define SSR_OUTPUT_IS_GAMMA_SPACE\n"; } if (this._useFresnel) { defines += "#define SSR_BLEND_WITH_FRESNEL\n"; } if (this._useScreenspaceDepth) { defines += "#define SSRAYTRACE_SCREENSPACE_DEPTH\n"; } if (this._reflectivityThreshold === 0) { defines += "#define SSR_DISABLE_REFLECTIVITY_TEST\n"; } if (this._normalsAreInWorldSpace) { defines += "#define SSR_NORMAL_IS_IN_WORLDSPACE\n"; } if (this._normalsAreUnsigned) { defines += "#define SSR_DECODE_NORMAL\n"; } this.updateEffect(defines); } }; ThinSSRBlurCombinerPostProcess.FragmentUrl = "screenSpaceReflection2BlurCombiner"; ThinSSRBlurCombinerPostProcess.Uniforms = [ "strength", "reflectionSpecularFalloffExponent", "reflectivityThreshold", "projection", "invProjectionMatrix", "nearPlaneZ", "farPlaneZ", "view" ]; ThinSSRBlurCombinerPostProcess.Samplers = ["textureSampler", "depthSampler", "normalSampler", "mainSampler", "reflectivitySampler"]; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/thinSSRRenderingPipeline.js init_math_vector(); var ThinSSRRenderingPipeline = class { static { __name(this, "ThinSSRRenderingPipeline"); } /** * Gets or sets a boolean indicating if the SSR rendering pipeline is supported */ get isSSRSupported() { return this._ssrPostProcess.isSSRSupported; } set isSSRSupported(supported) { this._ssrPostProcess.isSSRSupported = supported; } /** * Gets or sets the maxDistance used to define how far we look for reflection during the ray-marching on the reflected ray (default: 1000). * Note that this value is a view (camera) space distance (not pixels!). */ get maxDistance() { return this._ssrPostProcess.maxDistance; } set maxDistance(distance) { this._ssrPostProcess.maxDistance = distance; } /** * Gets or sets the step size used to iterate until the effect finds the color of the reflection's pixel. Should be an integer \>= 1 as it is the number of pixels we advance at each step (default: 1). * Use higher values to improve performances (but at the expense of quality). */ get step() { return this._ssrPostProcess.step; } set step(step) { this._ssrPostProcess.step = step; } /** * Gets or sets the thickness value used as tolerance when computing the intersection between the reflected ray and the scene (default: 0.5). * If setting "enableAutomaticThicknessComputation" to true, you can use lower values for "thickness" (even 0), as the geometry thickness * is automatically computed thank to the regular depth buffer + the backface depth buffer */ get thickness() { return this._ssrPostProcess.thickness; } set thickness(thickness) { this._ssrPostProcess.thickness = thickness; } /** * Gets or sets the current reflection strength. 1.0 is an ideal value but can be increased/decreased for particular results (default: 1). */ get strength() { return this._ssrPostProcess.strength; } set strength(strength) { this._ssrPostProcess.strength = strength; this._ssrBlurCombinerPostProcess.strength = strength; } /** * Gets or sets the falloff exponent used to compute the reflection strength. Higher values lead to fainter reflections (default: 1). */ get reflectionSpecularFalloffExponent() { return this._ssrPostProcess.reflectionSpecularFalloffExponent; } set reflectionSpecularFalloffExponent(exponent) { this._ssrPostProcess.reflectionSpecularFalloffExponent = exponent; this._ssrBlurCombinerPostProcess.reflectionSpecularFalloffExponent = exponent; } /** * Maximum number of steps during the ray marching process after which we consider an intersection could not be found (default: 1000). * Should be an integer value. */ get maxSteps() { return this._ssrPostProcess.maxSteps; } set maxSteps(steps) { this._ssrPostProcess.maxSteps = steps; } /** * Gets or sets the factor applied when computing roughness. Default value is 0.2. * When blurring based on roughness is enabled (meaning blurDispersionStrength \> 0), roughnessFactor is used as a global roughness factor applied on all objects. * If you want to disable this global roughness set it to 0. */ get roughnessFactor() { return this._ssrPostProcess.roughnessFactor; } set roughnessFactor(factor) { this._ssrPostProcess.roughnessFactor = factor; } /** * Number of steps to skip at start when marching the ray to avoid self collisions (default: 1) * 1 should normally be a good value, depending on the scene you may need to use a higher value (2 or 3) */ get selfCollisionNumSkip() { return this._ssrPostProcess.selfCollisionNumSkip; } set selfCollisionNumSkip(skip) { this._ssrPostProcess.selfCollisionNumSkip = skip; } /** * Gets or sets the minimum value for one of the reflectivity component of the material to consider it for SSR (default: 0.04). * If all r/g/b components of the reflectivity is below or equal this value, the pixel will not be considered reflective and SSR won't be applied. */ get reflectivityThreshold() { return this._ssrPostProcess.reflectivityThreshold; } set reflectivityThreshold(threshold) { const currentThreshold = this._ssrPostProcess.reflectivityThreshold; if (threshold === currentThreshold) { return; } this._ssrPostProcess.reflectivityThreshold = threshold; this._ssrBlurCombinerPostProcess.reflectivityThreshold = threshold; } /** * Gets or sets the blur dispersion strength. Set this value to 0 to disable blurring (default: 0.03) * The reflections are blurred based on the roughness of the surface and the distance between the pixel shaded and the reflected pixel: the higher the distance the more blurry the reflection is. * blurDispersionStrength allows to increase or decrease this effect. */ get blurDispersionStrength() { return this._ssrBlurXPostProcess.blurStrength; } set blurDispersionStrength(strength) { if (strength === this._ssrBlurXPostProcess.blurStrength) { return; } this._ssrPostProcess.useBlur = strength > 0; this._ssrBlurXPostProcess.blurStrength = strength; this._ssrBlurYPostProcess.blurStrength = strength; } /** * Gets or sets whether or not smoothing reflections is enabled (default: false) * Enabling smoothing will require more GPU power. * Note that this setting has no effect if step = 1: it's only used if step \> 1. */ get enableSmoothReflections() { return this._ssrPostProcess.enableSmoothReflections; } set enableSmoothReflections(enabled) { this._ssrPostProcess.enableSmoothReflections = enabled; } /** * Gets or sets the environment cube texture used to define the reflection when the reflected rays of SSR leave the view space or when the maxDistance/maxSteps is reached. */ get environmentTexture() { return this._ssrPostProcess.environmentTexture; } set environmentTexture(texture) { this._ssrPostProcess.environmentTexture = texture; } /** * Gets or sets the boolean defining if the environment texture is a standard cubemap (false) or a probe (true). Default value is false. * Note: a probe cube texture is treated differently than an ordinary cube texture because the Y axis is reversed. */ get environmentTextureIsProbe() { return this._ssrPostProcess.environmentTextureIsProbe; } set environmentTextureIsProbe(isProbe) { this._ssrPostProcess.environmentTextureIsProbe = isProbe; } /** * Gets or sets a boolean indicating if the reflections should be attenuated at the screen borders (default: true). */ get attenuateScreenBorders() { return this._ssrPostProcess.attenuateScreenBorders; } set attenuateScreenBorders(attenuate) { this._ssrPostProcess.attenuateScreenBorders = attenuate; } /** * Gets or sets a boolean indicating if the reflections should be attenuated according to the distance of the intersection (default: true). */ get attenuateIntersectionDistance() { return this._ssrPostProcess.attenuateIntersectionDistance; } set attenuateIntersectionDistance(attenuate) { this._ssrPostProcess.attenuateIntersectionDistance = attenuate; } /** * Gets or sets a boolean indicating if the reflections should be attenuated according to the number of iterations performed to find the intersection (default: true). */ get attenuateIntersectionIterations() { return this._ssrPostProcess.attenuateIntersectionIterations; } set attenuateIntersectionIterations(attenuate) { this._ssrPostProcess.attenuateIntersectionIterations = attenuate; } /** * Gets or sets a boolean indicating if the reflections should be attenuated when the reflection ray is facing the camera (the view direction) (default: false). */ get attenuateFacingCamera() { return this._ssrPostProcess.attenuateFacingCamera; } set attenuateFacingCamera(attenuate) { this._ssrPostProcess.attenuateFacingCamera = attenuate; } /** * Gets or sets a boolean indicating if the backface reflections should be attenuated (default: false). */ get attenuateBackfaceReflection() { return this._ssrPostProcess.attenuateBackfaceReflection; } set attenuateBackfaceReflection(attenuate) { this._ssrPostProcess.attenuateBackfaceReflection = attenuate; } /** * Gets or sets a boolean indicating if the ray should be clipped to the frustum (default: true). * You can try to set this parameter to false to save some performances: it may produce some artefacts in some cases, but generally they won't really be visible */ get clipToFrustum() { return this._ssrPostProcess.clipToFrustum; } set clipToFrustum(clip) { this._ssrPostProcess.clipToFrustum = clip; } /** * Gets or sets a boolean indicating whether the blending between the current color pixel and the reflection color should be done with a Fresnel coefficient (default: false). * It is more physically accurate to use the Fresnel coefficient (otherwise it uses the reflectivity of the material for blending), but it is also more expensive when you use blur (when blurDispersionStrength \> 0). */ get useFresnel() { return this._ssrPostProcess.useFresnel; } set useFresnel(fresnel) { this._ssrPostProcess.useFresnel = fresnel; this._ssrBlurCombinerPostProcess.useFresnel = fresnel; } /** * Gets or sets a boolean defining if geometry thickness should be computed automatically (default: false). * When enabled, a depth renderer is created which will render the back faces of the scene to a depth texture (meaning additional work for the GPU). * In that mode, the "thickness" property is still used as an offset to compute the ray intersection, but you can typically use a much lower * value than when enableAutomaticThicknessComputation is false (it's even possible to use a value of 0 when using low values for "step") * Note that for performance reasons, this option will only apply to the first camera to which the rendering pipeline is attached! */ get enableAutomaticThicknessComputation() { return this._ssrPostProcess.enableAutomaticThicknessComputation; } set enableAutomaticThicknessComputation(automatic) { if (this._ssrPostProcess.enableAutomaticThicknessComputation === automatic) { return; } this._ssrPostProcess.enableAutomaticThicknessComputation = automatic; } /** * Gets or sets a boolean defining if the input color texture is in gamma space (default: true) * The SSR effect works in linear space, so if the input texture is in gamma space, we must convert the texture to linear space before applying the effect */ get inputTextureColorIsInGammaSpace() { return this._ssrPostProcess.inputTextureColorIsInGammaSpace; } set inputTextureColorIsInGammaSpace(gammaSpace) { if (this._ssrPostProcess.inputTextureColorIsInGammaSpace === gammaSpace) { return; } this._ssrPostProcess.inputTextureColorIsInGammaSpace = gammaSpace; this._ssrBlurCombinerPostProcess.inputTextureColorIsInGammaSpace = gammaSpace; } /** * Gets or sets a boolean defining if the output color texture generated by the SSR pipeline should be in gamma space (default: true) * If you have a post-process that comes after the SSR and that post-process needs the input to be in a linear space, you must disable generateOutputInGammaSpace */ get generateOutputInGammaSpace() { return this._ssrPostProcess.generateOutputInGammaSpace; } set generateOutputInGammaSpace(gammaSpace) { if (this._ssrPostProcess.generateOutputInGammaSpace === gammaSpace) { return; } this._ssrPostProcess.generateOutputInGammaSpace = gammaSpace; this._ssrBlurCombinerPostProcess.generateOutputInGammaSpace = gammaSpace; } /** * Gets or sets a boolean indicating if the effect should be rendered in debug mode (default: false). * In this mode, colors have this meaning: * - blue: the ray hit the max distance (we reached maxDistance) * - red: the ray ran out of steps (we reached maxSteps) * - yellow: the ray went off screen * - green: the ray hit a surface. The brightness of the green color is proportional to the distance between the ray origin and the intersection point: A brighter green means more computation than a darker green. * In the first 3 cases, the final color is calculated by mixing the skybox color with the pixel color (if environmentTexture is defined), otherwise the pixel color is not modified * You should try to get as few blue/red/yellow pixels as possible, as this means that the ray has gone further than if it had hit a surface. */ get debug() { return this._ssrPostProcess.debug; } set debug(value) { if (this._ssrPostProcess.debug === value) { return; } this._ssrPostProcess.debug = value; this._ssrBlurCombinerPostProcess.debug = value; } /** * Gets or sets the camera to use to render the reflection */ get camera() { return this._ssrPostProcess.camera; } set camera(camera) { this._ssrPostProcess.camera = camera; this._ssrBlurCombinerPostProcess.camera = camera; } /** * Gets or sets a boolean indicating if the depth buffer stores screen space depth instead of camera view space depth. */ get useScreenspaceDepth() { return this._ssrPostProcess.useScreenspaceDepth; } set useScreenspaceDepth(use) { this._ssrPostProcess.useScreenspaceDepth = use; this._ssrBlurCombinerPostProcess.useScreenspaceDepth = use; } /** * Gets or sets a boolean indicating if the normals are in world space (false by default, meaning normals are in camera view space). */ get normalsAreInWorldSpace() { return this._ssrPostProcess.normalsAreInWorldSpace; } set normalsAreInWorldSpace(normalsAreInWorldSpace) { this._ssrPostProcess.normalsAreInWorldSpace = normalsAreInWorldSpace; this._ssrBlurCombinerPostProcess.normalsAreInWorldSpace = normalsAreInWorldSpace; } /** * Gets or sets a boolean indicating if the normals are encoded as unsigned, that is normalUnsigned = normal*0.5+0.5 (false by default). */ get normalsAreUnsigned() { return this._ssrPostProcess.normalsAreUnsigned; } set normalsAreUnsigned(normalsAreUnsigned) { this._ssrPostProcess.normalsAreUnsigned = normalsAreUnsigned; this._ssrBlurCombinerPostProcess.normalsAreUnsigned = normalsAreUnsigned; } /** * Checks if all the post processes in the pipeline are ready. * @returns true if all the post processes in the pipeline are ready */ isReady() { return this._ssrPostProcess.isReady() && this._ssrBlurXPostProcess.isReady() && this._ssrBlurYPostProcess.isReady() && this._ssrBlurCombinerPostProcess.isReady(); } /** * Constructor of the SSR rendering pipeline * @param name The rendering pipeline name * @param scene The scene linked to this pipeline */ constructor(name260, scene) { this.ssrDownsample = 0; this.blurDownsample = 0; this.name = name260; this._scene = scene; this._ssrPostProcess = new ThinSSRPostProcess(this.name, this._scene); this._ssrBlurXPostProcess = new ThinSSRBlurPostProcess(this.name + " BlurX", this._scene.getEngine(), new Vector2(1, 0)); this._ssrBlurYPostProcess = new ThinSSRBlurPostProcess(this.name + " BlurY", this._scene.getEngine(), new Vector2(0, 1)); this._ssrBlurCombinerPostProcess = new ThinSSRBlurCombinerPostProcess(this.name + " BlurCombiner", this._scene.getEngine()); this._ssrPostProcess.useBlur = this._ssrBlurXPostProcess.blurStrength > 0; } /** * Disposes of the pipeline */ dispose() { this._ssrPostProcess?.dispose(); this._ssrBlurXPostProcess?.dispose(); this._ssrBlurYPostProcess?.dispose(); this._ssrBlurCombinerPostProcess?.dispose(); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderPipelineManager.js init_observable(); var PostProcessRenderPipelineManager = class { static { __name(this, "PostProcessRenderPipelineManager"); } /** * Initializes a PostProcessRenderPipelineManager * @see https://doc.babylonjs.com/features/featuresDeepDive/postProcesses/postProcessRenderPipeline */ constructor() { this._renderPipelines = {}; this._onNewPipelineAddedObservable = new Observable(); this._onPipelineRemovedObservable = new Observable(); } /** * An event triggered when a pipeline is added to the manager */ get onNewPipelineAddedObservable() { return this._onNewPipelineAddedObservable; } /** * An event triggered when a pipeline is removed from the manager */ get onPipelineRemovedObservable() { return this._onPipelineRemovedObservable; } /** * Gets the list of supported render pipelines */ get supportedPipelines() { const result = []; for (const renderPipelineName in this._renderPipelines) { if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) { const pipeline = this._renderPipelines[renderPipelineName]; if (pipeline.isSupported) { result.push(pipeline); } } } return result; } /** * Adds a pipeline to the manager * @param renderPipeline The pipeline to add */ addPipeline(renderPipeline) { this.removePipeline(renderPipeline._name); this._renderPipelines[renderPipeline._name] = renderPipeline; this._onNewPipelineAddedObservable.notifyObservers(renderPipeline); } /** * Remove the pipeline from the manager * @param renderPipelineName the name of the pipeline to remove */ removePipeline(renderPipelineName) { const pipeline = this._renderPipelines[renderPipelineName]; if (pipeline) { this._onPipelineRemovedObservable.notifyObservers(pipeline); delete this._renderPipelines[renderPipelineName]; } } /** * Attaches a camera to the pipeline * @param renderPipelineName The name of the pipeline to attach to * @param cameras the camera to attach * @param unique if the camera can be attached multiple times to the pipeline */ attachCamerasToRenderPipeline(renderPipelineName, cameras, unique = false) { const renderPipeline = this._renderPipelines[renderPipelineName]; if (!renderPipeline) { return; } renderPipeline._attachCameras(cameras, unique); } /** * Detaches a camera from the pipeline * @param renderPipelineName The name of the pipeline to detach from * @param cameras the camera to detach */ detachCamerasFromRenderPipeline(renderPipelineName, cameras) { const renderPipeline = this._renderPipelines[renderPipelineName]; if (!renderPipeline) { return; } renderPipeline._detachCameras(cameras); } /** * Enables an effect by name on a pipeline * @param renderPipelineName the name of the pipeline to enable the effect in * @param renderEffectName the name of the effect to enable * @param cameras the cameras that the effect should be enabled on */ enableEffectInPipeline(renderPipelineName, renderEffectName, cameras) { const renderPipeline = this._renderPipelines[renderPipelineName]; if (!renderPipeline) { return; } renderPipeline._enableEffect(renderEffectName, cameras); } /** * Disables an effect by name on a pipeline * @param renderPipelineName the name of the pipeline to disable the effect in * @param renderEffectName the name of the effect to disable * @param cameras the cameras that the effect should be disabled on */ disableEffectInPipeline(renderPipelineName, renderEffectName, cameras) { const renderPipeline = this._renderPipelines[renderPipelineName]; if (!renderPipeline) { return; } renderPipeline._disableEffect(renderEffectName, cameras); } /** * Updates the state of all contained render pipelines and disposes of any non supported pipelines */ update() { for (const renderPipelineName in this._renderPipelines) { if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) { const pipeline = this._renderPipelines[renderPipelineName]; if (!pipeline.isSupported) { pipeline.dispose(); delete this._renderPipelines[renderPipelineName]; } else { pipeline._update(); } } } } /** @internal */ _rebuild() { for (const renderPipelineName in this._renderPipelines) { if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) { const pipeline = this._renderPipelines[renderPipelineName]; pipeline._rebuild(); } } } /** * Disposes of the manager and pipelines */ dispose() { for (const renderPipelineName in this._renderPipelines) { if (Object.prototype.hasOwnProperty.call(this._renderPipelines, renderPipelineName)) { const pipeline = this._renderPipelines[renderPipelineName]; pipeline.dispose(); } } } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/RenderPipeline/postProcessRenderPipelineManagerSceneComponent.js init_sceneComponent(); init_scene(); Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", { get: /* @__PURE__ */ __name(function() { if (!this._postProcessRenderPipelineManager) { let component = this._getComponent(SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER); if (!component) { component = new PostProcessRenderPipelineManagerSceneComponent(this); this._addComponent(component); } this._postProcessRenderPipelineManager = new PostProcessRenderPipelineManager(); } return this._postProcessRenderPipelineManager; }, "get"), enumerable: true, configurable: true }); var PostProcessRenderPipelineManagerSceneComponent = class { static { __name(this, "PostProcessRenderPipelineManagerSceneComponent"); } /** * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ constructor(scene) { this.name = SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER; this.scene = scene; } /** * Registers the component in a given scene */ register() { this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets); } /** * Rebuilds the elements related to this component in case of * context lost for instance. */ rebuild() { if (this.scene._postProcessRenderPipelineManager) { this.scene._postProcessRenderPipelineManager._rebuild(); } } /** * Disposes the component and the associated resources */ dispose() { if (this.scene._postProcessRenderPipelineManager) { this.scene._postProcessRenderPipelineManager.dispose(); } } _gatherRenderTargets() { if (this.scene._postProcessRenderPipelineManager) { this.scene._postProcessRenderPipelineManager.update(); } } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssrRenderingPipeline.js init_tslib_es6(); init_decorators(); init_decorators_serialization(); init_postProcess(); init_typeStore(); init_depthRenderer(); var SSRRenderingPipeline = class _SSRRenderingPipeline extends PostProcessRenderPipeline { static { __name(this, "SSRRenderingPipeline"); } /** * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1) */ set samples(sampleCount) { if (this._samples === sampleCount) { return; } this._samples = sampleCount; if (this._ssrPostProcess) { this._ssrPostProcess.samples = this.samples; } } get samples() { return this._samples; } /** * Gets or sets the maxDistance used to define how far we look for reflection during the ray-marching on the reflected ray (default: 1000). * Note that this value is a view (camera) space distance (not pixels!). */ get maxDistance() { return this._thinSSRRenderingPipeline.maxDistance; } set maxDistance(distance) { this._thinSSRRenderingPipeline.maxDistance = distance; } /** * Gets or sets the step size used to iterate until the effect finds the color of the reflection's pixel. Should be an integer \>= 1 as it is the number of pixels we advance at each step (default: 1). * Use higher values to improve performances (but at the expense of quality). */ get step() { return this._thinSSRRenderingPipeline.step; } set step(step) { this._thinSSRRenderingPipeline.step = step; } /** * Gets or sets the thickness value used as tolerance when computing the intersection between the reflected ray and the scene (default: 0.5). * If setting "enableAutomaticThicknessComputation" to true, you can use lower values for "thickness" (even 0), as the geometry thickness * is automatically computed thank to the regular depth buffer + the backface depth buffer */ get thickness() { return this._thinSSRRenderingPipeline.thickness; } set thickness(thickness) { this._thinSSRRenderingPipeline.thickness = thickness; } /** * Gets or sets the current reflection strength. 1.0 is an ideal value but can be increased/decreased for particular results (default: 1). */ get strength() { return this._thinSSRRenderingPipeline.strength; } set strength(strength) { this._thinSSRRenderingPipeline.strength = strength; } /** * Gets or sets the falloff exponent used to compute the reflection strength. Higher values lead to fainter reflections (default: 1). */ get reflectionSpecularFalloffExponent() { return this._thinSSRRenderingPipeline.reflectionSpecularFalloffExponent; } set reflectionSpecularFalloffExponent(exponent) { this._thinSSRRenderingPipeline.reflectionSpecularFalloffExponent = exponent; } /** * Maximum number of steps during the ray marching process after which we consider an intersection could not be found (default: 1000). * Should be an integer value. */ get maxSteps() { return this._thinSSRRenderingPipeline.maxSteps; } set maxSteps(steps) { this._thinSSRRenderingPipeline.maxSteps = steps; } /** * Gets or sets the factor applied when computing roughness. Default value is 0.2. * When blurring based on roughness is enabled (meaning blurDispersionStrength \> 0), roughnessFactor is used as a global roughness factor applied on all objects. * If you want to disable this global roughness set it to 0. */ get roughnessFactor() { return this._thinSSRRenderingPipeline.roughnessFactor; } set roughnessFactor(factor) { this._thinSSRRenderingPipeline.roughnessFactor = factor; } /** * Number of steps to skip at start when marching the ray to avoid self collisions (default: 1) * 1 should normally be a good value, depending on the scene you may need to use a higher value (2 or 3) */ get selfCollisionNumSkip() { return this._thinSSRRenderingPipeline.selfCollisionNumSkip; } set selfCollisionNumSkip(skip) { this._thinSSRRenderingPipeline.selfCollisionNumSkip = skip; } /** * Gets or sets the minimum value for one of the reflectivity component of the material to consider it for SSR (default: 0.04). * If all r/g/b components of the reflectivity is below or equal this value, the pixel will not be considered reflective and SSR won't be applied. */ get reflectivityThreshold() { return this._thinSSRRenderingPipeline.reflectivityThreshold; } set reflectivityThreshold(threshold) { const currentThreshold = this.reflectivityThreshold; if (threshold === currentThreshold) { return; } this._thinSSRRenderingPipeline.reflectivityThreshold = threshold; if (threshold === 0 && currentThreshold !== 0 || threshold !== 0 && currentThreshold === 0) { this._buildPipeline(); } } /** * Gets or sets the downsample factor used to reduce the size of the texture used to compute the SSR contribution (default: 0). * Use 0 to render the SSR contribution at full resolution, 1 to render at half resolution, 2 to render at 1/3 resolution, etc. * Note that it is used only when blurring is enabled (blurDispersionStrength \> 0), because in that mode the SSR contribution is generated in a separate texture. */ get ssrDownsample() { return this._thinSSRRenderingPipeline.ssrDownsample; } set ssrDownsample(downsample) { this._thinSSRRenderingPipeline.ssrDownsample = downsample; this._buildPipeline(); } /** * Gets or sets the blur dispersion strength. Set this value to 0 to disable blurring (default: 0.03) * The reflections are blurred based on the roughness of the surface and the distance between the pixel shaded and the reflected pixel: the higher the distance the more blurry the reflection is. * blurDispersionStrength allows to increase or decrease this effect. */ get blurDispersionStrength() { return this._thinSSRRenderingPipeline.blurDispersionStrength; } set blurDispersionStrength(strength) { const currentStrength = this.blurDispersionStrength; if (strength === currentStrength) { return; } this._thinSSRRenderingPipeline.blurDispersionStrength = strength; if (strength === 0 && currentStrength !== 0 || strength !== 0 && currentStrength === 0) { this._buildPipeline(); } } _useBlur() { return this.blurDispersionStrength > 0; } /** * Gets or sets the downsample factor used to reduce the size of the textures used to blur the reflection effect (default: 0). * Use 0 to blur at full resolution, 1 to render at half resolution, 2 to render at 1/3 resolution, etc. */ get blurDownsample() { return this._thinSSRRenderingPipeline.blurDownsample; } set blurDownsample(downsample) { this._thinSSRRenderingPipeline.blurDownsample = downsample; this._buildPipeline(); } /** * Gets or sets whether or not smoothing reflections is enabled (default: false) * Enabling smoothing will require more GPU power. * Note that this setting has no effect if step = 1: it's only used if step \> 1. */ get enableSmoothReflections() { return this._thinSSRRenderingPipeline.enableSmoothReflections; } set enableSmoothReflections(enabled) { this._thinSSRRenderingPipeline.enableSmoothReflections = enabled; } get _useScreenspaceDepth() { return this._thinSSRRenderingPipeline.useScreenspaceDepth; } /** * Gets or sets the environment cube texture used to define the reflection when the reflected rays of SSR leave the view space or when the maxDistance/maxSteps is reached. */ get environmentTexture() { return this._thinSSRRenderingPipeline.environmentTexture; } set environmentTexture(texture) { this._thinSSRRenderingPipeline.environmentTexture = texture; } /** * Gets or sets the boolean defining if the environment texture is a standard cubemap (false) or a probe (true). Default value is false. * Note: a probe cube texture is treated differently than an ordinary cube texture because the Y axis is reversed. */ get environmentTextureIsProbe() { return this._thinSSRRenderingPipeline.environmentTextureIsProbe; } set environmentTextureIsProbe(isProbe) { this._thinSSRRenderingPipeline.environmentTextureIsProbe = isProbe; } /** * Gets or sets a boolean indicating if the reflections should be attenuated at the screen borders (default: true). */ get attenuateScreenBorders() { return this._thinSSRRenderingPipeline.attenuateScreenBorders; } set attenuateScreenBorders(attenuate) { this._thinSSRRenderingPipeline.attenuateScreenBorders = attenuate; } /** * Gets or sets a boolean indicating if the reflections should be attenuated according to the distance of the intersection (default: true). */ get attenuateIntersectionDistance() { return this._thinSSRRenderingPipeline.attenuateIntersectionDistance; } set attenuateIntersectionDistance(attenuate) { this._thinSSRRenderingPipeline.attenuateIntersectionDistance = attenuate; } /** * Gets or sets a boolean indicating if the reflections should be attenuated according to the number of iterations performed to find the intersection (default: true). */ get attenuateIntersectionIterations() { return this._thinSSRRenderingPipeline.attenuateIntersectionIterations; } set attenuateIntersectionIterations(attenuate) { this._thinSSRRenderingPipeline.attenuateIntersectionIterations = attenuate; } /** * Gets or sets a boolean indicating if the reflections should be attenuated when the reflection ray is facing the camera (the view direction) (default: false). */ get attenuateFacingCamera() { return this._thinSSRRenderingPipeline.attenuateFacingCamera; } set attenuateFacingCamera(attenuate) { this._thinSSRRenderingPipeline.attenuateFacingCamera = attenuate; } /** * Gets or sets a boolean indicating if the backface reflections should be attenuated (default: false). */ get attenuateBackfaceReflection() { return this._thinSSRRenderingPipeline.attenuateBackfaceReflection; } set attenuateBackfaceReflection(attenuate) { this._thinSSRRenderingPipeline.attenuateBackfaceReflection = attenuate; } /** * Gets or sets a boolean indicating if the ray should be clipped to the frustum (default: true). * You can try to set this parameter to false to save some performances: it may produce some artefacts in some cases, but generally they won't really be visible */ get clipToFrustum() { return this._thinSSRRenderingPipeline.clipToFrustum; } set clipToFrustum(clip) { this._thinSSRRenderingPipeline.clipToFrustum = clip; } /** * Gets or sets a boolean indicating whether the blending between the current color pixel and the reflection color should be done with a Fresnel coefficient (default: false). * It is more physically accurate to use the Fresnel coefficient (otherwise it uses the reflectivity of the material for blending), but it is also more expensive when you use blur (when blurDispersionStrength \> 0). */ get useFresnel() { return this._thinSSRRenderingPipeline.useFresnel; } set useFresnel(fresnel) { this._thinSSRRenderingPipeline.useFresnel = fresnel; this._buildPipeline(); } /** * Gets or sets a boolean defining if geometry thickness should be computed automatically (default: false). * When enabled, a depth renderer is created which will render the back faces of the scene to a depth texture (meaning additional work for the GPU). * In that mode, the "thickness" property is still used as an offset to compute the ray intersection, but you can typically use a much lower * value than when enableAutomaticThicknessComputation is false (it's even possible to use a value of 0 when using low values for "step") * Note that for performance reasons, this option will only apply to the first camera to which the rendering pipeline is attached! */ get enableAutomaticThicknessComputation() { return this._thinSSRRenderingPipeline.enableAutomaticThicknessComputation; } set enableAutomaticThicknessComputation(automatic) { this._thinSSRRenderingPipeline.enableAutomaticThicknessComputation = automatic; this._buildPipeline(); } /** * Gets the depth renderer used to render the back faces of the scene to a depth texture. */ get backfaceDepthRenderer() { return this._depthRenderer; } /** * Gets or sets the downsample factor (default: 0) used to create the backface depth texture - used only if enableAutomaticThicknessComputation = true. * Use 0 to render the depth at full resolution, 1 to render at half resolution, 2 to render at 1/4 resolution, etc. * Note that you will get rendering artefacts when using a value different from 0: it's a tradeoff between image quality and performances. */ get backfaceDepthTextureDownsample() { return this._backfaceDepthTextureDownsample; } set backfaceDepthTextureDownsample(factor) { if (this._backfaceDepthTextureDownsample === factor) { return; } this._backfaceDepthTextureDownsample = factor; this._resizeDepthRenderer(); } /** * Gets or sets a boolean (default: true) indicating if the depth of transparent meshes should be written to the backface depth texture (when automatic thickness computation is enabled). */ get backfaceForceDepthWriteTransparentMeshes() { return this._backfaceForceDepthWriteTransparentMeshes; } set backfaceForceDepthWriteTransparentMeshes(force) { if (this._backfaceForceDepthWriteTransparentMeshes === force) { return; } this._backfaceForceDepthWriteTransparentMeshes = force; if (this._depthRenderer) { this._depthRenderer.forceDepthWriteTransparentMeshes = force; } } /** * Gets or sets a boolean indicating if the effect is enabled (default: true). */ get isEnabled() { return this._isEnabled; } set isEnabled(value) { if (this._isEnabled === value) { return; } this._isEnabled = value; if (!value) { if (this._cameras !== null) { this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); this._cameras = this._camerasToBeAttached.slice(); } } else if (value) { if (!this._isDirty) { if (this._cameras !== null) { this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); } } else { this._buildPipeline(); } } } /** * Gets or sets a boolean defining if the input color texture is in gamma space (default: true) * The SSR effect works in linear space, so if the input texture is in gamma space, we must convert the texture to linear space before applying the effect */ get inputTextureColorIsInGammaSpace() { return this._thinSSRRenderingPipeline.inputTextureColorIsInGammaSpace; } set inputTextureColorIsInGammaSpace(gammaSpace) { this._thinSSRRenderingPipeline.inputTextureColorIsInGammaSpace = gammaSpace; this._buildPipeline(); } /** * Gets or sets a boolean defining if the output color texture generated by the SSR pipeline should be in gamma space (default: true) * If you have a post-process that comes after the SSR and that post-process needs the input to be in a linear space, you must disable generateOutputInGammaSpace */ get generateOutputInGammaSpace() { return this._thinSSRRenderingPipeline.generateOutputInGammaSpace; } set generateOutputInGammaSpace(gammaSpace) { this._thinSSRRenderingPipeline.generateOutputInGammaSpace = gammaSpace; this._buildPipeline(); } /** * Gets or sets a boolean indicating if the effect should be rendered in debug mode (default: false). * In this mode, colors have this meaning: * - blue: the ray hit the max distance (we reached maxDistance) * - red: the ray ran out of steps (we reached maxSteps) * - yellow: the ray went off screen * - green: the ray hit a surface. The brightness of the green color is proportional to the distance between the ray origin and the intersection point: A brighter green means more computation than a darker green. * In the first 3 cases, the final color is calculated by mixing the skybox color with the pixel color (if environmentTexture is defined), otherwise the pixel color is not modified * You should try to get as few blue/red/yellow pixels as possible, as this means that the ray has gone further than if it had hit a surface. */ get debug() { return this._thinSSRRenderingPipeline.debug; } set debug(value) { this._thinSSRRenderingPipeline.debug = value; this._buildPipeline(); } /** * Gets the scene the effect belongs to. * @returns the scene the effect belongs to. */ getScene() { return this._scene; } get _geometryBufferRenderer() { if (!this._forceGeometryBuffer) { return null; } return this._scene.geometryBufferRenderer; } get _prePassRenderer() { if (this._forceGeometryBuffer) { return null; } return this._scene.prePassRenderer; } /** * Gets active scene */ get scene() { return this._scene; } /** * Returns true if SSR is supported by the running hardware */ get isSupported() { const caps = this._scene.getEngine().getCaps(); return caps.drawBuffersExtension && caps.texelFetch; } /** * Constructor of the SSR rendering pipeline * @param name The rendering pipeline name * @param scene The scene linked to this pipeline * @param cameras The array of cameras that the rendering pipeline will be attached to (default: scene.cameras) * @param forceGeometryBuffer Set to true if you want to use the legacy geometry buffer renderer (default: false) * @param textureType The texture type used by the different post processes created by SSR (default: 0) * @param useScreenspaceDepth Indicates if the depth buffer should be linear or screenspace (default: false). This allows sharing the buffer with other effect pipelines that may require the depth to be in screenspace. */ constructor(name260, scene, cameras, forceGeometryBuffer = false, textureType = 0, useScreenspaceDepth = false) { super(scene.getEngine(), name260); this.SSRRenderEffect = "SSRRenderEffect"; this.SSRBlurRenderEffect = "SSRBlurRenderEffect"; this.SSRCombineRenderEffect = "SSRCombineRenderEffect"; this._samples = 1; this._backfaceDepthTextureDownsample = 0; this._backfaceForceDepthWriteTransparentMeshes = true; this._isEnabled = true; this._forceGeometryBuffer = false; this._isDirty = false; this._camerasToBeAttached = []; this._thinSSRRenderingPipeline = new ThinSSRRenderingPipeline(name260, scene); this._thinSSRRenderingPipeline.isSSRSupported = false; this._thinSSRRenderingPipeline.useScreenspaceDepth = useScreenspaceDepth; this._cameras = cameras || scene.cameras; this._cameras = this._cameras.slice(); this._camerasToBeAttached = this._cameras.slice(); this._scene = scene; this._textureType = textureType; this._forceGeometryBuffer = forceGeometryBuffer; if (this.isSupported) { this._createSSRPostProcess(); scene.postProcessRenderPipelineManager.addPipeline(this); if (this._forceGeometryBuffer) { const geometryBufferRenderer = scene.enableGeometryBufferRenderer(); if (geometryBufferRenderer) { geometryBufferRenderer.enableReflectivity = true; geometryBufferRenderer.useSpecificClearForDepthTexture = true; geometryBufferRenderer.enableScreenspaceDepth = this._useScreenspaceDepth; geometryBufferRenderer.enableDepth = !this._useScreenspaceDepth; } } else { const prePassRenderer = scene.enablePrePassRenderer(); if (prePassRenderer) { prePassRenderer.useSpecificClearForDepthTexture = true; prePassRenderer.markAsDirty(); } } this._thinSSRRenderingPipeline.isSSRSupported = !!this._geometryBufferRenderer || !!this._prePassRenderer; this._buildPipeline(); } } /** * Get the class name * @returns "SSRRenderingPipeline" */ getClassName() { return "SSRRenderingPipeline"; } /** * Adds a camera to the pipeline * @param camera the camera to be added */ addCamera(camera) { this._camerasToBeAttached.push(camera); this._buildPipeline(); } /** * Removes a camera from the pipeline * @param camera the camera to remove */ removeCamera(camera) { const index = this._camerasToBeAttached.indexOf(camera); this._camerasToBeAttached.splice(index, 1); this._buildPipeline(); } /** * Removes the internal pipeline assets and detaches the pipeline from the scene cameras * @param disableGeometryBufferRenderer if the geometry buffer renderer should be disabled */ dispose(disableGeometryBufferRenderer = false) { this._disposeDepthRenderer(); this._disposeSSRPostProcess(); this._disposeBlurPostProcesses(); if (disableGeometryBufferRenderer) { this._scene.disableGeometryBufferRenderer(); } this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); this._scene.postProcessRenderPipelineManager.removePipeline(this._name); this._thinSSRRenderingPipeline.dispose(); super.dispose(); } _getTextureSize() { const engine = this._scene.getEngine(); const prePassRenderer = this._prePassRenderer; let textureSize = { width: engine.getRenderWidth(), height: engine.getRenderHeight() }; if (prePassRenderer && this._scene.activeCamera?._getFirstPostProcess() === this._ssrPostProcess) { const renderTarget = prePassRenderer.getRenderTarget(); if (renderTarget && renderTarget.textures) { textureSize = renderTarget.textures[prePassRenderer.getIndex(4)].getSize(); } } else if (this._ssrPostProcess?.inputTexture) { textureSize.width = this._ssrPostProcess.inputTexture.width; textureSize.height = this._ssrPostProcess.inputTexture.height; } return textureSize; } _buildPipeline() { if (!this.isSupported) { return; } if (!this._isEnabled) { this._isDirty = true; return; } this._isDirty = false; const engine = this._scene.getEngine(); this._disposeDepthRenderer(); if (this._cameras !== null) { this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); this._cameras = this._camerasToBeAttached.slice(); if (this._cameras.length > 0) { this._thinSSRRenderingPipeline.camera = this._cameras[0]; } } this._reset(); this._thinSSRRenderingPipeline.normalsAreInWorldSpace = !!(this._geometryBufferRenderer?.generateNormalsInWorldSpace ?? this._prePassRenderer?.generateNormalsInWorldSpace); if (this.enableAutomaticThicknessComputation) { const camera = this._cameras?.[0]; if (camera) { this._depthRendererCamera = camera; this._depthRenderer = new DepthRenderer(this._scene, void 0, void 0, this._useScreenspaceDepth, 1, !this._useScreenspaceDepth, "SSRBackDepth"); this._depthRenderer.reverseCulling = true; this._depthRenderer.forceDepthWriteTransparentMeshes = this.backfaceForceDepthWriteTransparentMeshes; this._resizeDepthRenderer(); camera.customRenderTargets.push(this._depthRenderer.getDepthMap()); } } this.addEffect(new PostProcessRenderEffect(engine, this.SSRRenderEffect, () => { return this._ssrPostProcess; }, true)); this._disposeBlurPostProcesses(); if (this._useBlur()) { this._createBlurAndCombinerPostProcesses(); this.addEffect(new PostProcessRenderEffect(engine, this.SSRBlurRenderEffect, () => { return [this._blurPostProcessX, this._blurPostProcessY]; }, true)); this.addEffect(new PostProcessRenderEffect(engine, this.SSRCombineRenderEffect, () => { return this._blurCombinerPostProcess; }, true)); } if (this._cameras !== null) { this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); } } _resizeDepthRenderer() { if (!this._depthRenderer) { return; } const textureSize = this._getTextureSize(); const depthRendererSize = this._depthRenderer.getDepthMap().getSize(); const width = Math.floor(textureSize.width / (this.backfaceDepthTextureDownsample + 1)); const height = Math.floor(textureSize.height / (this.backfaceDepthTextureDownsample + 1)); if (depthRendererSize.width !== width || depthRendererSize.height !== height) { this._depthRenderer.getDepthMap().resize({ width, height }); } } _disposeDepthRenderer() { if (this._depthRenderer) { if (this._depthRendererCamera) { const idx = this._depthRendererCamera.customRenderTargets.indexOf(this._depthRenderer.getDepthMap()) ?? -1; if (idx !== -1) { this._depthRendererCamera.customRenderTargets.splice(idx, 1); } } this._depthRendererCamera = null; this._depthRenderer.getDepthMap().dispose(); } this._depthRenderer = null; } _disposeBlurPostProcesses() { for (let i = 0; i < this._cameras.length; i++) { const camera = this._cameras[i]; this._blurPostProcessX?.dispose(camera); this._blurPostProcessY?.dispose(camera); this._blurCombinerPostProcess?.dispose(camera); } this._blurPostProcessX = null; this._blurPostProcessY = null; this._blurCombinerPostProcess = null; } _disposeSSRPostProcess() { for (let i = 0; i < this._cameras.length; i++) { const camera = this._cameras[i]; this._ssrPostProcess?.dispose(camera); } this._ssrPostProcess = null; } _createSSRPostProcess() { this._ssrPostProcess = new PostProcess("ssr", ThinSSRPostProcess.FragmentUrl, { uniformNames: ThinSSRPostProcess.Uniforms, samplerNames: ThinSSRPostProcess.Samplers, size: 1, samplingMode: 2, engine: this._scene.getEngine(), textureType: this._textureType, effectWrapper: this._thinSSRRenderingPipeline._ssrPostProcess }); this._ssrPostProcess.onApply = (effect) => { this._resizeDepthRenderer(); const geometryBufferRenderer = this._geometryBufferRenderer; const prePassRenderer = this._prePassRenderer; if (!prePassRenderer && !geometryBufferRenderer) { return; } if (geometryBufferRenderer) { const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE); const normalIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.NORMAL_TEXTURE_TYPE); effect.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[normalIndex]); effect.setTexture("reflectivitySampler", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]); if (this._useScreenspaceDepth) { const depthIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE); effect.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[depthIndex]); } else { const depthIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE); effect.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[depthIndex]); } } else if (prePassRenderer) { const depthIndex = prePassRenderer.getIndex(this._useScreenspaceDepth ? 10 : 5); const roughnessIndex = prePassRenderer.getIndex(3); const normalIndex = prePassRenderer.getIndex(6); effect.setTexture("normalSampler", prePassRenderer.getRenderTarget().textures[normalIndex]); effect.setTexture("depthSampler", prePassRenderer.getRenderTarget().textures[depthIndex]); effect.setTexture("reflectivitySampler", prePassRenderer.getRenderTarget().textures[roughnessIndex]); } if (this.enableAutomaticThicknessComputation && this._depthRenderer) { effect.setTexture("backDepthSampler", this._depthRenderer.getDepthMap()); effect.setFloat("backSizeFactor", this.backfaceDepthTextureDownsample + 1); } const textureSize = this._getTextureSize(); this._thinSSRRenderingPipeline._ssrPostProcess.textureWidth = textureSize.width; this._thinSSRRenderingPipeline._ssrPostProcess.textureHeight = textureSize.height; }; this._ssrPostProcess.samples = this.samples; if (!this._forceGeometryBuffer) { this._ssrPostProcess._prePassEffectConfiguration = new ScreenSpaceReflections2Configuration(this._useScreenspaceDepth); } } _createBlurAndCombinerPostProcesses() { const engine = this._scene.getEngine(); this._blurPostProcessX = new PostProcess("SSRblurX", ThinSSRBlurPostProcess.FragmentUrl, { uniformNames: ThinSSRBlurPostProcess.Uniforms, samplerNames: ThinSSRBlurPostProcess.Samplers, size: 1 / (this.ssrDownsample + 1), samplingMode: 2, engine, textureType: this._textureType, effectWrapper: this._thinSSRRenderingPipeline._ssrBlurXPostProcess }); this._blurPostProcessX.autoClear = false; this._blurPostProcessX.onApplyObservable.add(() => { this._thinSSRRenderingPipeline._ssrBlurXPostProcess.textureWidth = this._blurPostProcessX?.inputTexture.width ?? this._scene.getEngine().getRenderWidth(); this._thinSSRRenderingPipeline._ssrBlurXPostProcess.textureHeight = 1; }); this._blurPostProcessY = new PostProcess("SSRblurY", ThinSSRBlurPostProcess.FragmentUrl, { uniformNames: ThinSSRBlurPostProcess.Uniforms, samplerNames: ThinSSRBlurPostProcess.Samplers, size: 1 / (this.blurDownsample + 1), samplingMode: 2, engine, textureType: this._textureType, effectWrapper: this._thinSSRRenderingPipeline._ssrBlurYPostProcess }); this._blurPostProcessY.autoClear = false; this._blurPostProcessY.onApplyObservable.add(() => { this._thinSSRRenderingPipeline._ssrBlurYPostProcess.textureWidth = 1; this._thinSSRRenderingPipeline._ssrBlurYPostProcess.textureHeight = this._blurPostProcessY?.inputTexture.height ?? this._scene.getEngine().getRenderHeight(); }); this._blurCombinerPostProcess = new PostProcess("SSRblurCombiner", ThinSSRBlurCombinerPostProcess.FragmentUrl, { uniformNames: ThinSSRBlurCombinerPostProcess.Uniforms, samplerNames: ThinSSRBlurCombinerPostProcess.Samplers, size: 1 / (this.blurDownsample + 1), samplingMode: 1, engine, textureType: this._textureType, effectWrapper: this._thinSSRRenderingPipeline._ssrBlurCombinerPostProcess }); this._blurCombinerPostProcess.autoClear = false; this._blurCombinerPostProcess.onApplyObservable.add((effect) => { const geometryBufferRenderer = this._geometryBufferRenderer; const prePassRenderer = this._prePassRenderer; if (!prePassRenderer && !geometryBufferRenderer) { return; } if (prePassRenderer && this._scene.activeCamera?._getFirstPostProcess() === this._ssrPostProcess) { const renderTarget = prePassRenderer.getRenderTarget(); if (renderTarget && renderTarget.textures) { effect.setTexture("mainSampler", renderTarget.textures[prePassRenderer.getIndex(4)]); } } else { effect.setTextureFromPostProcess("mainSampler", this._ssrPostProcess); } if (geometryBufferRenderer) { const roughnessIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.REFLECTIVITY_TEXTURE_TYPE); effect.setTexture("reflectivitySampler", geometryBufferRenderer.getGBuffer().textures[roughnessIndex]); if (this.useFresnel) { effect.setTexture("normalSampler", geometryBufferRenderer.getGBuffer().textures[1]); if (this._useScreenspaceDepth) { const depthIndex = geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.SCREENSPACE_DEPTH_TEXTURE_TYPE); effect.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[depthIndex]); } else { effect.setTexture("depthSampler", geometryBufferRenderer.getGBuffer().textures[0]); } } } else if (prePassRenderer) { const roughnessIndex = prePassRenderer.getIndex(3); effect.setTexture("reflectivitySampler", prePassRenderer.getRenderTarget().textures[roughnessIndex]); if (this.useFresnel) { const depthIndex = prePassRenderer.getIndex(this._useScreenspaceDepth ? 10 : 5); const normalIndex = prePassRenderer.getIndex(6); effect.setTexture("normalSampler", prePassRenderer.getRenderTarget().textures[normalIndex]); effect.setTexture("depthSampler", prePassRenderer.getRenderTarget().textures[depthIndex]); } } }); } /** * Serializes the rendering pipeline (Used when exporting) * @returns the serialized object */ serialize() { const serializationObject = SerializationHelper.Serialize(this); serializationObject.customType = "SSRRenderingPipeline"; return serializationObject; } /** * Parse the serialized pipeline * @param source Source pipeline. * @param scene The scene to load the pipeline to. * @param rootUrl The URL of the serialized pipeline. * @returns An instantiated pipeline from the serialized object. */ static Parse(source, scene, rootUrl) { return SerializationHelper.Parse(() => new _SSRRenderingPipeline(source._name, scene, source._ratio), source, scene, rootUrl); } }; __decorate([ serialize() ], SSRRenderingPipeline.prototype, "samples", null); __decorate([ serialize() ], SSRRenderingPipeline.prototype, "maxDistance", null); __decorate([ serialize() ], SSRRenderingPipeline.prototype, "step", null); __decorate([ serialize() ], SSRRenderingPipeline.prototype, "thickness", null); __decorate([ serialize() ], SSRRenderingPipeline.prototype, "strength", null); __decorate([ serialize() ], SSRRenderingPipeline.prototype, "reflectionSpecularFalloffExponent", null); __decorate([ serialize() ], SSRRenderingPipeline.prototype, "maxSteps", null); __decorate([ serialize() ], SSRRenderingPipeline.prototype, "roughnessFactor", null); __decorate([ serialize() ], SSRRenderingPipeline.prototype, "selfCollisionNumSkip", null); __decorate([ serialize() ], SSRRenderingPipeline.prototype, "reflectivityThreshold", null); __decorate([ serialize() ], SSRRenderingPipeline.prototype, "ssrDownsample", null); __decorate([ serialize("blurDispersionStrength") ], SSRRenderingPipeline.prototype, "blurDispersionStrength", null); __decorate([ serialize("blurDownsample") ], SSRRenderingPipeline.prototype, "blurDownsample", null); __decorate([ serialize("enableSmoothReflections") ], SSRRenderingPipeline.prototype, "enableSmoothReflections", null); __decorate([ serialize("environmentTexture") ], SSRRenderingPipeline.prototype, "environmentTexture", null); __decorate([ serialize("environmentTextureIsProbe") ], SSRRenderingPipeline.prototype, "environmentTextureIsProbe", null); __decorate([ serialize("attenuateScreenBorders") ], SSRRenderingPipeline.prototype, "attenuateScreenBorders", null); __decorate([ serialize("attenuateIntersectionDistance") ], SSRRenderingPipeline.prototype, "attenuateIntersectionDistance", null); __decorate([ serialize("attenuateIntersectionIterations") ], SSRRenderingPipeline.prototype, "attenuateIntersectionIterations", null); __decorate([ serialize("attenuateFacingCamera") ], SSRRenderingPipeline.prototype, "attenuateFacingCamera", null); __decorate([ serialize("attenuateBackfaceReflection") ], SSRRenderingPipeline.prototype, "attenuateBackfaceReflection", null); __decorate([ serialize("clipToFrustum") ], SSRRenderingPipeline.prototype, "clipToFrustum", null); __decorate([ serialize("useFresnel") ], SSRRenderingPipeline.prototype, "useFresnel", null); __decorate([ serialize("enableAutomaticThicknessComputation") ], SSRRenderingPipeline.prototype, "enableAutomaticThicknessComputation", null); __decorate([ serialize("backfaceDepthTextureDownsample") ], SSRRenderingPipeline.prototype, "_backfaceDepthTextureDownsample", void 0); __decorate([ serialize("backfaceForceDepthWriteTransparentMeshes") ], SSRRenderingPipeline.prototype, "_backfaceForceDepthWriteTransparentMeshes", void 0); __decorate([ serialize("isEnabled") ], SSRRenderingPipeline.prototype, "_isEnabled", void 0); __decorate([ serialize("inputTextureColorIsInGammaSpace") ], SSRRenderingPipeline.prototype, "inputTextureColorIsInGammaSpace", null); __decorate([ serialize("generateOutputInGammaSpace") ], SSRRenderingPipeline.prototype, "generateOutputInGammaSpace", null); __decorate([ serialize("debug") ], SSRRenderingPipeline.prototype, "debug", null); RegisterClass("BABYLON.SSRRenderingPipeline", SSRRenderingPipeline); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/rendering/ssr.js var ssrRenderingPipeline = null; var ssrRenderingPipelineCameraConfigurations = /* @__PURE__ */ new Map(); function getSSRRenderingPipeline() { return ssrRenderingPipeline; } __name(getSSRRenderingPipeline, "getSSRRenderingPipeline"); function setSSRRenderingPipelineRef(pipeline) { ssrRenderingPipeline = pipeline; } __name(setSSRRenderingPipelineRef, "setSSRRenderingPipelineRef"); function disposeSSRRenderingPipeline() { if (ssrRenderingPipeline) { ssrRenderingPipeline.dispose(); ssrRenderingPipeline = null; } } __name(disposeSSRRenderingPipeline, "disposeSSRRenderingPipeline"); function createSSRRenderingPipeline(scene, camera) { ssrRenderingPipeline = new SSRRenderingPipeline("SSRRenderingPipeline", scene, [camera]); ssrRenderingPipeline.samples = 4; return ssrRenderingPipeline; } __name(createSSRRenderingPipeline, "createSSRRenderingPipeline"); function serializeSSRRenderingPipeline() { if (!ssrRenderingPipeline) { return null; } return { samples: ssrRenderingPipeline.samples, step: ssrRenderingPipeline.step, thickness: ssrRenderingPipeline.thickness, strength: ssrRenderingPipeline.strength, reflectionSpecularFalloffExponent: ssrRenderingPipeline.reflectionSpecularFalloffExponent, maxSteps: ssrRenderingPipeline.maxSteps, maxDistance: ssrRenderingPipeline.maxDistance, roughnessFactor: ssrRenderingPipeline.roughnessFactor, reflectivityThreshold: ssrRenderingPipeline.reflectivityThreshold, blurDispersionStrehgth: ssrRenderingPipeline.blurDispersionStrength, clipToFrustum: ssrRenderingPipeline.clipToFrustum, enableSmoothReflections: ssrRenderingPipeline.enableSmoothReflections, enableAutomaticThicknessComputation: ssrRenderingPipeline.enableAutomaticThicknessComputation, attenuateFacingCamera: ssrRenderingPipeline.attenuateFacingCamera, attenuateScreenBorders: ssrRenderingPipeline.attenuateScreenBorders, attenuateIntersectionDistance: ssrRenderingPipeline.attenuateIntersectionDistance, attenuateBackfaceReflection: ssrRenderingPipeline.attenuateBackfaceReflection, blurDownsample: ssrRenderingPipeline.blurDownsample, selfCollisionNumSkip: ssrRenderingPipeline.selfCollisionNumSkip, ssrDownsample: ssrRenderingPipeline.ssrDownsample, backfaceDepthTextureDownsample: ssrRenderingPipeline.backfaceDepthTextureDownsample }; } __name(serializeSSRRenderingPipeline, "serializeSSRRenderingPipeline"); function parseSSRRenderingPipeline(scene, camera, data) { if (ssrRenderingPipeline) { return ssrRenderingPipeline; } const pipeline = createSSRRenderingPipeline(scene, camera); pipeline.samples = data.samples; pipeline.step = data.step; pipeline.thickness = data.thickness; pipeline.strength = data.strength; pipeline.reflectionSpecularFalloffExponent = data.reflectionSpecularFalloffExponent; pipeline.maxSteps = data.maxSteps; pipeline.maxDistance = data.maxDistance; pipeline.roughnessFactor = data.roughnessFactor; pipeline.reflectivityThreshold = data.reflectivityThreshold; pipeline.blurDispersionStrength = data.blurDispersionStrehgth; pipeline.clipToFrustum = data.clipToFrustum; pipeline.enableSmoothReflections = data.enableSmoothReflections; pipeline.enableAutomaticThicknessComputation = data.enableAutomaticThicknessComputation; pipeline.attenuateFacingCamera = data.attenuateFacingCamera; pipeline.attenuateScreenBorders = data.attenuateScreenBorders; pipeline.attenuateIntersectionDistance = data.attenuateIntersectionDistance; pipeline.attenuateBackfaceReflection = data.attenuateBackfaceReflection; pipeline.blurDownsample = data.blurDownsample; pipeline.selfCollisionNumSkip = data.selfCollisionNumSkip; pipeline.ssrDownsample = data.ssrDownsample; pipeline.backfaceDepthTextureDownsample = data.backfaceDepthTextureDownsample; return pipeline; } __name(parseSSRRenderingPipeline, "parseSSRRenderingPipeline"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/ssao2Configuration.js var SSAO2Configuration = class { static { __name(this, "SSAO2Configuration"); } constructor() { this.enabled = false; this.name = "ssao2"; this.texturesRequired = [6, 5]; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/rawTexture.js init_texture(); var RawTexture = class _RawTexture extends Texture { static { __name(this, "RawTexture"); } /** * Instantiates a new RawTexture. * Raw texture can help creating a texture directly from an array of data. * This can be super useful if you either get the data from an uncompressed source or * if you wish to create your texture pixel by pixel. * @param data define the array of data to use to create the texture (null to create an empty texture) * @param width define the width of the texture * @param height define the height of the texture * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx) * @param sceneOrEngine defines the scene or engine the texture will belong to * @param generateMipMaps define whether mip maps should be generated or not * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). * @param waitDataToBeReady If set to true Rawtexture will wait data to be set in order to be flaged as ready. */ constructor(data, width, height, format, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags, useSRGBBuffer, waitDataToBeReady) { super(null, sceneOrEngine, !generateMipMaps, invertY, void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0, creationFlags); this.format = format; if (!this._engine) { return; } if (!this._engine._caps.textureFloatLinearFiltering && type === 1) { samplingMode = 1; } if (!this._engine._caps.textureHalfFloatLinearFiltering && type === 2) { samplingMode = 1; } this._texture = this._engine.createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type, creationFlags ?? 0, useSRGBBuffer ?? false); this.wrapU = Texture.CLAMP_ADDRESSMODE; this.wrapV = Texture.CLAMP_ADDRESSMODE; this._waitingForData = !!waitDataToBeReady && !data; } /** * Updates the texture underlying data. * @param data Define the new data of the texture */ update(data) { this._getEngine().updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, null, this._texture.type, this._texture._useSRGBBuffer); this._waitingForData = false; } /** * Clones the texture. * @returns the cloned texture */ clone() { if (!this._texture) { return super.clone(); } const rawTexture = new _RawTexture(null, this.getSize().width, this.getSize().height, this.format, this.getScene(), this._texture.generateMipMaps, this._invertY, this.samplingMode, this._texture.type, this._texture._creationFlags, this._useSRGBBuffer); rawTexture._texture = this._texture; this._texture.incrementReferences(); return rawTexture; } isReady() { return super.isReady() && !this._waitingForData; } /** * Creates a luminance texture from some data. * @param data Define the texture data * @param width Define the width of the texture * @param height Define the height of the texture * @param sceneOrEngine defines the scene or engine the texture will belong to * @param generateMipMaps Define whether or not to create mip maps for the texture * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @returns the luminance texture */ static CreateLuminanceTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) { return new _RawTexture(data, width, height, 1, sceneOrEngine, generateMipMaps, invertY, samplingMode); } /** * Creates a luminance alpha texture from some data. * @param data Define the texture data * @param width Define the width of the texture * @param height Define the height of the texture * @param sceneOrEngine defines the scene or engine the texture will belong to * @param generateMipMaps Define whether or not to create mip maps for the texture * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @returns the luminance alpha texture */ static CreateLuminanceAlphaTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) { return new _RawTexture(data, width, height, 2, sceneOrEngine, generateMipMaps, invertY, samplingMode); } /** * Creates an alpha texture from some data. * @param data Define the texture data * @param width Define the width of the texture * @param height Define the height of the texture * @param sceneOrEngine defines the scene or engine the texture will belong to * @param generateMipMaps Define whether or not to create mip maps for the texture * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @returns the alpha texture */ static CreateAlphaTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3) { return new _RawTexture(data, width, height, 0, sceneOrEngine, generateMipMaps, invertY, samplingMode); } /** * Creates a RGB texture from some data. * @param data Define the texture data * @param width Define the width of the texture * @param height Define the height of the texture * @param sceneOrEngine defines the scene or engine the texture will belong to * @param generateMipMaps Define whether or not to create mip maps for the texture * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). * @returns the RGB alpha texture */ static CreateRGBTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags = 0, useSRGBBuffer = false) { return new _RawTexture(data, width, height, 4, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, creationFlags, useSRGBBuffer); } /** * Creates a RGBA texture from some data. * @param data Define the texture data * @param width Define the width of the texture * @param height Define the height of the texture * @param sceneOrEngine defines the scene or engine the texture will belong to * @param generateMipMaps Define whether or not to create mip maps for the texture * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) * @param creationFlags specific flags to use when creating the texture (1 for storage textures, for eg) * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). * @param waitDataToBeReady if set to true this will force texture to wait for data to be set before it is considered ready. * @returns the RGBA texture */ static CreateRGBATexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, creationFlags = 0, useSRGBBuffer = false, waitDataToBeReady = false) { return new _RawTexture(data, width, height, 5, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, creationFlags, useSRGBBuffer, waitDataToBeReady); } /** * Creates a RGBA storage texture from some data. * @param data Define the texture data * @param width Define the width of the texture * @param height Define the height of the texture * @param sceneOrEngine defines the scene or engine the texture will belong to * @param generateMipMaps Define whether or not to create mip maps for the texture * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) * @param useSRGBBuffer defines if the texture must be loaded in a sRGB GPU buffer (if supported by the GPU). * @returns the RGBA texture */ static CreateRGBAStorageTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = 3, type = 0, useSRGBBuffer = false) { return new _RawTexture(data, width, height, 5, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, 1, useSRGBBuffer); } /** * Creates a R texture from some data. * @param data Define the texture data * @param width Define the width of the texture * @param height Define the height of the texture * @param sceneOrEngine defines the scene or engine the texture will belong to * @param generateMipMaps Define whether or not to create mip maps for the texture * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) * @returns the R texture */ static CreateRTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, type = 1) { return new _RawTexture(data, width, height, 6, sceneOrEngine, generateMipMaps, invertY, samplingMode, type); } /** * Creates a R storage texture from some data. * @param data Define the texture data * @param width Define the width of the texture * @param height Define the height of the texture * @param sceneOrEngine defines the scene or engine the texture will belong to * @param generateMipMaps Define whether or not to create mip maps for the texture * @param invertY define if the data should be flipped on Y when uploaded to the GPU * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE) * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx) * @returns the R texture */ // eslint-disable-next-line @typescript-eslint/naming-convention static CreateRStorageTexture(data, width, height, sceneOrEngine, generateMipMaps = true, invertY = false, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, type = 1) { return new _RawTexture(data, width, height, 6, sceneOrEngine, generateMipMaps, invertY, samplingMode, type, 1); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinSSAO2PostProcess.js init_effectRenderer(); init_math_vector(); init_camera(); init_math_scalar_functions(); init_texture(); var ThinSSAO2PostProcess = class _ThinSSAO2PostProcess extends EffectWrapper { static { __name(this, "ThinSSAO2PostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_ssao2_fragment(), ssao2_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_ssao2_fragment2(), ssao2_fragment_exports2))); } } get textureWidth() { return this._textureWidth; } set textureWidth(width) { if (this._textureWidth === width) { return; } this._textureWidth = width; } get textureHeight() { return this._textureHeight; } set textureHeight(height) { if (this._textureHeight === height) { return; } this._textureHeight = height; } set samples(n) { this._samples = n; this.updateEffect(this._getDefinesForSSAO()); this._sampleSphere = this._generateHemisphere(); } get samples() { return this._samples; } set epsilon(n) { this._epsilon = n; this.updateEffect(this._getDefinesForSSAO()); } get epsilon() { return this._epsilon; } constructor(name260, scene, options) { super({ ...options, name: name260, engine: scene.getEngine(), useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinSSAO2PostProcess.FragmentUrl, uniforms: _ThinSSAO2PostProcess.Uniforms, samplers: _ThinSSAO2PostProcess.Samplers, defines: `#define SSAO #define SAMPLES 8 #define EPSILON 0.0001`, shaderLanguage: scene.getEngine().isWebGPU ? 1 : 0 }); this.camera = null; this._textureWidth = 0; this._textureHeight = 0; this._samples = 8; this.totalStrength = 1; this.radius = 2; this.maxZ = 100; this.minZAspect = 0.2; this.base = 0; this._epsilon = 0.02; this._bits = new Uint32Array(1); this._scene = scene; this._createRandomTexture(); this.updateEffect(this._getDefinesForSSAO()); this._sampleSphere = this._generateHemisphere(); } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); const effect = this._drawWrapper.effect; const camera = this.camera; if (!camera) { return; } const projectionMatrix = camera.getProjectionMatrix(); effect.setArray3("sampleSphere", this._sampleSphere); effect.setFloat("randTextureTiles", 32); effect.setFloat("samplesFactor", 1 / this.samples); effect.setFloat("totalStrength", this.totalStrength); effect.setFloat2("texelSize", 1 / this.textureWidth, 1 / this.textureHeight); effect.setFloat("radius", this.radius); effect.setFloat("maxZ", this.maxZ); effect.setFloat("minZAspect", this.minZAspect); effect.setFloat("base", this.base); effect.setFloat("near", camera.minZ); if (camera.mode === Camera.PERSPECTIVE_CAMERA) { effect.setMatrix3x3("depthProjection", _ThinSSAO2PostProcess.PERSPECTIVE_DEPTH_PROJECTION); effect.setFloat("xViewport", Math.tan(camera.fov / 2) * this._scene.getEngine().getAspectRatio(camera, true)); effect.setFloat("yViewport", Math.tan(camera.fov / 2)); } else { const halfWidth = this._scene.getEngine().getRenderWidth() / 2; const halfHeight = this._scene.getEngine().getRenderHeight() / 2; const orthoLeft = camera.orthoLeft ?? -halfWidth; const orthoRight = camera.orthoRight ?? halfWidth; const orthoBottom = camera.orthoBottom ?? -halfHeight; const orthoTop = camera.orthoTop ?? halfHeight; effect.setMatrix3x3("depthProjection", _ThinSSAO2PostProcess.ORTHO_DEPTH_PROJECTION); effect.setFloat4("viewport", orthoLeft, orthoRight, orthoBottom, orthoTop); } effect.setMatrix("projection", projectionMatrix); effect.setTexture("randomSampler", this._randomTexture); } dispose() { this._randomTexture.dispose(); super.dispose(); } _createRandomTexture() { const size = 128; const data = new Uint8Array(size * size * 4); const randVector = Vector2.Zero(); for (let index = 0; index < data.length; ) { randVector.set(RandomRange(0, 1), RandomRange(0, 1)).normalize().scaleInPlace(255); data[index++] = Math.floor(randVector.x); data[index++] = Math.floor(randVector.y); data[index++] = 0; data[index++] = 255; } const texture = RawTexture.CreateRGBATexture(data, size, size, this._scene, false, false, 2); texture.name = "SSAORandomTexture"; texture.wrapU = Texture.WRAP_ADDRESSMODE; texture.wrapV = Texture.WRAP_ADDRESSMODE; this._randomTexture = texture; } //Van der Corput radical inverse _radicalInverseVdC(i) { this._bits[0] = i; this._bits[0] = (this._bits[0] << 16 | this._bits[0] >> 16) >>> 0; this._bits[0] = (this._bits[0] & 1431655765) << 1 | (this._bits[0] & 2863311530) >>> 1 >>> 0; this._bits[0] = (this._bits[0] & 858993459) << 2 | (this._bits[0] & 3435973836) >>> 2 >>> 0; this._bits[0] = (this._bits[0] & 252645135) << 4 | (this._bits[0] & 4042322160) >>> 4 >>> 0; this._bits[0] = (this._bits[0] & 16711935) << 8 | (this._bits[0] & 4278255360) >>> 8 >>> 0; return this._bits[0] * 23283064365386963e-26; } _hammersley(i, n) { return [i / n, this._radicalInverseVdC(i)]; } _hemisphereSampleUniform(u, v) { const phi = v * 2 * Math.PI; const cosTheta = 1 - u * 0.85; const sinTheta = Math.sqrt(1 - cosTheta * cosTheta); return new Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta); } _generateHemisphere() { const numSamples = this.samples; const result = []; let vector; let i = 0; while (i < numSamples) { if (numSamples < 16) { vector = this._hemisphereSampleUniform(Math.random(), Math.random()); } else { const rand = this._hammersley(i, numSamples); vector = this._hemisphereSampleUniform(rand[0], rand[1]); } result.push(vector.x, vector.y, vector.z); i++; } return result; } _getDefinesForSSAO() { let defines = `#define SSAO #define SAMPLES ${this.samples} #define EPSILON ${this.epsilon.toFixed(4)}`; if (this.camera?.mode === Camera.ORTHOGRAPHIC_CAMERA) { defines += ` #define ORTHOGRAPHIC_CAMERA`; } return defines; } }; ThinSSAO2PostProcess.ORTHO_DEPTH_PROJECTION = [1, 0, 0, 0, 1, 0, 0, 0, 1]; ThinSSAO2PostProcess.PERSPECTIVE_DEPTH_PROJECTION = [0, 0, 0, 0, 0, 0, 1, 1, 1]; ThinSSAO2PostProcess.FragmentUrl = "ssao2"; ThinSSAO2PostProcess.Uniforms = [ "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "base", "range", "projection", "near", "texelSize", "xViewport", "yViewport", "viewport", "maxZ", "minZAspect", "depthProjection" ]; ThinSSAO2PostProcess.Samplers = ["randomSampler", "depthSampler", "normalSampler"]; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinSSAO2BlurPostProcess.js init_effectRenderer(); init_engine(); var ThinSSAO2BlurPostProcess = class _ThinSSAO2BlurPostProcess extends EffectWrapper { static { __name(this, "ThinSSAO2BlurPostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_ssao2_fragment(), ssao2_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_ssao2_fragment2(), ssao2_fragment_exports2))); } } constructor(name260, engine = null, isHorizontal, options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinSSAO2BlurPostProcess.FragmentUrl, uniforms: _ThinSSAO2BlurPostProcess.Uniforms, samplers: _ThinSSAO2BlurPostProcess.Samplers, defines: "#define BLUR\n" + (isHorizontal ? "#define BLUR_H\n" : "") }); this._bypassBlur = false; this.textureSize = 0; this.bilateralSamples = 16; this.bilateralSoften = 0; this.bilateralTolerance = 0; this._expensiveBlur = true; this._isHorizontal = isHorizontal; const defines = this._getDefinesForBlur(this.expensiveBlur, this.bypassBlur); const samplers = this._getSamplersForBlur(this.bypassBlur); this.updateEffect(defines, null, samplers); } set bypassBlur(b) { const defines = this._getDefinesForBlur(this.expensiveBlur, b); const samplers = this._getSamplersForBlur(b); this.updateEffect(defines, null, samplers); this._bypassBlur = b; } get bypassBlur() { return this._bypassBlur; } set expensiveBlur(b) { const defines = this._getDefinesForBlur(b, this._bypassBlur); this.updateEffect(defines); this._expensiveBlur = b; } get expensiveBlur() { return this._expensiveBlur; } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); const effect = this._drawWrapper.effect; effect.setFloat("outSize", this.textureSize); effect.setInt("samples", this.bilateralSamples); effect.setFloat("soften", this.bilateralSoften); effect.setFloat("tolerance", this.bilateralTolerance); } _getSamplersForBlur(disabled) { return disabled ? ["textureSampler"] : ["textureSampler", "depthSampler"]; } _getDefinesForBlur(bilateral, disabled) { let define = "#define BLUR\n"; if (disabled) { define += "#define BLUR_BYPASS\n"; } if (!bilateral) { define += "#define BLUR_LEGACY\n"; } return this._isHorizontal ? define + "#define BLUR_H\n" : define; } }; ThinSSAO2BlurPostProcess.FragmentUrl = "ssao2"; ThinSSAO2BlurPostProcess.Uniforms = ["outSize", "samples", "soften", "tolerance"]; ThinSSAO2BlurPostProcess.Samplers = ["textureSampler", "depthSampler"]; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinSSAO2CombinePostProcess.js init_effectRenderer(); init_engine(); init_math_vector(); var ThinSSAO2CombinePostProcess = class _ThinSSAO2CombinePostProcess extends EffectWrapper { static { __name(this, "ThinSSAO2CombinePostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_ssaoCombine_fragment(), ssaoCombine_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_ssaoCombine_fragment2(), ssaoCombine_fragment_exports2))); } } constructor(name260, engine = null, options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinSSAO2CombinePostProcess.FragmentUrl, uniforms: _ThinSSAO2CombinePostProcess.Uniforms, samplers: _ThinSSAO2CombinePostProcess.Samplers }); this.camera = null; this.useViewportInCombineStage = true; } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); const effect = this._drawWrapper.effect; if (this.camera) { const viewport = this.camera.viewport; if (this.useViewportInCombineStage) { effect.setVector4("viewport", TmpVectors.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height)); } else { effect.setVector4("viewport", TmpVectors.Vector4[0].copyFromFloats(0, 0, 1, 1)); } } } }; ThinSSAO2CombinePostProcess.FragmentUrl = "ssaoCombine"; ThinSSAO2CombinePostProcess.Uniforms = ["viewport"]; ThinSSAO2CombinePostProcess.Samplers = ["originalColor"]; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/thinSSAO2RenderingPipeline.js var ThinSSAO2RenderingPipeline = class { static { __name(this, "ThinSSAO2RenderingPipeline"); } /** * The camera to which the rendering pipeline will be applied. */ get camera() { return this._ssaoPostProcess.camera; } set camera(camera) { this._ssaoPostProcess.camera = camera; this._ssaoCombinePostProcess.camera = camera; } /** * Number of samples used for the SSAO calculations. Default value is 8. */ set samples(n) { this._ssaoPostProcess.samples = n; } get samples() { return this._ssaoPostProcess.samples; } /** * The output strength of the SSAO post-process. Default value is 1.0. */ get totalStrength() { return this._ssaoPostProcess.totalStrength; } set totalStrength(value) { this._ssaoPostProcess.totalStrength = value; } /** * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0 */ get radius() { return this._ssaoPostProcess.radius; } set radius(value) { this._ssaoPostProcess.radius = value; } /** * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change. */ get maxZ() { return this._ssaoPostProcess.maxZ; } set maxZ(value) { this._ssaoPostProcess.maxZ = value; } /** * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much. */ get minZAspect() { return this._ssaoPostProcess.minZAspect; } set minZAspect(value) { this._ssaoPostProcess.minZAspect = value; } /** * The base color of the SSAO post-process * The final result is "base + ssao" between [0, 1] */ get base() { return this._ssaoPostProcess.base; } set base(value) { this._ssaoPostProcess.base = value; } /** * Used in SSAO calculations to compensate for accuracy issues with depth values. Default 0.02. * * Normally you do not need to change this value, but you can experiment with it if you get a lot of in false self-occlusion on flat surfaces when using fewer than 16 samples. Useful range is normally [0..0.1] but higher values is allowed. */ get epsilon() { return this._ssaoPostProcess.epsilon; } set epsilon(n) { this._ssaoPostProcess.epsilon = n; } /** * Skips the denoising (blur) stage of the SSAO calculations. * * Useful to temporarily set while experimenting with the other SSAO2 settings. */ set bypassBlur(b) { this._ssaoBlurXPostProcess.bypassBlur = b; this._ssaoBlurYPostProcess.bypassBlur = b; } get bypassBlur() { return this._ssaoBlurXPostProcess.bypassBlur; } /** * Enables the configurable bilateral denoising (blurring) filter. Default is true. * Set to false to instead use a legacy bilateral filter that can't be configured. * * The denoising filter runs after the SSAO calculations and is a very important step. Both options results in a so called bilateral being used, but the "expensive" one can be * configured in several ways to fit your scene. */ set expensiveBlur(b) { this._ssaoBlurXPostProcess.expensiveBlur = b; this._ssaoBlurYPostProcess.expensiveBlur = b; } get expensiveBlur() { return this._ssaoBlurXPostProcess.expensiveBlur; } /** * The number of samples the bilateral filter uses in both dimensions when denoising the SSAO calculations. Default value is 16. * * A higher value should result in smoother shadows but will use more processing time in the shaders. * * A high value can cause the shadows to get to blurry or create visible artifacts (bands) near sharp details in the geometry. The artifacts can sometimes be mitigated by increasing the bilateralSoften setting. */ get bilateralSamples() { return this._ssaoBlurXPostProcess.bilateralSamples; } set bilateralSamples(n) { this._ssaoBlurXPostProcess.bilateralSamples = n; this._ssaoBlurYPostProcess.bilateralSamples = n; } /** * Controls the shape of the denoising kernel used by the bilateral filter. Default value is 0. * * By default the bilateral filter acts like a box-filter, treating all samples on the same depth with equal weights. This is effective to maximize the denoising effect given a limited set of samples. However, it also often results in visible ghosting around sharp shadow regions and can spread out lines over large areas so they are no longer visible. * * Increasing this setting will make the filter pay less attention to samples further away from the center sample, reducing many artifacts but at the same time increasing noise. * * Useful value range is [0..1]. */ get bilateralSoften() { return this._ssaoBlurXPostProcess.bilateralSoften; } set bilateralSoften(n) { this._ssaoBlurXPostProcess.bilateralSoften = n; this._ssaoBlurYPostProcess.bilateralSoften = n; } /** * How forgiving the bilateral denoiser should be when rejecting samples. Default value is 0. * * A higher value results in the bilateral filter being more forgiving and thus doing a better job at denoising slanted and curved surfaces, but can lead to shadows spreading out around corners or between objects that are close to each other depth wise. * * Useful value range is normally [0..1], but higher values are allowed. */ get bilateralTolerance() { return this._ssaoBlurXPostProcess.bilateralTolerance; } set bilateralTolerance(n) { this._ssaoBlurXPostProcess.bilateralTolerance = n; this._ssaoBlurYPostProcess.bilateralTolerance = n; } /** * Indicates that the combine stage should use the current camera viewport to render the SSAO result on only a portion of the output texture (default: true). */ get useViewportInCombineStage() { return this._ssaoCombinePostProcess.useViewportInCombineStage; } set useViewportInCombineStage(b) { this._ssaoCombinePostProcess.useViewportInCombineStage = b; } /** * Checks if all the post processes in the pipeline are ready. * @returns true if all the post processes in the pipeline are ready */ isReady() { return this._ssaoPostProcess.isReady() && this._ssaoBlurXPostProcess.isReady() && this._ssaoBlurYPostProcess.isReady() && this._ssaoCombinePostProcess.isReady(); } /** * Constructor of the SSR rendering pipeline * @param name The rendering pipeline name * @param scene The scene linked to this pipeline */ constructor(name260, scene) { this.name = name260; this._scene = scene; this._ssaoPostProcess = new ThinSSAO2PostProcess(this.name, this._scene); this._ssaoBlurXPostProcess = new ThinSSAO2BlurPostProcess(this.name + " BlurX", this._scene.getEngine(), true); this._ssaoBlurYPostProcess = new ThinSSAO2BlurPostProcess(this.name + " BlurY", this._scene.getEngine(), false); this._ssaoCombinePostProcess = new ThinSSAO2CombinePostProcess(this.name + " Combiner", this._scene.getEngine()); } /** * Disposes of the pipeline */ dispose() { this._ssaoPostProcess?.dispose(); this._ssaoBlurXPostProcess?.dispose(); this._ssaoBlurYPostProcess?.dispose(); this._ssaoCombinePostProcess?.dispose(); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/ssao2RenderingPipeline.js init_tslib_es6(); init_logger(); init_decorators(); init_decorators_serialization(); init_texture(); init_postProcess(); init_passPostProcess(); init_typeStore(); init_engineStore(); var SSAO2RenderingPipeline = class _SSAO2RenderingPipeline extends PostProcessRenderPipeline { static { __name(this, "SSAO2RenderingPipeline"); } /** * The output strength of the SSAO post-process. Default value is 1.0. */ get totalStrength() { return this._thinSSAORenderingPipeline.totalStrength; } set totalStrength(value) { this._thinSSAORenderingPipeline.totalStrength = value; } /** * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change. */ get maxZ() { return this._thinSSAORenderingPipeline.maxZ; } set maxZ(value) { this._thinSSAORenderingPipeline.maxZ = value; } /** * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much. */ get minZAspect() { return this._thinSSAORenderingPipeline.minZAspect; } set minZAspect(value) { this._thinSSAORenderingPipeline.minZAspect = value; } /** * Used in SSAO calculations to compensate for accuracy issues with depth values. Default 0.02. * * Normally you do not need to change this value, but you can experiment with it if you get a lot of in false self-occlusion on flat surfaces when using fewer than 16 samples. Useful range is normally [0..0.1] but higher values is allowed. */ set epsilon(n) { this._thinSSAORenderingPipeline.epsilon = n; } get epsilon() { return this._thinSSAORenderingPipeline.epsilon; } /** * Number of samples used for the SSAO calculations. Default value is 8. */ set samples(n) { this._thinSSAORenderingPipeline.samples = n; } get samples() { return this._thinSSAORenderingPipeline.samples; } /** * Number of samples to use for antialiasing. */ set textureSamples(n) { this._textureSamples = n; if (this._prePassRenderer) { this._prePassRenderer.samples = n; } else { this._originalColorPostProcess.samples = n; } } get textureSamples() { return this._textureSamples; } get _geometryBufferRenderer() { if (!this._forceGeometryBuffer) { return null; } return this._forcedGeometryBuffer ?? this._scene.geometryBufferRenderer; } get _prePassRenderer() { if (this._forceGeometryBuffer) { return null; } return this._scene.prePassRenderer; } /** * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0 */ get radius() { return this._thinSSAORenderingPipeline.radius; } set radius(value) { this._thinSSAORenderingPipeline.radius = value; } /** * The base color of the SSAO post-process * The final result is "base + ssao" between [0, 1] */ get base() { return this._thinSSAORenderingPipeline.base; } set base(value) { this._thinSSAORenderingPipeline.base = value; } /** * Skips the denoising (blur) stage of the SSAO calculations. * * Useful to temporarily set while experimenting with the other SSAO2 settings. */ set bypassBlur(b) { this._thinSSAORenderingPipeline.bypassBlur = b; } get bypassBlur() { return this._thinSSAORenderingPipeline.bypassBlur; } /** * Enables the configurable bilateral denoising (blurring) filter. Default is true. * Set to false to instead use a legacy bilateral filter that can't be configured. * * The denoising filter runs after the SSAO calculations and is a very important step. Both options results in a so called bilateral being used, but the "expensive" one can be * configured in several ways to fit your scene. */ set expensiveBlur(b) { this._thinSSAORenderingPipeline.expensiveBlur = b; } get expensiveBlur() { return this._thinSSAORenderingPipeline.expensiveBlur; } /** * The number of samples the bilateral filter uses in both dimensions when denoising the SSAO calculations. Default value is 16. * * A higher value should result in smoother shadows but will use more processing time in the shaders. * * A high value can cause the shadows to get to blurry or create visible artifacts (bands) near sharp details in the geometry. The artifacts can sometimes be mitigated by increasing the bilateralSoften setting. */ get bilateralSamples() { return this._thinSSAORenderingPipeline.bilateralSamples; } set bilateralSamples(n) { this._thinSSAORenderingPipeline.bilateralSamples = n; } /** * Controls the shape of the denoising kernel used by the bilateral filter. Default value is 0. * * By default the bilateral filter acts like a box-filter, treating all samples on the same depth with equal weights. This is effective to maximize the denoising effect given a limited set of samples. However, it also often results in visible ghosting around sharp shadow regions and can spread out lines over large areas so they are no longer visible. * * Increasing this setting will make the filter pay less attention to samples further away from the center sample, reducing many artifacts but at the same time increasing noise. * * Useful value range is [0..1]. */ get bilateralSoften() { return this._thinSSAORenderingPipeline.bilateralSoften; } set bilateralSoften(n) { this._thinSSAORenderingPipeline.bilateralSoften = n; } /** * How forgiving the bilateral denoiser should be when rejecting samples. Default value is 0. * * A higher value results in the bilateral filter being more forgiving and thus doing a better job at denoising slanted and curved surfaces, but can lead to shadows spreading out around corners or between objects that are close to each other depth wise. * * Useful value range is normally [0..1], but higher values are allowed. */ get bilateralTolerance() { return this._thinSSAORenderingPipeline.bilateralTolerance; } set bilateralTolerance(n) { this._thinSSAORenderingPipeline.bilateralTolerance = n; } /** * Support test. */ static get IsSupported() { const engine = EngineStore.LastCreatedEngine; if (!engine) { return false; } return engine._features.supportSSAO2; } /** * Indicates that the combine stage should use the current camera viewport to render the SSAO result on only a portion of the output texture (default: true). */ get useViewportInCombineStage() { return this._thinSSAORenderingPipeline.useViewportInCombineStage; } set useViewportInCombineStage(b) { this._thinSSAORenderingPipeline.useViewportInCombineStage = b; } /** * Gets active scene */ get scene() { return this._scene; } /** * Creates the SSAO2 rendering pipeline. * @param name The rendering pipeline name * @param scene The scene linked to this pipeline * @param ratio The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 } * @param cameras The array of cameras that the rendering pipeline will be attached to * @param forceGeometryBuffer Set to true if you want to use the legacy geometry buffer renderer. You can also pass an existing instance of GeometryBufferRenderer if you want to use your own geometry buffer renderer. * @param textureType The texture type used by the different post processes created by SSAO (default: 0) */ constructor(name260, scene, ratio, cameras, forceGeometryBuffer = false, textureType = 0) { super(scene.getEngine(), name260); this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect"; this.SSAORenderEffect = "SSAORenderEffect"; this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect"; this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect"; this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect"; this._textureSamples = 1; this._forcedGeometryBuffer = null; this._forceGeometryBuffer = false; this._thinSSAORenderingPipeline = new ThinSSAO2RenderingPipeline(name260, scene); this._scene = scene; this._ratio = ratio; this._textureType = textureType; if (forceGeometryBuffer instanceof GeometryBufferRenderer) { this._forceGeometryBuffer = true; this._forcedGeometryBuffer = forceGeometryBuffer; } else { this._forceGeometryBuffer = forceGeometryBuffer; } if (!this.isSupported) { Logger.Error("The current engine does not support SSAO 2."); return; } const ssaoRatio = this._ratio.ssaoRatio || ratio; const blurRatio = this._ratio.blurRatio || ratio; if (this._forceGeometryBuffer) { if (!this._forcedGeometryBuffer) { scene.enableGeometryBufferRenderer(); } if (scene.geometryBufferRenderer?.generateNormalsInWorldSpace) { Logger.Error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the geometry buffer renderer!"); } } else { scene.enablePrePassRenderer(); if (scene.prePassRenderer?.generateNormalsInWorldSpace) { Logger.Error("SSAO2RenderingPipeline does not support generateNormalsInWorldSpace=true for the prepass renderer!"); } } this._originalColorPostProcess = new PassPostProcess("SSAOOriginalSceneColor", 1, null, Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), void 0, this._textureType); this._originalColorPostProcess.samples = this.textureSamples; this._createSSAOPostProcess(1, textureType); this._createBlurPostProcess(ssaoRatio, blurRatio, this._textureType); this._createSSAOCombinePostProcess(blurRatio, this._textureType); this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, () => { return this._originalColorPostProcess; }, true)); this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, () => { return this._ssaoPostProcess; }, true)); this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, () => { return this._blurHPostProcess; }, true)); this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, () => { return this._blurVPostProcess; }, true)); this.addEffect(new PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, () => { return this._ssaoCombinePostProcess; }, true)); scene.postProcessRenderPipelineManager.addPipeline(this); if (cameras) { scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name260, cameras); } } // Public Methods /** * Get the class name * @returns "SSAO2RenderingPipeline" */ getClassName() { return "SSAO2RenderingPipeline"; } /** * Removes the internal pipeline assets and detaches the pipeline from the scene cameras * @param disableGeometryBufferRenderer Set to true if you want to disable the Geometry Buffer renderer */ dispose(disableGeometryBufferRenderer = false) { for (let i = 0; i < this._scene.cameras.length; i++) { const camera = this._scene.cameras[i]; this._originalColorPostProcess.dispose(camera); this._ssaoPostProcess.dispose(camera); this._blurHPostProcess.dispose(camera); this._blurVPostProcess.dispose(camera); this._ssaoCombinePostProcess.dispose(camera); } if (disableGeometryBufferRenderer && !this._forcedGeometryBuffer) { this._scene.disableGeometryBufferRenderer(); } this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras); this._scene.postProcessRenderPipelineManager.removePipeline(this._name); this._thinSSAORenderingPipeline.dispose(); super.dispose(); } // Private Methods /** @internal */ _rebuild() { super._rebuild(); } _createBlurPostProcess(ssaoRatio, blurRatio, textureType) { this._blurHPostProcess = this._createBlurFilter("BlurH", ssaoRatio, textureType, true); this._blurVPostProcess = this._createBlurFilter("BlurV", blurRatio, textureType, false); } _createBlurFilter(name260, ratio, textureType, horizontal) { const blurFilter = new PostProcess(name260, ThinSSAO2BlurPostProcess.FragmentUrl, { size: ratio, samplingMode: 2, engine: this._scene.getEngine(), textureType: this._textureType, effectWrapper: horizontal ? this._thinSSAORenderingPipeline._ssaoBlurXPostProcess : this._thinSSAORenderingPipeline._ssaoBlurYPostProcess }); blurFilter.onApply = (effect) => { const ratio2 = this._ratio.blurRatio || this._ratio; const ssaoCombineSize = horizontal ? this._originalColorPostProcess.width * ratio2 : this._originalColorPostProcess.height * ratio2; const originalColorSize = horizontal ? this._originalColorPostProcess.width : this._originalColorPostProcess.height; this._thinSSAORenderingPipeline._ssaoBlurXPostProcess.textureSize = ssaoCombineSize > 0 ? ssaoCombineSize : originalColorSize; this._thinSSAORenderingPipeline._ssaoBlurYPostProcess.textureSize = ssaoCombineSize > 0 ? ssaoCombineSize : originalColorSize; if (this._geometryBufferRenderer) { effect.setTexture("depthSampler", this._geometryBufferRenderer.getGBuffer().textures[0]); } else if (this._prePassRenderer) { effect.setTexture("depthSampler", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]); } }; blurFilter.samples = this.textureSamples; blurFilter.autoClear = false; return blurFilter; } _getTextureSize() { const engine = this._scene.getEngine(); const prePassRenderer = this._prePassRenderer; let textureSize = { width: engine.getRenderWidth(), height: engine.getRenderHeight() }; if (prePassRenderer && this._scene.activeCamera?._getFirstPostProcess() === this._ssaoPostProcess) { const renderTarget = prePassRenderer.getRenderTarget(); if (renderTarget && renderTarget.textures) { textureSize = renderTarget.textures[prePassRenderer.getIndex(4)].getSize(); } } else if (this._ssaoPostProcess.inputTexture) { textureSize.width = this._ssaoPostProcess.inputTexture.width; textureSize.height = this._ssaoPostProcess.inputTexture.height; } return textureSize; } _createSSAOPostProcess(ratio, textureType) { this._ssaoPostProcess = new PostProcess("ssao", ThinSSAO2PostProcess.FragmentUrl, { size: ratio, samplingMode: 2, engine: this._scene.getEngine(), textureType, effectWrapper: this._thinSSAORenderingPipeline._ssaoPostProcess }); this._ssaoPostProcess.autoClear = false; this._ssaoPostProcess.onApply = (effect) => { this._thinSSAORenderingPipeline._ssaoPostProcess.camera = this._scene.activeCamera; if (this._geometryBufferRenderer) { effect.setTexture("depthSampler", this._geometryBufferRenderer.getGBuffer().textures[0]); effect.setTexture("normalSampler", this._geometryBufferRenderer.getGBuffer().textures[1]); } else if (this._prePassRenderer) { effect.setTexture("depthSampler", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(5)]); effect.setTexture("normalSampler", this._prePassRenderer.getRenderTarget().textures[this._prePassRenderer.getIndex(6)]); } const textureSize = this._getTextureSize(); this._thinSSAORenderingPipeline._ssaoPostProcess.textureWidth = textureSize.width; this._thinSSAORenderingPipeline._ssaoPostProcess.textureHeight = textureSize.height; }; this._ssaoPostProcess.samples = this.textureSamples; if (!this._forceGeometryBuffer) { this._ssaoPostProcess._prePassEffectConfiguration = new SSAO2Configuration(); } } _createSSAOCombinePostProcess(ratio, textureType) { this._ssaoCombinePostProcess = new PostProcess("ssaoCombine", ThinSSAO2CombinePostProcess.FragmentUrl, { size: ratio, samplingMode: 2, engine: this._scene.getEngine(), textureType, effectWrapper: this._thinSSAORenderingPipeline._ssaoCombinePostProcess }); this._ssaoCombinePostProcess.onApply = (effect) => { this._thinSSAORenderingPipeline._ssaoCombinePostProcess.camera = this._scene.activeCamera; effect.setTextureFromPostProcessOutput("originalColor", this._originalColorPostProcess); }; this._ssaoCombinePostProcess.autoClear = false; this._ssaoCombinePostProcess.samples = this.textureSamples; } /** * Serialize the rendering pipeline (Used when exporting) * @returns the serialized object */ serialize() { const serializationObject = SerializationHelper.Serialize(this); serializationObject.customType = "SSAO2RenderingPipeline"; return serializationObject; } /** * Parse the serialized pipeline * @param source Source pipeline. * @param scene The scene to load the pipeline to. * @param rootUrl The URL of the serialized pipeline. * @returns An instantiated pipeline from the serialized object. */ static Parse(source, scene, rootUrl) { return SerializationHelper.Parse(() => new _SSAO2RenderingPipeline(source._name, scene, source._ratio, void 0, source._forceGeometryBuffer, source._textureType), source, scene, rootUrl); } }; __decorate([ serialize() ], SSAO2RenderingPipeline.prototype, "totalStrength", null); __decorate([ serialize() ], SSAO2RenderingPipeline.prototype, "maxZ", null); __decorate([ serialize() ], SSAO2RenderingPipeline.prototype, "minZAspect", null); __decorate([ serialize("epsilon") ], SSAO2RenderingPipeline.prototype, "epsilon", null); __decorate([ serialize("samples") ], SSAO2RenderingPipeline.prototype, "samples", null); __decorate([ serialize("textureSamples") ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0); __decorate([ serialize() ], SSAO2RenderingPipeline.prototype, "_forceGeometryBuffer", void 0); __decorate([ serialize() ], SSAO2RenderingPipeline.prototype, "_ratio", void 0); __decorate([ serialize() ], SSAO2RenderingPipeline.prototype, "_textureType", void 0); __decorate([ serialize() ], SSAO2RenderingPipeline.prototype, "radius", null); __decorate([ serialize() ], SSAO2RenderingPipeline.prototype, "base", null); __decorate([ serialize("bypassBlur") ], SSAO2RenderingPipeline.prototype, "bypassBlur", null); __decorate([ serialize("expensiveBlur") ], SSAO2RenderingPipeline.prototype, "expensiveBlur", null); __decorate([ serialize() ], SSAO2RenderingPipeline.prototype, "bilateralSamples", null); __decorate([ serialize() ], SSAO2RenderingPipeline.prototype, "bilateralSoften", null); __decorate([ serialize() ], SSAO2RenderingPipeline.prototype, "bilateralTolerance", null); RegisterClass("BABYLON.SSAO2RenderingPipeline", SSAO2RenderingPipeline); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/rendering/ssao.js var ssaoRenderingPipeline = null; var ssaoRenderingPipelineCameraConfigurations = /* @__PURE__ */ new Map(); function getSSAO2RenderingPipeline() { return ssaoRenderingPipeline; } __name(getSSAO2RenderingPipeline, "getSSAO2RenderingPipeline"); function setSSAO2RenderingPipelineRef(pipeline) { ssaoRenderingPipeline = pipeline; } __name(setSSAO2RenderingPipelineRef, "setSSAO2RenderingPipelineRef"); function disposeSSAO2RenderingPipeline() { if (ssaoRenderingPipeline) { ssaoRenderingPipeline.dispose(); ssaoRenderingPipeline = null; } } __name(disposeSSAO2RenderingPipeline, "disposeSSAO2RenderingPipeline"); function createSSAO2RenderingPipeline(scene, camera) { ssaoRenderingPipeline = new SSAO2RenderingPipeline("SSAO2RenderingPipeline", scene, 1, [camera]); ssaoRenderingPipeline.samples = 4; return ssaoRenderingPipeline; } __name(createSSAO2RenderingPipeline, "createSSAO2RenderingPipeline"); function serializeSSAO2RenderingPipeline() { if (!ssaoRenderingPipeline) { return null; } return { radius: ssaoRenderingPipeline.radius, totalStrength: ssaoRenderingPipeline.totalStrength, samples: ssaoRenderingPipeline.samples, maxZ: ssaoRenderingPipeline.maxZ, minZAspect: ssaoRenderingPipeline.minZAspect, epsilon: ssaoRenderingPipeline.epsilon, textureSamples: ssaoRenderingPipeline.textureSamples, bypassBlur: ssaoRenderingPipeline.bypassBlur, bilateralSamples: ssaoRenderingPipeline.bilateralSamples, bilateralSoften: ssaoRenderingPipeline.bilateralSoften, bilateralTolerance: ssaoRenderingPipeline.bilateralTolerance, expensiveBlur: ssaoRenderingPipeline.expensiveBlur }; } __name(serializeSSAO2RenderingPipeline, "serializeSSAO2RenderingPipeline"); function parseSSAO2RenderingPipeline(scene, camera, data) { if (ssaoRenderingPipeline) { return ssaoRenderingPipeline; } const pipeline = createSSAO2RenderingPipeline(scene, camera); pipeline.radius = data.radius; pipeline.totalStrength = data.totalStrength; pipeline.samples = data.samples; pipeline.maxZ = data.maxZ; pipeline.minZAspect = data.minZAspect; pipeline.epsilon = data.epsilon; pipeline.textureSamples = data.textureSamples; pipeline.bypassBlur = data.bypassBlur; pipeline.bilateralSamples = data.bilateralSamples; pipeline.bilateralSoften = data.bilateralSoften; pipeline.bilateralTolerance = data.bilateralTolerance; pipeline.expensiveBlur = data.expensiveBlur; return pipeline; } __name(parseSSAO2RenderingPipeline, "parseSSAO2RenderingPipeline"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/motionBlurConfiguration.js var MotionBlurConfiguration = class { static { __name(this, "MotionBlurConfiguration"); } constructor() { this.enabled = false; this.name = "motionBlur"; this.texturesRequired = [2]; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Bones/bone.js init_math_vector(); init_arrayTools(); init_node(); var Bone = class _Bone extends Node { static { __name(this, "Bone"); } /** @internal */ get _matrix() { this._compose(); return this._localMatrix; } /** @internal */ set _matrix(value) { if (value.updateFlag === this._localMatrix.updateFlag && !this._needToCompose) { return; } this._needToCompose = false; this._localMatrix.copyFrom(value); this._markAsDirtyAndDecompose(); } /** * 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 (default: identity) * @param restMatrix defines the rest matrix (default: localMatrix) * @param bindMatrix defines the bind matrix (default: localMatrix) * @param index defines index of the bone in the hierarchy (default: null) */ constructor(name260, skeleton, parentBone = null, localMatrix = null, restMatrix = null, bindMatrix = null, index = null) { super(name260, skeleton.getScene(), false); this.name = name260; this.children = []; this.animations = []; this._index = null; this._scalingDeterminant = 1; this._needToDecompose = true; this._needToCompose = false; this._linkedTransformNode = null; this._waitingTransformNodeId = null; this._skeleton = skeleton; this._localMatrix = localMatrix?.clone() ?? Matrix.Identity(); this._restMatrix = restMatrix ?? this._localMatrix.clone(); this._bindMatrix = bindMatrix ?? this._localMatrix.clone(); this._index = index; this._absoluteMatrix = new Matrix(); this._absoluteBindMatrix = new Matrix(); this._absoluteInverseBindMatrix = new Matrix(); this._finalMatrix = new Matrix(); skeleton.bones.push(this); this.setParent(parentBone, false); this._updateAbsoluteBindMatrices(); } /** * Gets the current object class name. * @returns the class name */ getClassName() { return "Bone"; } // Members /** * Gets the parent skeleton * @returns a skeleton */ getSkeleton() { return this._skeleton; } get parent() { return this._parentNode; } /** * Gets parent bone * @returns a bone or null if the bone is the root of the bone hierarchy */ getParent() { return this.parent; } /** * Returns an array containing the children of the bone * @returns an array containing the children of the bone (can be empty if the bone has no children) */ getChildren() { return this.children; } /** * Gets the node index in matrix array generated for rendering * @returns the node index */ getIndex() { return this._index === null ? this.getSkeleton().bones.indexOf(this) : this._index; } set parent(newParent) { this.setParent(newParent); } /** * Sets the parent bone * @param parent defines the parent (can be null if the bone is the root) * @param updateAbsoluteBindMatrices defines if the absolute bind and absolute inverse bind matrices must be updated */ setParent(parent, updateAbsoluteBindMatrices = true) { if (this.parent === parent) { return; } if (this.parent) { const index = this.parent.children.indexOf(this); if (index !== -1) { this.parent.children.splice(index, 1); } } this._parentNode = parent; if (this.parent) { this.parent.children.push(this); } if (updateAbsoluteBindMatrices) { this._updateAbsoluteBindMatrices(); } this.markAsDirty(); } /** * Gets the local matrix * @returns the local matrix */ getLocalMatrix() { this._compose(); return this._localMatrix; } /** * Gets the bind matrix * @returns the bind matrix */ getBindMatrix() { return this._bindMatrix; } /** * Gets the bind matrix. * @returns the bind matrix * @deprecated Please use getBindMatrix instead */ getBaseMatrix() { return this.getBindMatrix(); } /** * Gets the rest matrix * @returns the rest matrix */ getRestMatrix() { return this._restMatrix; } /** * Gets the rest matrix * @returns the rest matrix * @deprecated Please use getRestMatrix instead */ getRestPose() { return this.getRestMatrix(); } /** * Sets the rest matrix * @param matrix the local-space rest matrix to set for this bone */ setRestMatrix(matrix) { this._restMatrix.copyFrom(matrix); } /** * Sets the rest matrix * @param matrix the local-space rest to set for this bone * @deprecated Please use setRestMatrix instead */ setRestPose(matrix) { this.setRestMatrix(matrix); } /** * Gets the bind matrix * @returns the bind matrix * @deprecated Please use getBindMatrix instead */ getBindPose() { return this.getBindMatrix(); } /** * Sets the bind matrix * This will trigger a recomputation of the absolute bind and absolute inverse bind matrices for this bone and its children * Note that the local matrix will also be set with the matrix passed in parameter! * @param matrix the local-space bind matrix to set for this bone */ setBindMatrix(matrix) { this.updateMatrix(matrix); } /** * Sets the bind matrix * @param matrix the local-space bind to set for this bone * @deprecated Please use setBindMatrix instead */ setBindPose(matrix) { this.setBindMatrix(matrix); } /** * Gets the matrix used to store the final world transformation of the bone (ie. the matrix sent to shaders) * @returns the final world matrix */ getFinalMatrix() { return this._finalMatrix; } /** * Gets the matrix used to store the final world transformation of the bone (ie. the matrix sent to shaders) * @deprecated Please use getFinalMatrix instead * @returns the final world matrix */ getWorldMatrix() { return this.getFinalMatrix(); } /** * Sets the local matrix to the rest matrix */ returnToRest() { if (this._linkedTransformNode) { const localScaling = TmpVectors.Vector3[0]; const localRotation = TmpVectors.Quaternion[0]; const localPosition = TmpVectors.Vector3[1]; this.getRestMatrix().decompose(localScaling, localRotation, localPosition); this._linkedTransformNode.position.copyFrom(localPosition); this._linkedTransformNode.rotationQuaternion = this._linkedTransformNode.rotationQuaternion ?? Quaternion.Identity(); this._linkedTransformNode.rotationQuaternion.copyFrom(localRotation); this._linkedTransformNode.scaling.copyFrom(localScaling); } else { this._matrix = this._restMatrix; } } /** * Gets the inverse of the bind matrix, in world space (relative to the skeleton root) * @returns the inverse bind matrix, in world space */ getAbsoluteInverseBindMatrix() { return this._absoluteInverseBindMatrix; } /** * Gets the inverse of the bind matrix, in world space (relative to the skeleton root) * @returns the inverse bind matrix, in world space * @deprecated Please use getAbsoluteInverseBindMatrix instead */ getInvertedAbsoluteTransform() { return this.getAbsoluteInverseBindMatrix(); } /** * Gets the bone matrix, in world space (relative to the skeleton root) * @returns the bone matrix, in world space */ getAbsoluteMatrix() { this._skeleton.computeAbsoluteMatrices(); return this._absoluteMatrix; } /** * Gets the bone matrix, in world space (relative to the skeleton root) * @returns the bone matrix, in world space * @deprecated Please use getAbsoluteMatrix instead */ getAbsoluteTransform() { return this.getAbsoluteMatrix(); } /** * Links with the given transform node. * The local matrix of this bone is overwritten by the transform of the node every frame. * @param transformNode defines the transform node to link to */ linkTransformNode(transformNode) { if (this._linkedTransformNode) { this._skeleton._numBonesWithLinkedTransformNode--; } this._linkedTransformNode = transformNode; if (this._linkedTransformNode) { this._skeleton._numBonesWithLinkedTransformNode++; } } // Properties (matches TransformNode properties) /** * Gets the node used to drive the bone's transformation * @returns a transform node or null */ getTransformNode() { return this._linkedTransformNode; } /** Gets or sets current position (in local space) */ get position() { this._decompose(); return this._localPosition; } set position(newPosition) { this._decompose(); this._localPosition.copyFrom(newPosition); this._markAsDirtyAndCompose(); } /** Gets or sets current rotation (in local space) */ get rotation() { return this.getRotation(); } set rotation(newRotation) { this.setRotation(newRotation); } /** Gets or sets current rotation quaternion (in local space) */ get rotationQuaternion() { this._decompose(); return this._localRotation; } set rotationQuaternion(newRotation) { this.setRotationQuaternion(newRotation); } /** Gets or sets current scaling (in local space) */ get scaling() { return this.getScale(); } set scaling(newScaling) { this.setScale(newScaling); } /** * Gets the animation properties override */ get animationPropertiesOverride() { return this._skeleton.animationPropertiesOverride; } // Methods _decompose() { if (!this._needToDecompose) { return; } this._needToDecompose = false; if (!this._localScaling) { this._localScaling = Vector3.Zero(); this._localRotation = Quaternion.Zero(); this._localPosition = Vector3.Zero(); } this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition); } _compose() { if (!this._needToCompose) { return; } if (!this._localScaling) { this._needToCompose = false; return; } this._needToCompose = false; Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix); } /** * Update the bind (and optionally the local) matrix * @param bindMatrix defines the new matrix to set to the bind/local matrix, in local space * @param updateAbsoluteBindMatrices defines if the absolute bind and absolute inverse bind matrices must be recomputed (default: true) * @param updateLocalMatrix defines if the local matrix should also be updated with the matrix passed in parameter (default: true) */ updateMatrix(bindMatrix, updateAbsoluteBindMatrices = true, updateLocalMatrix = true) { this._bindMatrix.copyFrom(bindMatrix); if (updateAbsoluteBindMatrices) { this._updateAbsoluteBindMatrices(); } if (updateLocalMatrix) { this._matrix = bindMatrix; } else { this.markAsDirty(); } } /** * @internal */ _updateAbsoluteBindMatrices(bindMatrix, updateChildren = true) { if (!bindMatrix) { bindMatrix = this._bindMatrix; } if (this.parent) { bindMatrix.multiplyToRef(this.parent._absoluteBindMatrix, this._absoluteBindMatrix); } else { this._absoluteBindMatrix.copyFrom(bindMatrix); } this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix); if (updateChildren) { for (let index = 0; index < this.children.length; index++) { this.children[index]._updateAbsoluteBindMatrices(); } } this._scalingDeterminant = this._absoluteBindMatrix.determinant() < 0 ? -1 : 1; } /** * Flag the bone as dirty (Forcing it to update everything) * @returns this bone */ markAsDirty() { this._currentRenderId++; this._childUpdateId++; this._skeleton._markAsDirty(); return this; } /** @internal */ _markAsDirtyAndCompose() { this.markAsDirty(); this._needToCompose = true; } _markAsDirtyAndDecompose() { this.markAsDirty(); this._needToDecompose = true; } _updatePosition(vec, space = 0, tNode, translationMode = true) { const lm = this.getLocalMatrix(); if (space == 0) { if (translationMode) { lm.addAtIndex(12, vec.x); lm.addAtIndex(13, vec.y); lm.addAtIndex(14, vec.z); } else { lm.setTranslationFromFloats(vec.x, vec.y, vec.z); } } else { const tmat = _Bone._TmpMats[0]; const tvec = _Bone._TmpVecs[0]; if (this.parent) { tmat.copyFrom(this.parent.getAbsoluteMatrix()); if (tNode) { tmat.multiplyToRef(tNode.getWorldMatrix(), tmat); } } else { Matrix.IdentityToRef(tmat); } if (translationMode) { tmat.setTranslationFromFloats(0, 0, 0); } tmat.invert(); Vector3.TransformCoordinatesToRef(vec, tmat, tvec); if (translationMode) { lm.addAtIndex(12, tvec.x); lm.addAtIndex(13, tvec.y); lm.addAtIndex(14, tvec.z); } else { lm.setTranslationFromFloats(tvec.x, tvec.y, tvec.z); } } this._markAsDirtyAndDecompose(); } /** * 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 (default: Space.LOCAL) * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD */ translate(vec, space = 0, tNode) { this._updatePosition(vec, space, tNode, true); } /** * Set the position 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 (default: Space.LOCAL) * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD */ setPosition(position, space = 0, tNode) { this._updatePosition(position, space, tNode, false); } /** * Set the absolute position of the bone (world space) * @param position The position to set the bone * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD */ setAbsolutePosition(position, tNode) { this.setPosition(position, 1, tNode); } /** * 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) */ scale(x, y, z, scaleChildren = false) { const locMat = this.getLocalMatrix(); const scaleMat = _Bone._TmpMats[0]; Matrix.ScalingToRef(x, y, z, scaleMat); scaleMat.multiplyToRef(locMat, locMat); scaleMat.invert(); for (const child of this.children) { const 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 (const child of this.children) { child.scale(x, y, z, scaleChildren); } } } /** * Set the bone scaling in local space * @param scale defines the scaling vector */ setScale(scale) { this._decompose(); this._localScaling.copyFrom(scale); this._markAsDirtyAndCompose(); } /** * Gets the current scaling in local space * @returns the current scaling vector */ getScale() { 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 */ getScaleToRef(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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD */ setYawPitchRoll(yaw, pitch, roll, space = 0, tNode) { if (space === 0) { const quat = _Bone._TmpQuat; Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat); this.setRotationQuaternion(quat, space, tNode); return; } const rotMatInv = _Bone._TmpMats[0]; if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) { return; } const rotMat = _Bone._TmpMats[1]; Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat); rotMatInv.multiplyToRef(rotMat, rotMat); this._rotateWithMatrix(rotMat, space, tNode); } /** * 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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD */ rotate(axis, amount, space = 0, tNode) { const rmat = _Bone._TmpMats[0]; rmat.setTranslationFromFloats(0, 0, 0); Matrix.RotationAxisToRef(axis, amount, rmat); this._rotateWithMatrix(rmat, space, tNode); } /** * 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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD */ setAxisAngle(axis, angle, space = 0, tNode) { if (space === 0) { const quat = _Bone._TmpQuat; Quaternion.RotationAxisToRef(axis, angle, quat); this.setRotationQuaternion(quat, space, tNode); return; } const rotMatInv = _Bone._TmpMats[0]; if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) { return; } const rotMat = _Bone._TmpMats[1]; Matrix.RotationAxisToRef(axis, angle, rotMat); rotMatInv.multiplyToRef(rotMat, rotMat); this._rotateWithMatrix(rotMat, space, tNode); } /** * Set the euler rotation of the bone in local or world space * @param rotation The euler rotation that the bone should be set to * @param space The space that the rotation is in * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD */ setRotation(rotation, space = 0, tNode) { this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, tNode); } /** * Set the quaternion rotation of the bone in local or world space * @param quat The quaternion rotation that the bone should be set to * @param space The space that the rotation is in * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD */ setRotationQuaternion(quat, space = 0, tNode) { if (space === 0) { this._decompose(); this._localRotation.copyFrom(quat); this._markAsDirtyAndCompose(); return; } const rotMatInv = _Bone._TmpMats[0]; if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) { return; } const rotMat = _Bone._TmpMats[1]; Matrix.FromQuaternionToRef(quat, rotMat); rotMatInv.multiplyToRef(rotMat, rotMat); this._rotateWithMatrix(rotMat, space, tNode); } /** * Set the rotation matrix of the bone in local or world space * @param rotMat The rotation matrix that the bone should be set to * @param space The space that the rotation is in * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD */ setRotationMatrix(rotMat, space = 0, tNode) { if (space === 0) { const quat = _Bone._TmpQuat; Quaternion.FromRotationMatrixToRef(rotMat, quat); this.setRotationQuaternion(quat, space, tNode); return; } const rotMatInv = _Bone._TmpMats[0]; if (!this._getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode)) { return; } const rotMat2 = _Bone._TmpMats[1]; rotMat2.copyFrom(rotMat); rotMatInv.multiplyToRef(rotMat, rotMat2); this._rotateWithMatrix(rotMat2, space, tNode); } _rotateWithMatrix(rmat, space = 0, tNode) { const lmat = this.getLocalMatrix(); const lx = lmat.m[12]; const ly = lmat.m[13]; const lz = lmat.m[14]; const parent = this.getParent(); const parentScale = _Bone._TmpMats[3]; const parentScaleInv = _Bone._TmpMats[4]; if (parent && space == 1) { if (tNode) { parentScale.copyFrom(tNode.getWorldMatrix()); parent.getAbsoluteMatrix().multiplyToRef(parentScale, parentScale); } else { parentScale.copyFrom(parent.getAbsoluteMatrix()); } parentScaleInv.copyFrom(parentScale); parentScaleInv.invert(); lmat.multiplyToRef(parentScale, lmat); lmat.multiplyToRef(rmat, lmat); lmat.multiplyToRef(parentScaleInv, lmat); } else { if (space == 1 && tNode) { parentScale.copyFrom(tNode.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._markAsDirtyAndDecompose(); } _getAbsoluteInverseMatrixUnscaledToRef(rotMatInv, tNode) { const scaleMatrix = _Bone._TmpMats[2]; rotMatInv.copyFrom(this.getAbsoluteMatrix()); if (tNode) { rotMatInv.multiplyToRef(tNode.getWorldMatrix(), rotMatInv); Matrix.ScalingToRef(tNode.scaling.x, tNode.scaling.y, tNode.scaling.z, scaleMatrix); } else { Matrix.IdentityToRef(scaleMatrix); } rotMatInv.invert(); if (isNaN(rotMatInv.m[0])) { 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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @returns The position of the bone */ getPosition(space = 0, tNode = null) { const pos = Vector3.Zero(); this.getPositionToRef(space, tNode, 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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @param result The vector3 to copy the position to */ getPositionToRef(space = 0, tNode, result) { if (space == 0) { const lm = this.getLocalMatrix(); result.x = lm.m[12]; result.y = lm.m[13]; result.z = lm.m[14]; } else { const tmat = _Bone._TmpMats[0].copyFrom(this.getAbsoluteMatrix()); if (tNode) { tmat.multiplyToRef(tNode.getWorldMatrix(), tmat); } 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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @returns The absolute position of the bone */ getAbsolutePosition(tNode = null) { const pos = Vector3.Zero(); this.getPositionToRef(1, tNode, pos); return pos; } /** * Copy the absolute position of the bone (world space) to the result param * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @param result The vector3 to copy the absolute position to */ getAbsolutePositionToRef(tNode, result) { this.getPositionToRef(1, tNode, result); } /** * Compute the absolute matrices of this bone and its children */ computeAbsoluteMatrices() { this._compose(); if (this.parent) { this._localMatrix.multiplyToRef(this.parent._absoluteMatrix, this._absoluteMatrix); } else { this._absoluteMatrix.copyFrom(this._localMatrix); const poseMatrix = this._skeleton.getPoseMatrix(); if (poseMatrix) { this._absoluteMatrix.multiplyToRef(poseMatrix, this._absoluteMatrix); } } const children = this.children; const len = children.length; for (let i = 0; i < len; i++) { children[i].computeAbsoluteMatrices(); } } /** * Compute the absolute matrices of this bone and its children * @deprecated Please use computeAbsoluteMatrices instead */ computeAbsoluteTransforms() { this.computeAbsoluteMatrices(); } /** * 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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @returns The world direction */ getDirection(localAxis, tNode = null) { const result = Vector3.Zero(); this.getDirectionToRef(localAxis, tNode, 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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @param result The vector3 that the world direction will be copied to */ getDirectionToRef(localAxis, tNode = null, result) { const tMat = _Bone._TmpMats[0].copyFrom(this.getAbsoluteMatrix()); if (tNode) { tMat.multiplyToRef(tNode.getWorldMatrix(), tMat); } Vector3.TransformNormalToRef(localAxis, tMat, 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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @returns The euler rotation */ getRotation(space = 0, tNode = null) { const result = Vector3.Zero(); this.getRotationToRef(space, tNode, 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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @param result The vector3 that the rotation should be copied to */ getRotationToRef(space = 0, tNode = null, result) { const quat = _Bone._TmpQuat; this.getRotationQuaternionToRef(space, tNode, 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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @returns The quaternion rotation */ getRotationQuaternion(space = 0, tNode = null) { const result = Quaternion.Identity(); this.getRotationQuaternionToRef(space, tNode, 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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @param result The quaternion that the rotation should be copied to */ getRotationQuaternionToRef(space = 0, tNode = null, result) { if (space == 0) { this._decompose(); result.copyFrom(this._localRotation); } else { const mat = _Bone._TmpMats[0]; const amat = this.getAbsoluteMatrix(); if (tNode) { amat.multiplyToRef(tNode.getWorldMatrix(), mat); } else { mat.copyFrom(amat); } mat.multiplyAtIndex(0, this._scalingDeterminant); mat.multiplyAtIndex(1, this._scalingDeterminant); mat.multiplyAtIndex(2, this._scalingDeterminant); mat.decompose(void 0, result, void 0); } } /** * Get the rotation matrix of the bone in local or world space * @param space The space that the rotation should be in * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @returns The rotation matrix */ getRotationMatrix(space = 0, tNode) { const result = Matrix.Identity(); this.getRotationMatrixToRef(space, tNode, 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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @param result The quaternion that the rotation should be copied to */ getRotationMatrixToRef(space = 0, tNode, result) { if (space == 0) { this.getLocalMatrix().getRotationMatrixToRef(result); } else { const mat = _Bone._TmpMats[0]; const amat = this.getAbsoluteMatrix(); if (tNode) { amat.multiplyToRef(tNode.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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @returns The world position */ getAbsolutePositionFromLocal(position, tNode = null) { const result = Vector3.Zero(); this.getAbsolutePositionFromLocalToRef(position, tNode, 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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @param result The vector3 that the world position should be copied to */ getAbsolutePositionFromLocalToRef(position, tNode = null, result) { const tmat = _Bone._TmpMats[0].copyFrom(this.getAbsoluteMatrix()); if (tNode) { tmat.multiplyToRef(tNode.getWorldMatrix(), tmat); } Vector3.TransformCoordinatesToRef(position, tmat, result); } /** * Get the local position of a point that is in world space * @param position The world position * @param tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @returns The local position */ getLocalPositionFromAbsolute(position, tNode = null) { const result = Vector3.Zero(); this.getLocalPositionFromAbsoluteToRef(position, tNode, 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 tNode A TransformNode whose world matrix is to be applied to the calculated absolute matrix. In most cases, you'll want to pass the mesh associated with the skeleton from which this bone comes. Used only when space=Space.WORLD * @param result The vector3 that the local position should be copied to */ getLocalPositionFromAbsoluteToRef(position, tNode = null, result) { const tmat = _Bone._TmpMats[0].copyFrom(this.getAbsoluteMatrix()); if (tNode) { tmat.multiplyToRef(tNode.getWorldMatrix(), tmat); } tmat.invert(); Vector3.TransformCoordinatesToRef(position, tmat, result); } /** * Set the current local matrix as the restMatrix for this bone. */ setCurrentPoseAsRest() { this.setRestMatrix(this.getLocalMatrix()); } /** * Releases associated resources */ dispose() { this._linkedTransformNode = null; const index = this._skeleton.bones.indexOf(this); if (index !== -1) { this._skeleton.bones.splice(index, 1); } if (this._parentNode && this._parentNode.children) { const children = this._parentNode.children; const index2 = children.indexOf(this); if (index2 !== -1) { children.splice(index2, 1); } } super.dispose(); } }; Bone._TmpVecs = BuildArray(2, Vector3.Zero); Bone._TmpQuat = Quaternion.Identity(); Bone._TmpMats = BuildArray(5, Matrix.Identity); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Animations/animationRange.js var AnimationRange = class _AnimationRange { static { __name(this, "AnimationRange"); } /** * 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 */ constructor(name260, from, to) { this.name = name260; this.from = from; this.to = to; } /** * Makes a copy of the animation range * @returns A copy of the animation range */ clone() { return new _AnimationRange(this.name, this.from, this.to); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Animations/animation.js init_math_vector(); init_math_color(); init_math_scalar_functions(); init_typeStore(); init_node(); init_math_size(); init_webRequest(); init_decorators_serialization(); var _StaticOffsetValueQuaternion = Object.freeze(new Quaternion(0, 0, 0, 0)); var _StaticOffsetValueVector3 = Object.freeze(Vector3.Zero()); var _StaticOffsetValueVector2 = Object.freeze(Vector2.Zero()); var _StaticOffsetValueSize = Object.freeze(Size.Zero()); var _StaticOffsetValueColor3 = Object.freeze(Color3.Black()); var _StaticOffsetValueColor4 = Object.freeze(new Color4(0, 0, 0, 0)); var EvaluateAnimationState = { key: 0, repeatCount: 0, loopMode: 2 }; var Animation = class _Animation { static { __name(this, "Animation"); } /** * @internal Internal use */ static _PrepareAnimation(name260, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) { let dataType = void 0; if (!isNaN(parseFloat(from)) && isFinite(from)) { dataType = _Animation.ANIMATIONTYPE_FLOAT; } else if (from instanceof Quaternion) { dataType = _Animation.ANIMATIONTYPE_QUATERNION; } else if (from instanceof Vector3) { dataType = _Animation.ANIMATIONTYPE_VECTOR3; } else if (from instanceof Vector2) { dataType = _Animation.ANIMATIONTYPE_VECTOR2; } else if (from instanceof Color3) { dataType = _Animation.ANIMATIONTYPE_COLOR3; } else if (from instanceof Color4) { dataType = _Animation.ANIMATIONTYPE_COLOR4; } else if (from instanceof Size) { dataType = _Animation.ANIMATIONTYPE_SIZE; } if (dataType == void 0) { return null; } const animation = new _Animation(name260, targetProperty, framePerSecond, dataType, loopMode); const keys = [ { frame: 0, value: from }, { frame: totalFrame, value: to } ]; animation.setKeys(keys); if (easingFunction !== void 0) { 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 */ static CreateAnimation(property, animationType, framePerSecond, easingFunction) { const 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 target defines the target 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 * @param scene defines the hosting scene * @returns the animatable created for this animation */ static CreateAndStartAnimation(name260, target, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd, scene) { const animation = _Animation._PrepareAnimation(name260, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); if (!animation) { return null; } if (target.getScene) { scene = target.getScene(); } if (!scene) { return null; } return scene.beginDirectAnimation(target, [animation], 0, totalFrame, animation.loopMode !== _Animation.ANIMATIONLOOPMODE_CONSTANT, 1, 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 */ static CreateAndStartHierarchyAnimation(name260, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { const animation = _Animation._PrepareAnimation(name260, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); if (!animation) { return null; } const scene = node.getScene(); return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, animation.loopMode === 1, 1, 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 */ static CreateMergeAndStartAnimation(name260, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { const animation = _Animation._PrepareAnimation(name260, 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, onAnimationEnd); } /** @internal */ static MakeAnimationAdditive(sourceAnimation, referenceFrameOrOptions, range, cloneOriginal = false, clonedName) { let options; if (typeof referenceFrameOrOptions === "object") { options = referenceFrameOrOptions; } else { options = { referenceFrame: referenceFrameOrOptions ?? 0, range, cloneOriginalAnimation: cloneOriginal, clonedAnimationName: clonedName }; } let animation = sourceAnimation; if (options.cloneOriginalAnimation) { animation = sourceAnimation.clone(); animation.name = options.clonedAnimationName || animation.name; } if (!animation._keys.length) { return animation; } const referenceFrame = options.referenceFrame && options.referenceFrame >= 0 ? options.referenceFrame : 0; let startIndex = 0; const firstKey = animation._keys[0]; let endIndex = animation._keys.length - 1; const lastKey = animation._keys[endIndex]; const valueStore = { referenceValue: firstKey.value, referencePosition: TmpVectors.Vector3[0], referenceQuaternion: TmpVectors.Quaternion[0], referenceScaling: TmpVectors.Vector3[1], keyPosition: TmpVectors.Vector3[2], keyQuaternion: TmpVectors.Quaternion[1], keyScaling: TmpVectors.Vector3[3] }; let from = firstKey.frame; let to = lastKey.frame; if (options.range) { const rangeValue = animation.getRange(options.range); if (rangeValue) { from = rangeValue.from; to = rangeValue.to; } } else { from = options.fromFrame ?? from; to = options.toFrame ?? to; } if (from !== firstKey.frame) { startIndex = animation.createKeyForFrame(from); } if (to !== lastKey.frame) { endIndex = animation.createKeyForFrame(to); } if (animation._keys.length === 1) { const value = animation._getKeyValue(animation._keys[0]); valueStore.referenceValue = value.clone ? value.clone() : value; } else if (referenceFrame <= firstKey.frame) { const value = animation._getKeyValue(firstKey.value); valueStore.referenceValue = value.clone ? value.clone() : value; } else if (referenceFrame >= lastKey.frame) { const value = animation._getKeyValue(lastKey.value); valueStore.referenceValue = value.clone ? value.clone() : value; } else { EvaluateAnimationState.key = 0; const value = animation._interpolate(referenceFrame, EvaluateAnimationState); valueStore.referenceValue = value.clone ? value.clone() : value; } if (animation.dataType === _Animation.ANIMATIONTYPE_QUATERNION) { valueStore.referenceValue.normalize().conjugateInPlace(); } else if (animation.dataType === _Animation.ANIMATIONTYPE_MATRIX) { valueStore.referenceValue.decompose(valueStore.referenceScaling, valueStore.referenceQuaternion, valueStore.referencePosition); valueStore.referenceQuaternion.normalize().conjugateInPlace(); } let startFrame = Number.MAX_VALUE; const clippedKeys = options.clipKeys ? [] : null; for (let index = startIndex; index <= endIndex; index++) { let key = animation._keys[index]; if (clippedKeys || options.cloneOriginalAnimation) { key = { frame: key.frame, value: key.value.clone ? key.value.clone() : key.value, inTangent: key.inTangent, outTangent: key.outTangent, interpolation: key.interpolation, lockedTangent: key.lockedTangent }; if (clippedKeys) { if (startFrame === Number.MAX_VALUE) { startFrame = key.frame; } key.frame -= startFrame; clippedKeys.push(key); } } 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); 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; } } if (clippedKeys) { animation.setKeys(clippedKeys, true); } 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 */ static TransitionTo(property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd = null) { if (duration <= 0) { host[property] = targetValue; if (onAnimationEnd) { onAnimationEnd(); } return null; } const endFrame = frameRate * (duration / 1e3); 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); const animation = scene.beginAnimation(host, 0, endFrame, false); animation.onAnimationEnd = onAnimationEnd; return animation; } /** * Return the array of runtime animations currently using this animation */ get runtimeAnimations() { return this._runtimeAnimations; } /** * Specifies if any of the runtime animations are currently running */ get hasRunningRuntimeAnimations() { for (const runtimeAnimation of this._runtimeAnimations) { if (!runtimeAnimation.isStopped()) { return true; } } return false; } /** * 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 */ constructor(name260, targetProperty, framePerSecond, dataType, loopMode, enableBlending) { this.name = name260; this.targetProperty = targetProperty; this.framePerSecond = framePerSecond; this.dataType = dataType; this.loopMode = loopMode; this.enableBlending = enableBlending; this._easingFunction = null; this._runtimeAnimations = new Array(); this._events = new Array(); this.blendingSpeed = 0.01; this._ranges = {}; this._coreAnimation = null; this.targetPropertyPath = targetProperty.split("."); this.dataType = dataType; this.loopMode = loopMode === void 0 ? _Animation.ANIMATIONLOOPMODE_CYCLE : loopMode; this.uniqueId = _Animation._UniqueIdGenerator++; } // Methods /** * Converts the animation to a string * @param fullDetails support for multiple levels of logging within scene loading * @returns String form of the animation */ toString(fullDetails) { let 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: {"; let first = true; for (const name260 in this._ranges) { if (first) { ret += ", "; first = false; } ret += name260; } ret += "}"; } return ret; } /** * Add an event to this animation * @param event Event to add */ addEvent(event) { this._events.push(event); this._events.sort((a, b) => a.frame - b.frame); } /** * Remove all events found at the given frame * @param frame The frame to remove events from */ removeEvents(frame) { for (let 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 */ getEvents() { 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 */ createRange(name260, from, to) { if (!this._ranges[name260]) { this._ranges[name260] = new AnimationRange(name260, 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) */ deleteRange(name260, deleteFrames = true) { const range = this._ranges[name260]; if (!range) { return; } if (deleteFrames) { const from = range.from; const to = range.to; for (let 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[name260] = null; } /** * Gets the animation range by name, or null if not defined * @param name Name of the animation range * @returns Nullable animation range */ getRange(name260) { return this._ranges[name260]; } /** * Gets the key frames from the animation * @returns The key frames of the animation */ getKeys() { return this._keys; } /** * Gets the highest frame of the animation * @returns Highest frame of the animation */ getHighestFrame() { let ret = 0; for (let 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 */ getEasingFunction() { return this._easingFunction; } /** * Sets the easing function of the animation * @param easingFunction A custom mathematical formula for animation */ setEasingFunction(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 */ floatInterpolateFunction(startValue, endValue, gradient) { return 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 */ floatInterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { return 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 */ quaternionInterpolateFunction(startValue, endValue, gradient) { return 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 */ quaternionInterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { return Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize(); } /** * Interpolates a Vector3 linearly * @param startValue Start value of the animation curve * @param endValue End value of the animation curve * @param gradient Scalar amount to interpolate (value between 0 and 1) * @returns Interpolated scalar value */ vector3InterpolateFunction(startValue, endValue, gradient) { return 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 (value between 0 and 1) * @returns InterpolatedVector3 value */ vector3InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { return 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 (value between 0 and 1) * @returns Interpolated Vector2 value */ vector2InterpolateFunction(startValue, endValue, gradient) { return 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 (value between 0 and 1) * @returns Interpolated Vector2 value */ vector2InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { return 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 */ sizeInterpolateFunction(startValue, endValue, gradient) { return 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 */ color3InterpolateFunction(startValue, endValue, gradient) { return Color3.Lerp(startValue, endValue, gradient); } /** * Interpolates a Color3 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 value */ color3InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { return Color3.Hermite(startValue, outTangent, endValue, inTangent, 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 */ color4InterpolateFunction(startValue, endValue, gradient) { return Color4.Lerp(startValue, endValue, gradient); } /** * Interpolates a Color4 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 value */ color4InterpolateFunctionWithTangents(startValue, outTangent, endValue, inTangent, gradient) { return Color4.Hermite(startValue, outTangent, endValue, inTangent, gradient); } /** * @internal Internal use only */ _getKeyValue(value) { if (typeof value === "function") { return value(); } return value; } /** * Evaluate the animation value at a given frame * @param currentFrame defines the frame where we want to evaluate the animation * @returns the animation value */ evaluate(currentFrame) { EvaluateAnimationState.key = 0; return this._interpolate(currentFrame, EvaluateAnimationState); } /** * @internal Internal use only */ _interpolate(currentFrame, state, searchClosestKeyOnly = false) { if (state.loopMode === _Animation.ANIMATIONLOOPMODE_CONSTANT && state.repeatCount > 0) { return state.highLimitValue.clone ? state.highLimitValue.clone() : state.highLimitValue; } const keys = this._keys; let key; if (!this._coreAnimation) { const keysLength = keys.length; key = state.key; while (key >= 0 && currentFrame < keys[key].frame) { --key; } while (key + 1 <= keysLength - 1 && currentFrame >= keys[key + 1].frame) { ++key; } state.key = key; if (key < 0) { return searchClosestKeyOnly ? void 0 : this._getKeyValue(keys[0].value); } else if (key + 1 > keysLength - 1) { return searchClosestKeyOnly ? void 0 : this._getKeyValue(keys[keysLength - 1].value); } this._key = key; } else { key = this._coreAnimation._key; } const startKey = keys[key]; const endKey = keys[key + 1]; if (searchClosestKeyOnly && (currentFrame === startKey.frame || currentFrame === endKey.frame)) { return void 0; } const startValue = this._getKeyValue(startKey.value); const endValue = this._getKeyValue(endKey.value); if (startKey.interpolation === 1) { if (endKey.frame > currentFrame) { return startValue; } else { return endValue; } } const useTangent = startKey.outTangent !== void 0 && endKey.inTangent !== void 0; const frameDelta = endKey.frame - startKey.frame; let gradient = (currentFrame - startKey.frame) / frameDelta; const easingFunction = startKey.easingFunction || this.getEasingFunction(); if (easingFunction) { gradient = easingFunction.ease(gradient); } switch (this.dataType) { // Float case _Animation.ANIMATIONTYPE_FLOAT: { const 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: case _Animation.ANIMATIONLOOPMODE_YOYO: return floatValue; case _Animation.ANIMATIONLOOPMODE_RELATIVE: case _Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: return (state.offsetValue ?? 0) * state.repeatCount + floatValue; } break; } // Quaternion case _Animation.ANIMATIONTYPE_QUATERNION: { const 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: case _Animation.ANIMATIONLOOPMODE_YOYO: return quatValue; case _Animation.ANIMATIONLOOPMODE_RELATIVE: case _Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: return quatValue.addInPlace((state.offsetValue || _StaticOffsetValueQuaternion).scale(state.repeatCount)); } return quatValue; } // Vector3 case _Animation.ANIMATIONTYPE_VECTOR3: { const 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: case _Animation.ANIMATIONLOOPMODE_YOYO: return vec3Value; case _Animation.ANIMATIONLOOPMODE_RELATIVE: case _Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: return vec3Value.add((state.offsetValue || _StaticOffsetValueVector3).scale(state.repeatCount)); } break; } // Vector2 case _Animation.ANIMATIONTYPE_VECTOR2: { const 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: case _Animation.ANIMATIONLOOPMODE_YOYO: return vec2Value; case _Animation.ANIMATIONLOOPMODE_RELATIVE: case _Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: return vec2Value.add((state.offsetValue || _StaticOffsetValueVector2).scale(state.repeatCount)); } break; } // Size case _Animation.ANIMATIONTYPE_SIZE: { switch (state.loopMode) { case _Animation.ANIMATIONLOOPMODE_CYCLE: case _Animation.ANIMATIONLOOPMODE_CONSTANT: case _Animation.ANIMATIONLOOPMODE_YOYO: return this.sizeInterpolateFunction(startValue, endValue, gradient); case _Animation.ANIMATIONLOOPMODE_RELATIVE: case _Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: return this.sizeInterpolateFunction(startValue, endValue, gradient).add((state.offsetValue || _StaticOffsetValueSize).scale(state.repeatCount)); } break; } // Color3 case _Animation.ANIMATIONTYPE_COLOR3: { const color3Value = useTangent ? this.color3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.color3InterpolateFunction(startValue, endValue, gradient); switch (state.loopMode) { case _Animation.ANIMATIONLOOPMODE_CYCLE: case _Animation.ANIMATIONLOOPMODE_CONSTANT: case _Animation.ANIMATIONLOOPMODE_YOYO: return color3Value; case _Animation.ANIMATIONLOOPMODE_RELATIVE: case _Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: return color3Value.add((state.offsetValue || _StaticOffsetValueColor3).scale(state.repeatCount)); } break; } // Color4 case _Animation.ANIMATIONTYPE_COLOR4: { const color4Value = useTangent ? this.color4InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.color4InterpolateFunction(startValue, endValue, gradient); switch (state.loopMode) { case _Animation.ANIMATIONLOOPMODE_CYCLE: case _Animation.ANIMATIONLOOPMODE_CONSTANT: case _Animation.ANIMATIONLOOPMODE_YOYO: return color4Value; case _Animation.ANIMATIONLOOPMODE_RELATIVE: case _Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: return color4Value.add((state.offsetValue || _StaticOffsetValueColor4).scale(state.repeatCount)); } break; } // Matrix case _Animation.ANIMATIONTYPE_MATRIX: { switch (state.loopMode) { case _Animation.ANIMATIONLOOPMODE_CYCLE: case _Animation.ANIMATIONLOOPMODE_CONSTANT: case _Animation.ANIMATIONLOOPMODE_YOYO: { if (_Animation.AllowMatricesInterpolation) { return this.matrixInterpolateFunction(startValue, endValue, gradient, state.workValue); } return startValue; } case _Animation.ANIMATIONLOOPMODE_RELATIVE: case _Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT: { return startValue; } } break; } } return 0; } /** * 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 */ matrixInterpolateFunction(startValue, endValue, gradient, result) { if (_Animation.AllowMatrixDecomposeForInterpolation) { if (result) { Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result); return result; } return Matrix.DecomposeLerp(startValue, endValue, gradient); } if (result) { Matrix.LerpToRef(startValue, endValue, gradient, result); return result; } return Matrix.Lerp(startValue, endValue, gradient); } /** * Makes a copy of the animation * @returns Cloned animation */ clone() { const 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 (const name260 in this._ranges) { const range = this._ranges[name260]; if (!range) { continue; } clone._ranges[name260] = range.clone(); } } return clone; } /** * Sets the key frames of the animation * @param values The animation key frames to set * @param dontClone Whether to clone the keys or not (default is false, so the array of keys is cloned) */ setKeys(values, dontClone = false) { this._keys = !dontClone ? values.slice(0) : values; } /** * Creates a key for the frame passed as a parameter and adds it to the animation IF a key doesn't already exist for that frame * @param frame Frame number * @returns The key index if the key was added or the index of the pre existing key if the frame passed as parameter already has a corresponding key */ createKeyForFrame(frame) { EvaluateAnimationState.key = 0; const value = this._interpolate(frame, EvaluateAnimationState, true); if (!value) { return this._keys[EvaluateAnimationState.key].frame === frame ? EvaluateAnimationState.key : EvaluateAnimationState.key + 1; } const newKey = { frame, value: value.clone ? value.clone() : value }; this._keys.splice(EvaluateAnimationState.key + 1, 0, newKey); return EvaluateAnimationState.key + 1; } /** * Serializes the animation to an object * @returns Serialized object */ serialize() { const 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; const dataType = this.dataType; serializationObject.keys = []; const keys = this.getKeys(); for (let index = 0; index < keys.length; index++) { const animationKey = keys[index]; const key = {}; key.frame = animationKey.frame; switch (dataType) { case _Animation.ANIMATIONTYPE_FLOAT: key.values = [animationKey.value]; if (animationKey.inTangent !== void 0) { key.values.push(animationKey.inTangent); } if (animationKey.outTangent !== void 0) { if (animationKey.inTangent === void 0) { key.values.push(void 0); } key.values.push(animationKey.outTangent); } if (animationKey.interpolation !== void 0) { if (animationKey.inTangent === void 0) { key.values.push(void 0); } if (animationKey.outTangent === void 0) { key.values.push(void 0); } key.values.push(animationKey.interpolation); } 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 != void 0) { key.values.push(animationKey.inTangent.asArray()); } if (animationKey.outTangent != void 0) { if (animationKey.inTangent === void 0) { key.values.push(void 0); } key.values.push(animationKey.outTangent.asArray()); } if (animationKey.interpolation !== void 0) { if (animationKey.inTangent === void 0) { key.values.push(void 0); } if (animationKey.outTangent === void 0) { key.values.push(void 0); } key.values.push(animationKey.interpolation); } break; } serializationObject.keys.push(key); } serializationObject.ranges = []; for (const name260 in this._ranges) { const source = this._ranges[name260]; if (!source) { continue; } const range = {}; range.name = name260; range.from = source.from; range.to = source.to; serializationObject.ranges.push(range); } return serializationObject; } /** * @internal */ static _UniversalLerp(left, right, amount) { const constructor = left.constructor; if (constructor.Lerp) { return constructor.Lerp(left, right, amount); } else if (constructor.Slerp) { return constructor.Slerp(left, right, amount); } else if (left.toFixed) { return left * (1 - amount) + amount * right; } else { return right; } } /** * Parses an animation object and creates an animation * @param parsedAnimation Parsed animation object * @returns Animation object */ static Parse(parsedAnimation) { const animation = new _Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior); const dataType = parsedAnimation.dataType; const keys = []; let data; let index; if (parsedAnimation.enableBlending) { animation.enableBlending = parsedAnimation.enableBlending; } if (parsedAnimation.blendingSpeed) { animation.blendingSpeed = parsedAnimation.blendingSpeed; } for (index = 0; index < parsedAnimation.keys.length; index++) { const key = parsedAnimation.keys[index]; let inTangent = void 0; let outTangent = void 0; let interpolation = void 0; switch (dataType) { case _Animation.ANIMATIONTYPE_FLOAT: data = key.values[0]; if (key.values.length >= 2) { inTangent = key.values[1]; } if (key.values.length >= 3) { outTangent = key.values[2]; } if (key.values.length >= 4) { interpolation = key.values[3]; } break; case _Animation.ANIMATIONTYPE_QUATERNION: data = Quaternion.FromArray(key.values); if (key.values.length >= 8) { const _inTangent = Quaternion.FromArray(key.values.slice(4, 8)); if (!_inTangent.equals(Quaternion.Zero())) { inTangent = _inTangent; } } if (key.values.length >= 12) { const _outTangent = Quaternion.FromArray(key.values.slice(8, 12)); if (!_outTangent.equals(Quaternion.Zero())) { outTangent = _outTangent; } } if (key.values.length >= 13) { interpolation = key.values[12]; } break; case _Animation.ANIMATIONTYPE_MATRIX: data = Matrix.FromArray(key.values); if (key.values.length >= 17) { interpolation = key.values[16]; } break; case _Animation.ANIMATIONTYPE_COLOR3: data = Color3.FromArray(key.values); if (key.values[3]) { inTangent = Color3.FromArray(key.values[3]); } if (key.values[4]) { outTangent = Color3.FromArray(key.values[4]); } if (key.values[5]) { interpolation = key.values[5]; } break; case _Animation.ANIMATIONTYPE_COLOR4: data = Color4.FromArray(key.values); if (key.values[4]) { inTangent = Color4.FromArray(key.values[4]); } if (key.values[5]) { outTangent = Color4.FromArray(key.values[5]); } if (key.values[6]) { interpolation = Color4.FromArray(key.values[6]); } break; case _Animation.ANIMATIONTYPE_VECTOR3: default: data = Vector3.FromArray(key.values); if (key.values[3]) { inTangent = Vector3.FromArray(key.values[3]); } if (key.values[4]) { outTangent = Vector3.FromArray(key.values[4]); } if (key.values[5]) { interpolation = key.values[5]; } break; } const keyData = {}; keyData.frame = key.frame; keyData.value = data; if (inTangent != void 0) { keyData.inTangent = inTangent; } if (outTangent != void 0) { keyData.outTangent = outTangent; } if (interpolation != void 0) { keyData.interpolation = interpolation; } 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 */ static AppendSerializedAnimations(source, destination) { 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 */ static async ParseFromFileAsync(name260, url) { return await new Promise((resolve, reject) => { const request = new WebRequest(); request.addEventListener("readystatechange", () => { if (request.readyState == 4) { if (request.status == 200) { let serializationObject = JSON.parse(request.responseText); if (serializationObject.animations) { serializationObject = serializationObject.animations; } if (serializationObject.length) { const output = []; for (const serializedAnimation of serializationObject) { output.push(this.Parse(serializedAnimation)); } resolve(output); } else { const output = this.Parse(serializationObject); if (name260) { output.name = name260; } 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 */ static async ParseFromSnippetAsync(snippetId) { return await new Promise((resolve, reject) => { const request = new WebRequest(); request.addEventListener("readystatechange", () => { if (request.readyState == 4) { if (request.status == 200) { const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); if (snippet.animations) { const serializationObject = JSON.parse(snippet.animations); const outputs = []; for (const serializedAnimation of serializationObject.animations) { const output = this.Parse(serializedAnimation); output.snippetId = snippetId; outputs.push(output); } resolve(outputs); } else { const serializationObject = JSON.parse(snippet.animation); const 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(); }); } }; Animation._UniqueIdGenerator = 0; Animation.AllowMatricesInterpolation = false; Animation.AllowMatrixDecomposeForInterpolation = true; Animation.SnippetUrl = `https://snippet.babylonjs.com`; Animation.ANIMATIONTYPE_FLOAT = 0; Animation.ANIMATIONTYPE_VECTOR3 = 1; Animation.ANIMATIONTYPE_QUATERNION = 2; Animation.ANIMATIONTYPE_MATRIX = 3; Animation.ANIMATIONTYPE_COLOR3 = 4; Animation.ANIMATIONTYPE_COLOR4 = 7; Animation.ANIMATIONTYPE_VECTOR2 = 5; Animation.ANIMATIONTYPE_SIZE = 6; Animation.ANIMATIONLOOPMODE_RELATIVE = 0; Animation.ANIMATIONLOOPMODE_CYCLE = 1; Animation.ANIMATIONLOOPMODE_CONSTANT = 2; Animation.ANIMATIONLOOPMODE_YOYO = 4; Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT = 5; Animation.CreateFromSnippetAsync = Animation.ParseFromSnippetAsync; RegisterClass("BABYLON.Animation", Animation); Node._AnimationRangeFactory = (name260, from, to) => new AnimationRange(name260, from, to); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Animations/runtimeAnimation.js init_math_vector(); var RuntimeAnimation = class { static { __name(this, "RuntimeAnimation"); } /** * Gets the current frame of the runtime animation */ get currentFrame() { return this._currentFrame; } /** * Gets the weight of the runtime animation */ get weight() { return this._weight; } /** * Gets the current value of the runtime animation */ get currentValue() { return this._currentValue; } /** * Gets or sets the target path of the runtime animation */ get targetPath() { return this._targetPath; } /** * Gets the actual target of the runtime animation */ get target() { return this._currentActiveTarget; } /** * Gets the additive state of the runtime animation */ get isAdditive() { return this._host && this._host.isAdditive; } /** * 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 */ constructor(target, animation, scene, host) { this._events = new Array(); this._currentFrame = 0; this._originalValue = new Array(); this._originalBlendValue = null; this._offsetsCache = {}; this._highLimitsCache = {}; this._stopped = false; this._blendingFactor = 0; this._currentValue = null; this._currentActiveTarget = null; this._directTarget = null; this._targetPath = ""; this._weight = 1; this._absoluteFrameOffset = 0; this._previousElapsedTime = 0; this._yoyoDirection = 1; this._previousAbsoluteFrame = 0; this._targetIsArray = false; this._coreRuntimeAnimation = null; this._animation = animation; this._target = target; this._scene = scene; this._host = host; this._activeTargets = []; animation._runtimeAnimations.push(this); this._animationState = { key: 0, repeatCount: 0, loopMode: this._getCorrectLoopMode() }; if (this._animation.dataType === Animation.ANIMATIONTYPE_MATRIX) { this._animationState.workValue = Matrix.Zero(); } 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; if (this._minFrame !== 0) { const newKey = { frame: 0, value: this._minValue }; this._keys.splice(0, 0, newKey); } if (this._target instanceof Array) { let index = 0; for (const target2 of this._target) { this._preparePath(target2, index); this._getOriginalValues(index); index++; } this._targetIsArray = true; } else { this._preparePath(this._target); this._getOriginalValues(); this._targetIsArray = false; this._directTarget = this._activeTargets[0]; } const events = animation.getEvents(); if (events && events.length > 0) { for (const e of events) { this._events.push(e._clone()); } } this._enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending; } _preparePath(target, targetIndex = 0) { const targetPropertyPath = this._animation.targetPropertyPath; if (targetPropertyPath.length > 1) { let property = target; for (let index = 0; index < targetPropertyPath.length - 1; index++) { const name260 = targetPropertyPath[index]; property = property[name260]; if (property === void 0) { throw new Error(`Invalid property (${name260}) in property path (${targetPropertyPath.join(".")})`); } } this._targetPath = targetPropertyPath[targetPropertyPath.length - 1]; this._activeTargets[targetIndex] = property; } else { this._targetPath = targetPropertyPath[0]; this._activeTargets[targetIndex] = target; } if (this._activeTargets[targetIndex][this._targetPath] === void 0) { throw new Error(`Invalid property (${this._targetPath}) in property path (${targetPropertyPath.join(".")})`); } } /** * Gets the animation from the runtime animation */ get animation() { return this._animation; } /** * Resets the runtime animation to the beginning * @param restoreOriginal defines whether to restore the target property to the original value */ reset(restoreOriginal = false) { if (restoreOriginal) { if (this._target instanceof Array) { let index = 0; for (const target of this._target) { if (this._originalValue[index] !== void 0) { this._setValue(target, this._activeTargets[index], this._originalValue[index], -1, index); } index++; } } else { if (this._originalValue[0] !== void 0) { this._setValue(this._target, this._directTarget, this._originalValue[0], -1, 0); } } } this._offsetsCache = {}; this._highLimitsCache = {}; this._currentFrame = 0; this._blendingFactor = 0; for (let 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 */ isStopped() { return this._stopped; } /** * Disposes of the runtime animation */ dispose() { const 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) */ setValue(currentValue, weight) { if (this._targetIsArray) { for (let index = 0; index < this._target.length; index++) { const target = this._target[index]; this._setValue(target, this._activeTargets[index], currentValue, weight, index); } return; } this._setValue(this._target, this._directTarget, currentValue, weight, 0); } _getOriginalValues(targetIndex = 0) { let originalValue; const target = this._activeTargets[targetIndex]; if (target.getLocalMatrix && this._targetPath === "_matrix") { originalValue = target.getLocalMatrix(); } else { originalValue = target[this._targetPath]; } if (originalValue && originalValue.clone) { this._originalValue[targetIndex] = originalValue.clone(); } else { this._originalValue[targetIndex] = originalValue; } } _registerTargetForLateAnimationBinding(runtimeAnimation, originalValue) { const target = runtimeAnimation.target; this._scene._registeredForLateAnimationBindings.pushNoDuplicate(target); if (!target._lateAnimationHolders) { target._lateAnimationHolders = {}; } if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) { target._lateAnimationHolders[runtimeAnimation.targetPath] = { totalWeight: 0, totalAdditiveWeight: 0, animations: [], additiveAnimations: [], 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; } } _setValue(target, destination, currentValue, weight, targetIndex) { this._currentActiveTarget = destination; this._weight = weight; if (this._enableBlending && this._blendingFactor <= 1) { if (!this._originalBlendValue) { const originalValue = destination[this._targetPath]; if (originalValue.clone) { this._originalBlendValue = originalValue.clone(); } else { this._originalBlendValue = originalValue; } } if (this._originalBlendValue.m) { if (Animation.AllowMatrixDecomposeForInterpolation) { if (this._currentValue) { Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue); } else { this._currentValue = Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor); } } else { if (this._currentValue) { Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue); } else { this._currentValue = Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor); } } } else { this._currentValue = Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor); } const blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed; this._blendingFactor += blendingSpeed; } else { if (!this._currentValue) { if (currentValue?.clone) { this._currentValue = currentValue.clone(); } else { this._currentValue = currentValue; } } else if (this._currentValue.copyFrom) { this._currentValue.copyFrom(currentValue); } else { this._currentValue = currentValue; } } if (weight !== -1) { this._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]); } else { if (this._animationState.loopMode === Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT) { if (this._currentValue.addToRef) { this._currentValue.addToRef(this._originalValue[targetIndex], destination[this._targetPath]); } else { destination[this._targetPath] = this._originalValue[targetIndex] + this._currentValue; } } 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 */ _getCorrectLoopMode() { 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 * @param weight defines the weight to apply to the animation (-1.0 by default) */ goToFrame(frame, weight = -1) { const 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; } const events = this._events; if (events.length) { for (let index = 0; index < events.length; index++) { if (!events[index].onlyOnce) { events[index].isDone = events[index].frame < frame; } } } this._currentFrame = frame; const currentValue = this._animation._interpolate(frame, this._animationState); this.setValue(currentValue, weight); } /** * @internal Internal use only */ _prepareForSpeedRatioChange(newSpeedRatio) { const newAbsoluteFrame = this._previousElapsedTime * (this._animation.framePerSecond * newSpeedRatio) / 1e3; this._absoluteFrameOffset = this._previousAbsoluteFrame - newAbsoluteFrame; } /** * Execute the current animation * @param elapsedTimeSinceAnimationStart defines the elapsed time (in milliseconds) since the animation was started * @param from defines the lower frame of the animation range * @param to defines the upper frame 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) * @returns a boolean indicating if the animation is running */ animate(elapsedTimeSinceAnimationStart, from, to, loop, speedRatio, weight = -1) { const animation = this._animation; const targetPropertyPath = animation.targetPropertyPath; if (!targetPropertyPath || targetPropertyPath.length < 1) { this._stopped = true; return false; } let returnValue = true; let currentFrame; const events = this._events; let frameRange = 0; if (!this._coreRuntimeAnimation) { if (from < this._minFrame || from > this._maxFrame) { from = this._minFrame; } if (to < this._minFrame || to > this._maxFrame) { to = this._maxFrame; } frameRange = to - from; let offsetValue; let absoluteFrame = elapsedTimeSinceAnimationStart * (animation.framePerSecond * speedRatio) / 1e3 + this._absoluteFrameOffset; let highLimitValue = 0; let yoyoLoop = false; const yoyoMode = loop && this._animationState.loopMode === Animation.ANIMATIONLOOPMODE_YOYO; if (yoyoMode) { const position = (absoluteFrame - from) / frameRange; const sin = Math.sin(position * Math.PI); const yoyoPosition = Math.abs(sin); absoluteFrame = yoyoPosition * frameRange + from; const direction = sin >= 0 ? 1 : -1; if (this._yoyoDirection !== direction) { yoyoLoop = true; } this._yoyoDirection = direction; } this._previousElapsedTime = elapsedTimeSinceAnimationStart; this._previousAbsoluteFrame = absoluteFrame; if (!loop && to >= from && (absoluteFrame >= frameRange && speedRatio > 0 || absoluteFrame <= 0 && speedRatio < 0)) { returnValue = false; highLimitValue = animation._getKeyValue(this._maxValue); } else if (!loop && from >= to && (absoluteFrame <= frameRange && speedRatio < 0 || absoluteFrame >= 0 && speedRatio > 0)) { returnValue = false; highLimitValue = animation._getKeyValue(this._minValue); } else if (this._animationState.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) { const keyOffset = to.toString() + from.toString(); if (!this._offsetsCache[keyOffset]) { this._animationState.repeatCount = 0; this._animationState.loopMode = Animation.ANIMATIONLOOPMODE_CYCLE; const fromValue = animation._interpolate(from, this._animationState); const toValue = animation._interpolate(to, this._animationState); this._animationState.loopMode = this._getCorrectLoopMode(); switch (animation.dataType) { // Float case Animation.ANIMATIONTYPE_FLOAT: this._offsetsCache[keyOffset] = toValue - fromValue; break; // Quaternion case Animation.ANIMATIONTYPE_QUATERNION: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); break; // Vector3 case Animation.ANIMATIONTYPE_VECTOR3: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); break; // Vector2 case Animation.ANIMATIONTYPE_VECTOR2: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); break; // Size case Animation.ANIMATIONTYPE_SIZE: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); break; // Color3 case Animation.ANIMATIONTYPE_COLOR3: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); break; default: break; } this._highLimitsCache[keyOffset] = toValue; } highLimitValue = this._highLimitsCache[keyOffset]; offsetValue = this._offsetsCache[keyOffset]; } if (offsetValue === void 0) { switch (animation.dataType) { // Float case Animation.ANIMATIONTYPE_FLOAT: offsetValue = 0; break; // Quaternion case Animation.ANIMATIONTYPE_QUATERNION: offsetValue = _StaticOffsetValueQuaternion; break; // Vector3 case Animation.ANIMATIONTYPE_VECTOR3: offsetValue = _StaticOffsetValueVector3; break; // Vector2 case Animation.ANIMATIONTYPE_VECTOR2: offsetValue = _StaticOffsetValueVector2; break; // Size case Animation.ANIMATIONTYPE_SIZE: offsetValue = _StaticOffsetValueSize; break; // Color3 case Animation.ANIMATIONTYPE_COLOR3: offsetValue = _StaticOffsetValueColor3; break; case Animation.ANIMATIONTYPE_COLOR4: offsetValue = _StaticOffsetValueColor4; break; } } if (this._host && this._host.syncRoot) { const syncRoot = this._host.syncRoot; const hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame); currentFrame = from + frameRange * hostNormalizedFrame; } else { if (absoluteFrame > 0 && from > to || absoluteFrame < 0 && from < to) { currentFrame = returnValue && frameRange !== 0 ? to + absoluteFrame % frameRange : from; } else { currentFrame = returnValue && frameRange !== 0 ? from + absoluteFrame % frameRange : to; } } if (!yoyoMode && (speedRatio > 0 && this.currentFrame > currentFrame || speedRatio < 0 && this.currentFrame < currentFrame) || yoyoMode && yoyoLoop) { this._onLoop(); for (let index = 0; index < events.length; index++) { if (!events[index].onlyOnce) { events[index].isDone = false; } } this._animationState.key = speedRatio > 0 ? 0 : animation.getKeys().length - 1; } this._currentFrame = currentFrame; this._animationState.repeatCount = frameRange === 0 ? 0 : absoluteFrame / frameRange >> 0; this._animationState.highLimitValue = highLimitValue; this._animationState.offsetValue = offsetValue; } else { frameRange = to - from; currentFrame = this._coreRuntimeAnimation.currentFrame; this._currentFrame = currentFrame; this._animationState.repeatCount = this._coreRuntimeAnimation._animationState.repeatCount; this._animationState.highLimitValue = this._coreRuntimeAnimation._animationState.highLimitValue; this._animationState.offsetValue = this._coreRuntimeAnimation._animationState.offsetValue; } const currentValue = animation._interpolate(currentFrame, this._animationState); this.setValue(currentValue, weight); if (events.length) { for (let index = 0; index < events.length; index++) { if (frameRange >= 0 && currentFrame >= events[index].frame && events[index].frame >= from || frameRange < 0 && currentFrame <= events[index].frame && events[index].frame <= from) { const event = events[index]; if (!event.isDone) { if (event.onlyOnce) { events.splice(index, 1); index--; } event.isDone = true; event.action(currentFrame); } } } } if (!returnValue) { this._stopped = true; } return returnValue; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Animations/animatable.core.js init_observable(); init_precisionDate(); init_math_vector(); var Animatable = class _Animatable { static { __name(this, "Animatable"); } /** * Gets the root Animatable used to synchronize and normalize animations */ get syncRoot() { return this._syncRoot; } /** * Gets the current frame of the first RuntimeAnimation * Used to synchronize Animatables */ get masterFrame() { if (this._runtimeAnimations.length === 0) { return 0; } return this._runtimeAnimations[0].currentFrame; } /** * Gets or sets the animatable weight (-1.0 by default meaning not weighted) */ get weight() { return this._weight; } set weight(value) { if (value === -1) { this._weight = -1; return; } this._weight = Math.min(Math.max(value, 0), 1); } /** * Gets or sets the speed ratio to apply to the animatable (1.0 by default) */ get speedRatio() { return this._speedRatio; } set speedRatio(value) { for (let index = 0; index < this._runtimeAnimations.length; index++) { const animation = this._runtimeAnimations[index]; animation._prepareForSpeedRatioChange(value); } this._speedRatio = value; if (this._goToFrame !== null) { this.goToFrame(this._goToFrame); } } /** * Gets the elapsed time since the animatable started in milliseconds */ get elapsedTime() { return this._localDelayOffset === null ? 0 : this._scene._animationTime - this._localDelayOffset; } /** * 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 * @param playOrder defines the order in which this animatable should be processed in the list of active animatables (default: 0) */ constructor(scene, target, fromFrame = 0, toFrame = 100, loopAnimation = false, speedRatio = 1, onAnimationEnd, animations, onAnimationLoop, isAdditive = false, playOrder = 0) { this.target = target; this.fromFrame = fromFrame; this.toFrame = toFrame; this.loopAnimation = loopAnimation; this.onAnimationEnd = onAnimationEnd; this.onAnimationLoop = onAnimationLoop; this.isAdditive = isAdditive; this.playOrder = playOrder; this._localDelayOffset = null; this._pausedDelay = null; this._manualJumpDelay = null; this._runtimeAnimations = new Array(); this._paused = false; this._speedRatio = 1; this._weight = -1; this._previousWeight = -1; this._syncRoot = null; this._frameToSyncFromJump = null; this._goToFrame = null; this.disposeOnEnd = true; this.animationStarted = false; this.onAnimationEndObservable = new Observable(); this.onAnimationLoopObservable = new Observable(); this._scene = scene; if (animations) { this.appendAnimations(target, animations); } this._speedRatio = speedRatio; scene._activeAnimatables.push(this); } // 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 (null to stop synchronizing) * @returns the current Animatable */ syncWith(root) { this._syncRoot = root; if (root) { const 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 */ getAnimations() { 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 */ appendAnimations(target, animations) { for (let index = 0; index < animations.length; index++) { const animation = animations[index]; const newRuntimeAnimation = new RuntimeAnimation(target, animation, this._scene, this); newRuntimeAnimation._onLoop = () => { 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 property to look for * @returns null or the source animation for the given property */ getAnimationByTargetProperty(property) { const runtimeAnimations = this._runtimeAnimations; for (let 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 property to look for * @returns null or the runtime animation for the given property */ getRuntimeAnimationByTargetProperty(property) { const runtimeAnimations = this._runtimeAnimations; for (let index = 0; index < runtimeAnimations.length; index++) { if (runtimeAnimations[index].animation.targetProperty === property) { return runtimeAnimations[index]; } } return null; } /** * Resets the animatable to its original state */ reset() { const runtimeAnimations = this._runtimeAnimations; for (let 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/features/featuresDeepDive/animation/advanced_animations#animation-blending * @param blendingSpeed defines the blending speed to use */ enableBlending(blendingSpeed) { const runtimeAnimations = this._runtimeAnimations; for (let index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].animation.enableBlending = true; runtimeAnimations[index].animation.blendingSpeed = blendingSpeed; } } /** * Disable animation blending * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-blending */ disableBlending() { const runtimeAnimations = this._runtimeAnimations; for (let 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 * @param useWeight defines whether the animation weight should be applied to the image to be jumped to (false by default) */ goToFrame(frame, useWeight = false) { const runtimeAnimations = this._runtimeAnimations; if (runtimeAnimations[0]) { const fps = runtimeAnimations[0].animation.framePerSecond; this._frameToSyncFromJump = this._frameToSyncFromJump ?? runtimeAnimations[0].currentFrame; const delay = this.speedRatio === 0 ? 0 : (frame - this._frameToSyncFromJump) / fps * 1e3 / this.speedRatio; this._manualJumpDelay = -delay; } for (let index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].goToFrame(frame, useWeight ? this._weight : -1); } this._goToFrame = frame; } /** * Returns true if the animations for this animatable are paused */ get paused() { return this._paused; } /** * Pause the animation */ pause() { if (this._paused) { return; } this._paused = true; } /** * Restart the animation */ restart() { this._paused = false; } _raiseOnAnimationEnd() { 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) * @param useGlobalSplice if true, the animatables will be removed by the caller of this function (false by default) * @param skipOnAnimationEnd defines if the system should not raise onAnimationEnd. Default is false */ stop(animationName, targetMask, useGlobalSplice = false, skipOnAnimationEnd = false) { if (animationName || targetMask) { const idx = this._scene._activeAnimatables.indexOf(this); if (idx > -1) { const runtimeAnimations = this._runtimeAnimations; for (let index = runtimeAnimations.length - 1; index >= 0; index--) { const 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) { if (!useGlobalSplice) { this._scene._activeAnimatables.splice(idx, 1); } if (!skipOnAnimationEnd) { this._raiseOnAnimationEnd(); } } } } else { const index = this._scene._activeAnimatables.indexOf(this); if (index > -1) { if (!useGlobalSplice) { this._scene._activeAnimatables.splice(index, 1); } const runtimeAnimations = this._runtimeAnimations; for (let index2 = 0; index2 < runtimeAnimations.length; index2++) { runtimeAnimations[index2].dispose(); } this._runtimeAnimations.length = 0; if (!skipOnAnimationEnd) { this._raiseOnAnimationEnd(); } } } } /** * Wait asynchronously for the animation to end * @returns a promise which will be fulfilled when the animation ends */ async waitAsync() { return await new Promise((resolve) => { this.onAnimationEndObservable.add(() => { resolve(this); }, void 0, void 0, this, true); }); } /** * @internal */ _animate(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._manualJumpDelay !== null) { this._localDelayOffset += this.speedRatio < 0 ? -this._manualJumpDelay : this._manualJumpDelay; this._manualJumpDelay = null; this._frameToSyncFromJump = null; } this._goToFrame = null; if (!_Animatable.ProcessPausedAnimatables && this._weight === 0 && this._previousWeight === 0) { return true; } this._previousWeight = this._weight; let running = false; const runtimeAnimations = this._runtimeAnimations; let index; for (index = 0; index < runtimeAnimations.length; index++) { const animation = runtimeAnimations[index]; const 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) { index = this._scene._activeAnimatables.indexOf(this); this._scene._activeAnimatables.splice(index, 1); 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; } }; Animatable.ProcessPausedAnimatables = false; function ProcessLateAnimationBindingsForMatrices(holder) { if (holder.totalWeight === 0 && holder.totalAdditiveWeight === 0) { return holder.originalValue; } let normalizer = 1; const finalPosition = TmpVectors.Vector3[0]; const finalScaling = TmpVectors.Vector3[1]; const finalQuaternion = TmpVectors.Quaternion[0]; let startIndex = 0; const originalAnimation = holder.animations[0]; const originalValue = holder.originalValue; let scale = 1; let skipOverride = false; if (holder.totalWeight < 1) { scale = 1 - holder.totalWeight; originalValue.decompose(finalScaling, finalQuaternion, finalPosition); } else { startIndex = 1; 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); } if (!skipOverride) { finalScaling.scaleInPlace(scale); finalPosition.scaleInPlace(scale); finalQuaternion.scaleInPlace(scale); for (let animIndex = startIndex; animIndex < holder.animations.length; animIndex++) { const runtimeAnimation = holder.animations[animIndex]; if (runtimeAnimation.weight === 0) { continue; } scale = runtimeAnimation.weight / normalizer; const currentPosition = TmpVectors.Vector3[2]; const currentScaling = TmpVectors.Vector3[3]; const currentQuaternion = TmpVectors.Quaternion[1]; runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition); currentScaling.scaleAndAddToRef(scale, finalScaling); currentQuaternion.scaleAndAddToRef(Quaternion.Dot(finalQuaternion, currentQuaternion) > 0 ? scale : -scale, finalQuaternion); currentPosition.scaleAndAddToRef(scale, finalPosition); } finalQuaternion.normalize(); } for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) { const runtimeAnimation = holder.additiveAnimations[animIndex]; if (runtimeAnimation.weight === 0) { continue; } const currentPosition = TmpVectors.Vector3[2]; const currentScaling = TmpVectors.Vector3[3]; const currentQuaternion = TmpVectors.Quaternion[1]; runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition); currentScaling.multiplyToRef(finalScaling, currentScaling); Vector3.LerpToRef(finalScaling, currentScaling, runtimeAnimation.weight, finalScaling); finalQuaternion.multiplyToRef(currentQuaternion, currentQuaternion); Quaternion.SlerpToRef(finalQuaternion, currentQuaternion, runtimeAnimation.weight, finalQuaternion); currentPosition.scaleAndAddToRef(runtimeAnimation.weight, finalPosition); } const workValue = originalAnimation ? originalAnimation._animationState.workValue : TmpVectors.Matrix[0].clone(); Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, workValue); return workValue; } __name(ProcessLateAnimationBindingsForMatrices, "ProcessLateAnimationBindingsForMatrices"); function ProcessLateAnimationBindingsForQuaternions(holder, refQuaternion) { if (holder.totalWeight === 0 && holder.totalAdditiveWeight === 0) { return refQuaternion; } const originalAnimation = holder.animations[0]; const originalValue = holder.originalValue; let cumulativeQuaternion = refQuaternion; if (holder.totalWeight === 0 && holder.totalAdditiveWeight > 0) { cumulativeQuaternion.copyFrom(originalValue); } else if (holder.animations.length === 1) { Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1, holder.totalWeight), cumulativeQuaternion); if (holder.totalAdditiveWeight === 0) { return cumulativeQuaternion; } } else if (holder.animations.length > 1) { let normalizer = 1; let quaternions; let weights; if (holder.totalWeight < 1) { const scale = 1 - holder.totalWeight; quaternions = []; weights = []; quaternions.push(originalValue); weights.push(scale); } else { if (holder.animations.length === 2) { 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 (let animIndex = 0; animIndex < holder.animations.length; animIndex++) { const runtimeAnimation = holder.animations[animIndex]; quaternions.push(runtimeAnimation.currentValue); weights.push(runtimeAnimation.weight / normalizer); } let cumulativeAmount = 0; for (let index = 0; index < quaternions.length; ) { if (!index) { 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]; Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion); index++; } } for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) { const runtimeAnimation = holder.additiveAnimations[animIndex]; if (runtimeAnimation.weight === 0) { continue; } cumulativeQuaternion.multiplyToRef(runtimeAnimation.currentValue, TmpVectors.Quaternion[0]); Quaternion.SlerpToRef(cumulativeQuaternion, TmpVectors.Quaternion[0], runtimeAnimation.weight, cumulativeQuaternion); } return cumulativeQuaternion; } __name(ProcessLateAnimationBindingsForQuaternions, "ProcessLateAnimationBindingsForQuaternions"); function ProcessLateAnimationBindings(scene) { if (!scene._registeredForLateAnimationBindings.length) { return; } for (let index = 0; index < scene._registeredForLateAnimationBindings.length; index++) { const target = scene._registeredForLateAnimationBindings.data[index]; for (const path in target._lateAnimationHolders) { const holder = target._lateAnimationHolders[path]; const originalAnimation = holder.animations[0]; const originalValue = holder.originalValue; if (originalValue === void 0 || originalValue === null) { continue; } const matrixDecomposeMode = Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; let finalValue = target[path]; if (matrixDecomposeMode) { finalValue = ProcessLateAnimationBindingsForMatrices(holder); } else { const quaternionMode = originalValue.w !== void 0; if (quaternionMode) { finalValue = ProcessLateAnimationBindingsForQuaternions(holder, finalValue || Quaternion.Identity()); } else { let startIndex = 0; let normalizer = 1; const originalAnimationIsLoopRelativeFromCurrent = originalAnimation && originalAnimation._animationState.loopMode === Animation.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT; if (holder.totalWeight < 1) { if (originalAnimationIsLoopRelativeFromCurrent) { finalValue = originalValue.clone ? originalValue.clone() : originalValue; } else if (originalAnimation && originalValue.scale) { finalValue = originalValue.scale(1 - holder.totalWeight); } else if (originalAnimation) { finalValue = originalValue * (1 - holder.totalWeight); } else if (originalValue.clone) { finalValue = originalValue.clone(); } else { finalValue = originalValue; } } else if (originalAnimation) { normalizer = holder.totalWeight; const scale = originalAnimation.weight / normalizer; if (scale !== 1) { if (originalAnimation.currentValue.scale) { finalValue = originalAnimation.currentValue.scale(scale); } else { finalValue = originalAnimation.currentValue * scale; } } else { finalValue = originalAnimation.currentValue; } if (originalAnimationIsLoopRelativeFromCurrent) { if (finalValue.addToRef) { finalValue.addToRef(originalValue, finalValue); } else { finalValue += originalValue; } } startIndex = 1; } for (let animIndex = startIndex; animIndex < holder.animations.length; animIndex++) { const runtimeAnimation = holder.animations[animIndex]; const scale = runtimeAnimation.weight / normalizer; if (!scale) { continue; } else if (runtimeAnimation.currentValue.scaleAndAddToRef) { runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue); } else { finalValue += runtimeAnimation.currentValue * scale; } } for (let animIndex = 0; animIndex < holder.additiveAnimations.length; animIndex++) { const runtimeAnimation = holder.additiveAnimations[animIndex]; const 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 = {}; } scene._registeredForLateAnimationBindings.reset(); } __name(ProcessLateAnimationBindings, "ProcessLateAnimationBindings"); function RegisterTargetForLateAnimationBinding(scene, runtimeAnimation, originalValue) { const target = runtimeAnimation.target; scene._registeredForLateAnimationBindings.pushNoDuplicate(target); if (!target._lateAnimationHolders) { target._lateAnimationHolders = {}; } if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) { target._lateAnimationHolders[runtimeAnimation.targetPath] = { totalWeight: 0, totalAdditiveWeight: 0, animations: [], additiveAnimations: [], 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; } } __name(RegisterTargetForLateAnimationBinding, "RegisterTargetForLateAnimationBinding"); function AddAnimationExtensions(sceneClass, boneClass) { if (boneClass) { boneClass.prototype.copyAnimationRange = function(source, rangeName, frameOffset, rescaleAsRequired = false, skelDimensionsRatio = null) { if (this.animations.length === 0) { this.animations.push(new Animation(this.name, "_matrix", source.animations[0].framePerSecond, Animation.ANIMATIONTYPE_MATRIX, 0)); this.animations[0].setKeys([]); } const sourceRange = source.animations[0].getRange(rangeName); if (!sourceRange) { return false; } const from = sourceRange.from; const to = sourceRange.to; const sourceKeys = source.animations[0].getKeys(); const sourceBoneLength = source.length; const sourceParent = source.getParent(); const parent = this.getParent(); const parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length; const parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1; const dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1); const destKeys = this.animations[0].getKeys(); let orig; let origTranslation; let mat; for (let key = 0, nKeys = sourceKeys.length; key < nKeys; key++) { orig = sourceKeys[key]; if (orig.frame >= from && orig.frame <= to) { if (rescaleAsRequired) { mat = orig.value.clone(); if (parentScalingReqd) { origTranslation = mat.getTranslation(); mat.setTranslation(origTranslation.scaleInPlace(parentRatio)); } else if (dimensionsScalingReqd && skelDimensionsRatio) { origTranslation = mat.getTranslation(); mat.setTranslation(origTranslation.multiplyInPlace(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; }; } if (!sceneClass) { return; } sceneClass.prototype._animate = function(customDeltaTime) { if (!this.animationsEnabled) { return; } const now = PrecisionDate.Now; if (!this._animationTimeLast) { if (this._pendingData.length > 0) { return; } this._animationTimeLast = now; } this.deltaTime = customDeltaTime !== void 0 ? customDeltaTime : this.useConstantAnimationDeltaTime ? 16 : (now - this._animationTimeLast) * this.animationTimeScale; this._animationTimeLast = now; const animatables = this._activeAnimatables; if (animatables.length === 0) { return; } this._animationTime += this.deltaTime; const animationTime = this._animationTime; for (let index = 0; index < animatables.length; index++) { const animatable = animatables[index]; if (!animatable._animate(animationTime) && animatable.disposeOnEnd) { index--; } } ProcessLateAnimationBindings(this); }; sceneClass.prototype.sortActiveAnimatables = function() { this._activeAnimatables.sort((a, b) => { return a.playOrder - b.playOrder; }); }; sceneClass.prototype.beginWeightedAnimation = function(target, from, to, weight = 1, loop, speedRatio = 1, onAnimationEnd, animatable, targetMask, onAnimationLoop, isAdditive = false) { const returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask, onAnimationLoop, isAdditive); returnedAnimatable.weight = weight; return returnedAnimatable; }; sceneClass.prototype.beginAnimation = function(target, from, to, loop, speedRatio = 1, onAnimationEnd, animatable, stopCurrent = true, targetMask, onAnimationLoop, isAdditive = false) { if (speedRatio < 0) { const tmp = from; from = to; to = tmp; speedRatio = -speedRatio; } if (from > to) { speedRatio = -speedRatio; } if (stopCurrent) { this.stopAnimation(target, void 0, targetMask); } if (!animatable) { animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, void 0, onAnimationLoop, isAdditive); } const shouldRunTargetAnimations = targetMask ? targetMask(target) : true; if (target.animations && shouldRunTargetAnimations) { animatable.appendAnimations(target, target.animations); } if (target.getAnimatables) { const animatables = target.getAnimatables(); for (let index = 0; index < animatables.length; index++) { this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop); } } animatable.reset(); return animatable; }; sceneClass.prototype.beginHierarchyAnimation = function(target, directDescendantsOnly, from, to, loop, speedRatio = 1, onAnimationEnd, animatable, stopCurrent = true, targetMask, onAnimationLoop, isAdditive = false) { const children = target.getDescendants(directDescendantsOnly); const result = []; result.push(this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, void 0, isAdditive)); for (const child of children) { result.push(this.beginAnimation(child, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, void 0, isAdditive)); } return result; }; sceneClass.prototype.beginDirectAnimation = function(target, animations, from, to, loop, speedRatio = 1, onAnimationEnd, onAnimationLoop, isAdditive = false) { if (speedRatio < 0) { const tmp = from; from = to; to = tmp; speedRatio = -speedRatio; } if (from > to) { speedRatio = -speedRatio; } const animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations, onAnimationLoop, isAdditive); return animatable; }; sceneClass.prototype.beginDirectHierarchyAnimation = function(target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive = false) { const children = target.getDescendants(directDescendantsOnly); const result = []; result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive)); for (const child of children) { result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive)); } return result; }; sceneClass.prototype.getAnimatableByTarget = function(target) { for (let index = 0; index < this._activeAnimatables.length; index++) { if (this._activeAnimatables[index].target === target) { return this._activeAnimatables[index]; } } return null; }; sceneClass.prototype.getAllAnimatablesByTarget = function(target) { const result = []; for (let index = 0; index < this._activeAnimatables.length; index++) { if (this._activeAnimatables[index].target === target) { result.push(this._activeAnimatables[index]); } } return result; }; sceneClass.prototype.stopAnimation = function(target, animationName, targetMask) { const animatables = this.getAllAnimatablesByTarget(target); for (const animatable of animatables) { animatable.stop(animationName, targetMask); } }; sceneClass.prototype.stopAllAnimations = function() { if (this._activeAnimatables) { for (let i = 0; i < this._activeAnimatables.length; i++) { this._activeAnimatables[i].stop(void 0, void 0, true); } this._activeAnimatables.length = 0; } for (const group of this.animationGroups) { group.stop(); } }; } __name(AddAnimationExtensions, "AddAnimationExtensions"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Animations/animatable.js init_scene(); AddAnimationExtensions(Scene, Bone); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Rendering/geometryBufferRendererSceneComponent.js init_scene(); init_sceneComponent(); Object.defineProperty(Scene.prototype, "geometryBufferRenderer", { get: /* @__PURE__ */ __name(function() { return this._geometryBufferRenderer; }, "get"), set: /* @__PURE__ */ __name(function(value) { if (value && value.isSupported) { this._geometryBufferRenderer = value; } }, "set"), enumerable: true, configurable: true }); Scene.prototype.enableGeometryBufferRenderer = function(ratio = 1, depthFormat = 15, textureTypesAndFormats) { if (this._geometryBufferRenderer) { return this._geometryBufferRenderer; } this._geometryBufferRenderer = new GeometryBufferRenderer(this, ratio, depthFormat, textureTypesAndFormats); if (!this._geometryBufferRenderer.isSupported) { this._geometryBufferRenderer = null; } return this._geometryBufferRenderer; }; Scene.prototype.disableGeometryBufferRenderer = function() { if (!this._geometryBufferRenderer) { return; } this._geometryBufferRenderer.dispose(); this._geometryBufferRenderer = null; }; var GeometryBufferRendererSceneComponent = class { static { __name(this, "GeometryBufferRendererSceneComponent"); } /** * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ constructor(scene) { this.name = SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER; this.scene = scene; } /** * Registers the component in a given scene */ register() { this.scene._gatherRenderTargetsStage.registerStep(SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets); } /** * Rebuilds the elements related to this component in case of * context lost for instance. */ rebuild() { } /** * Disposes the component and the associated resources */ dispose() { } _gatherRenderTargets(renderTargets) { if (this.scene._geometryBufferRenderer) { renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer()); } } }; GeometryBufferRenderer._SceneComponentInitialization = (scene) => { let component = scene._getComponent(SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER); if (!component) { component = new GeometryBufferRendererSceneComponent(scene); scene._addComponent(component); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinMotionBlurPostProcess.js init_effectRenderer(); init_math_vector(); var ThinMotionBlurPostProcess = class _ThinMotionBlurPostProcess extends EffectWrapper { static { __name(this, "ThinMotionBlurPostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_motionBlur_fragment(), motionBlur_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_motionBlur_fragment2(), motionBlur_fragment_exports2))); } } /** * Constructs a new motion blur post process * @param name Name of the effect * @param scene The scene the effect belongs to * @param options Options to configure the effect */ constructor(name260, scene, options) { super({ ...options, name: name260, engine: scene.getEngine(), useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinMotionBlurPostProcess.FragmentUrl, uniforms: _ThinMotionBlurPostProcess.Uniforms, samplers: _ThinMotionBlurPostProcess.Samplers, defines: _ThinMotionBlurPostProcess.Defines }); this._invViewProjection = Matrix.Identity(); this._previousViewProjection = Matrix.Identity(); this.motionStrength = 1; this._motionBlurSamples = 32; this._isObjectBased = true; this.textureWidth = 0; this.textureHeight = 0; this._scene = scene; this._applyMode(); } /** * Gets the number of iterations that are used for motion blur quality. Default value is equal to 32 */ get motionBlurSamples() { return this._motionBlurSamples; } /** * Sets the number of iterations to be used for motion blur quality */ set motionBlurSamples(samples) { this._motionBlurSamples = samples; this._updateEffect(); } /** * Gets whether or not the motion blur post-process is in object based mode. */ get isObjectBased() { return this._isObjectBased; } /** * Sets whether or not the motion blur post-process is in object based mode. */ set isObjectBased(value) { if (this._isObjectBased === value) { return; } this._isObjectBased = value; this._applyMode(); } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); const effect = this._drawWrapper.effect; effect.setFloat2("screenSize", this.textureWidth, this.textureHeight); effect.setFloat("motionScale", this._scene.getAnimationRatio()); effect.setFloat("motionStrength", this.motionStrength); if (!this.isObjectBased) { const viewProjection = TmpVectors.Matrix[0]; viewProjection.copyFrom(this._scene.getTransformMatrix()); viewProjection.invertToRef(this._invViewProjection); effect.setMatrix("inverseViewProjection", this._invViewProjection); effect.setMatrix("prevViewProjection", this._previousViewProjection); this._previousViewProjection.copyFrom(viewProjection); effect.setMatrix("projection", this._scene.getProjectionMatrix()); } } _updateEffect() { const defines = [ "#define GEOMETRY_SUPPORTED", "#define SAMPLES " + this._motionBlurSamples.toFixed(1), this._isObjectBased ? "#define OBJECT_BASED" : "#define SCREEN_BASED" ]; this.updateEffect(defines.join("\n")); } _applyMode() { this._updateEffect(); this._previousViewProjection.copyFrom(this._scene.getTransformMatrix()); } }; ThinMotionBlurPostProcess.FragmentUrl = "motionBlur"; ThinMotionBlurPostProcess.Uniforms = ["motionStrength", "motionScale", "screenSize", "inverseViewProjection", "prevViewProjection", "projection"]; ThinMotionBlurPostProcess.Samplers = ["velocitySampler", "depthSampler"]; ThinMotionBlurPostProcess.Defines = "#define GEOMETRY_SUPPORTED\n#define SAMPLES 64.0\n#define OBJECT_BASED"; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/motionBlurPostProcess.js init_tslib_es6(); init_logger(); init_postProcess(); init_decorators(); init_decorators_serialization(); init_typeStore(); var MotionBlurPostProcess = class _MotionBlurPostProcess extends PostProcess { static { __name(this, "MotionBlurPostProcess"); } /** * Defines how much the image is blurred by the movement. Default value is equal to 1 */ get motionStrength() { return this._effectWrapper.motionStrength; } set motionStrength(value) { this._effectWrapper.motionStrength = value; } /** * Gets the number of iterations are used for motion blur quality. Default value is equal to 32 */ get motionBlurSamples() { return this._effectWrapper.motionBlurSamples; } /** * Sets the number of iterations to be used for motion blur quality */ set motionBlurSamples(samples) { this._effectWrapper.motionBlurSamples = samples; } /** * Gets whether or not the motion blur post-process is in object based mode. */ get isObjectBased() { return this._effectWrapper.isObjectBased; } /** * Sets whether or not the motion blur post-process is in object based mode. */ set isObjectBased(value) { if (this.isObjectBased === value) { return; } this._effectWrapper.isObjectBased = value; this._applyMode(); } get _geometryBufferRenderer() { if (!this._forceGeometryBuffer) { return null; } return this._forcedGeometryBuffer ?? this._scene.geometryBufferRenderer; } get _prePassRenderer() { if (this._forceGeometryBuffer) { return null; } return this._scene.prePassRenderer; } /** * Gets a string identifying the name of the class * @returns "MotionBlurPostProcess" string */ getClassName() { return "MotionBlurPostProcess"; } /** * Creates a new instance MotionBlurPostProcess * @param name The name of the effect. * @param scene The scene containing the objects to blur according to their velocity. * @param options The required width/height ratio to downsize to before computing the render pass. * @param camera The camera to apply the render pass to. * @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 blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: true) * @param forceGeometryBuffer If this post process should use geometry buffer instead of prepass (default: false) */ constructor(name260, scene, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false, forceGeometryBuffer = false) { const localOptions = { uniforms: ThinMotionBlurPostProcess.Uniforms, samplers: ThinMotionBlurPostProcess.Samplers, defines: ThinMotionBlurPostProcess.Defines, size: typeof options === "number" ? options : void 0, camera, samplingMode, engine, reusable, textureType, blockCompilation, ...options }; super(name260, ThinMotionBlurPostProcess.FragmentUrl, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinMotionBlurPostProcess(name260, scene, localOptions) : void 0, ...localOptions }); this._forcedGeometryBuffer = null; this._forceGeometryBuffer = false; if (forceGeometryBuffer instanceof GeometryBufferRenderer) { this._forceGeometryBuffer = true; this._forcedGeometryBuffer = forceGeometryBuffer; } else { this._forceGeometryBuffer = forceGeometryBuffer; } if (this._forceGeometryBuffer) { if (!this._forcedGeometryBuffer) { scene.enableGeometryBufferRenderer(); } if (this._geometryBufferRenderer) { this._geometryBufferRenderer.enableVelocity = this.isObjectBased; } } else { scene.enablePrePassRenderer(); if (this._prePassRenderer) { this._prePassRenderer.markAsDirty(); this._prePassEffectConfiguration = new MotionBlurConfiguration(); } } this._applyMode(); } /** * Excludes the given skinned mesh from computing bones velocities. * Computing bones velocities can have a cost and that cost. The cost can be saved by calling this function and by passing the skinned mesh reference to ignore. * @param skinnedMesh The mesh containing the skeleton to ignore when computing the velocity map. */ excludeSkinnedMesh(skinnedMesh) { if (skinnedMesh.skeleton) { let list; if (this._geometryBufferRenderer) { list = this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity; } else if (this._prePassRenderer) { list = this._prePassRenderer.excludedSkinnedMesh; } else { return; } list.push(skinnedMesh); } } /** * Removes the given skinned mesh from the excluded meshes to integrate bones velocities while rendering the velocity map. * @param skinnedMesh The mesh containing the skeleton that has been ignored previously. * @see excludeSkinnedMesh to exclude a skinned mesh from bones velocity computation. */ removeExcludedSkinnedMesh(skinnedMesh) { if (skinnedMesh.skeleton) { let list; if (this._geometryBufferRenderer) { list = this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity; } else if (this._prePassRenderer) { list = this._prePassRenderer.excludedSkinnedMesh; } else { return; } const index = list.indexOf(skinnedMesh); if (index !== -1) { list.splice(index, 1); } } } /** * Disposes the post process. * @param camera The camera to dispose the post process on. */ dispose(camera) { if (this._geometryBufferRenderer && !this._forcedGeometryBuffer) { this._geometryBufferRenderer._previousTransformationMatrices = {}; this._geometryBufferRenderer._previousBonesTransformationMatrices = {}; this._geometryBufferRenderer.excludedSkinnedMeshesFromVelocity = []; } super.dispose(camera); } /** * Called on the mode changed (object based or screen based). */ _applyMode() { if (!this._geometryBufferRenderer && !this._prePassRenderer) { Logger.Warn("Multiple Render Target support needed to compute object based motion blur"); return; } if (this._geometryBufferRenderer) { this._geometryBufferRenderer.enableVelocity = this.isObjectBased; } if (this.isObjectBased) { if (this._prePassRenderer && this._prePassEffectConfiguration) { this._prePassEffectConfiguration.texturesRequired[0] = 2; } this.onApply = (effect) => this._onApplyObjectBased(effect); } else { if (this._prePassRenderer && this._prePassEffectConfiguration) { this._prePassEffectConfiguration.texturesRequired[0] = 5; } this.onApply = (effect) => this._onApplyScreenBased(effect); } } /** * Called on the effect is applied when the motion blur post-process is in object based mode. * @param effect */ _onApplyObjectBased(effect) { this._effectWrapper.textureWidth = this.width; this._effectWrapper.textureHeight = this.height; if (this._geometryBufferRenderer) { const velocityIndex = this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.VELOCITY_TEXTURE_TYPE); effect.setTexture("velocitySampler", this._geometryBufferRenderer.getGBuffer().textures[velocityIndex]); } else if (this._prePassRenderer) { const velocityIndex = this._prePassRenderer.getIndex(2); effect.setTexture("velocitySampler", this._prePassRenderer.getRenderTarget().textures[velocityIndex]); } } /** * Called on the effect is applied when the motion blur post-process is in screen based mode. * @param effect */ _onApplyScreenBased(effect) { this._effectWrapper.textureWidth = this.width; this._effectWrapper.textureHeight = this.height; if (this._geometryBufferRenderer) { const depthIndex = this._geometryBufferRenderer.getTextureIndex(GeometryBufferRenderer.DEPTH_TEXTURE_TYPE); effect.setTexture("depthSampler", this._geometryBufferRenderer.getGBuffer().textures[depthIndex]); } else if (this._prePassRenderer) { const depthIndex = this._prePassRenderer.getIndex(5); effect.setTexture("depthSampler", this._prePassRenderer.getRenderTarget().textures[depthIndex]); } } /** * @internal */ static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { return SerializationHelper.Parse(() => { return new _MotionBlurPostProcess(parsedPostProcess.name, scene, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, false); }, parsedPostProcess, scene, rootUrl); } }; __decorate([ serialize() ], MotionBlurPostProcess.prototype, "motionStrength", null); __decorate([ serialize() ], MotionBlurPostProcess.prototype, "motionBlurSamples", null); __decorate([ serialize() ], MotionBlurPostProcess.prototype, "isObjectBased", null); RegisterClass("BABYLON.MotionBlurPostProcess", MotionBlurPostProcess); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/rendering/motion-blur.js var motionBlurPostProcess = null; var motionBlurPostProcessCameraConfigurations = /* @__PURE__ */ new Map(); function getMotionBlurPostProcess() { return motionBlurPostProcess; } __name(getMotionBlurPostProcess, "getMotionBlurPostProcess"); function setMotionBlurPostProcessRef(postProcess) { motionBlurPostProcess = postProcess; } __name(setMotionBlurPostProcessRef, "setMotionBlurPostProcessRef"); function disposeMotionBlurPostProcess() { if (motionBlurPostProcess) { motionBlurPostProcess.dispose(); motionBlurPostProcess = null; } } __name(disposeMotionBlurPostProcess, "disposeMotionBlurPostProcess"); function createMotionBlurPostProcess(scene, camera) { motionBlurPostProcess = new MotionBlurPostProcess("MotionBlurPostProcess", scene, 1, camera); motionBlurPostProcess.motionStrength = 1; motionBlurPostProcess.isObjectBased = true; return motionBlurPostProcess; } __name(createMotionBlurPostProcess, "createMotionBlurPostProcess"); function serializeMotionBlurPostProcess() { if (!motionBlurPostProcess) { return null; } return { isObjectBased: motionBlurPostProcess.isObjectBased, motionStrength: motionBlurPostProcess.motionStrength, motionBlurSamples: motionBlurPostProcess.motionBlurSamples }; } __name(serializeMotionBlurPostProcess, "serializeMotionBlurPostProcess"); function parseMotionBlurPostProcess(scene, camera, data) { if (motionBlurPostProcess) { return motionBlurPostProcess; } const postProcess = createMotionBlurPostProcess(scene, camera); postProcess.isObjectBased = data.isObjectBased; postProcess.motionStrength = data.motionStrength; postProcess.motionBlurSamples = data.motionBlurSamples; return postProcess; } __name(parseMotionBlurPostProcess, "parseMotionBlurPostProcess"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/colorGradingTexture.js init_math_vector(); init_baseTexture(); init_typeStore(); var ColorGradingTexture = class _ColorGradingTexture extends BaseTexture { static { __name(this, "ColorGradingTexture"); } /** * Instantiates a ColorGradingTexture from the following parameters. * * @param url The location of the color grading data (currently only supporting 3dl) * @param sceneOrEngine The scene or engine the texture will be used in * @param onLoad defines a callback triggered when the texture has been loaded */ constructor(url, sceneOrEngine, onLoad = null) { super(sceneOrEngine); if (!url) { return; } this._textureMatrix = Matrix.Identity(); this.name = url; this.url = url; this._onLoad = onLoad; this._texture = this._getFromCache(url, true); if (!this._texture) { const scene = this.getScene(); if (scene) { if (!scene.useDelayedTextureLoading) { this._loadTexture(); } else { this.delayLoadState = 4; } } else { this._loadTexture(); } } else { this._triggerOnLoad(); } } /** * Fires the onload event from the constructor if requested. */ _triggerOnLoad() { if (this._onLoad) { this._onLoad(); } } /** * @returns the texture matrix used in most of the material. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in). */ getTextureMatrix() { return this._textureMatrix; } /** * Occurs when the file being loaded is a .3dl LUT file. * @returns the 3D LUT texture */ _load3dlTexture() { const engine = this._getEngine(); let texture; if (!engine._features.support3DTextures) { texture = engine.createRawTexture(null, 1, 1, 5, false, false, 2, null, 0); } else { texture = engine.createRawTexture3D(null, 1, 1, 1, 5, false, false, 2, null, 0); } this._texture = texture; this._texture.isReady = false; this.isCube = false; this.is3D = engine._features.support3DTextures; this.wrapU = 0; this.wrapV = 0; this.wrapR = 0; this.anisotropicFilteringLevel = 1; const callback = /* @__PURE__ */ __name((text) => { if (typeof text !== "string") { return; } let data = null; let tempData = null; let line; const lines = text.split("\n"); let size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0; let maxColor = 0; for (let i = 0; i < lines.length; i++) { line = lines[i]; if (!_ColorGradingTexture._NoneEmptyLineRegex.test(line)) { continue; } if (line.indexOf("#") === 0) { continue; } const words = line.split(" "); if (size === 0) { size = words.length; data = new Uint8Array(size * size * size * 4); tempData = new Float32Array(size * size * size * 4); continue; } if (size != 0) { const r = Math.max(parseInt(words[0]), 0); const g = Math.max(parseInt(words[1]), 0); const b = Math.max(parseInt(words[2]), 0); maxColor = Math.max(r, maxColor); maxColor = Math.max(g, maxColor); maxColor = Math.max(b, maxColor); const pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4; if (tempData) { tempData[pixelStorageIndex + 0] = r; tempData[pixelStorageIndex + 1] = g; tempData[pixelStorageIndex + 2] = b; } pixelIndexH++; if (pixelIndexH % size == 0) { pixelIndexSlice++; pixelIndexH = 0; if (pixelIndexSlice % size == 0) { pixelIndexW++; pixelIndexSlice = 0; } } } } if (tempData && data) { for (let i = 0; i < tempData.length; i++) { if (i > 0 && (i + 1) % 4 === 0) { data[i] = 255; } else { const value = tempData[i]; data[i] = value / maxColor * 255; } } } if (texture.is3D) { texture.updateSize(size, size, size); engine.updateRawTexture3D(texture, data, 5, false); } else { texture.updateSize(size * size, size); engine.updateRawTexture(texture, data, 5, false); } texture.isReady = true; this._triggerOnLoad(); }, "callback"); const scene = this.getScene(); if (scene) { scene._loadFile(this.url, callback); } else { engine._loadFile(this.url, callback); } return this._texture; } /** * Starts the loading process of the texture. */ _loadTexture() { if (this.url) { const url = this.url.toLocaleLowerCase(); if (url.endsWith(".3dl") || url.startsWith("blob:")) { this._load3dlTexture(); } } } /** * Clones the color grading texture. * @returns the cloned texture */ clone() { const newTexture = new _ColorGradingTexture(this.url, this.getScene() || this._getEngine()); newTexture.level = this.level; return newTexture; } /** * Called during delayed load for textures. */ delayLoad() { if (this.delayLoadState !== 4) { return; } this.delayLoadState = 1; this._texture = this._getFromCache(this.url, true); if (!this._texture) { this._loadTexture(); } } /** * Parses a color grading texture serialized by Babylon. * @param parsedTexture The texture information being parsedTexture * @param scene The scene to load the texture in * @returns A color grading texture */ static Parse(parsedTexture, scene) { let texture = null; if (parsedTexture.name && !parsedTexture.isRenderTarget) { texture = new _ColorGradingTexture(parsedTexture.name, scene); texture.name = parsedTexture.name; texture.level = parsedTexture.level; } return texture; } /** * Serializes the LUT texture to json format. * @returns The JSON representation of the texture */ serialize() { if (!this.name) { return null; } const serializationObject = {}; serializationObject.name = this.name; serializationObject.level = this.level; serializationObject.customType = "BABYLON.ColorGradingTexture"; return serializationObject; } }; ColorGradingTexture._NoneEmptyLineRegex = /\S+/; RegisterClass("BABYLON.ColorGradingTexture", ColorGradingTexture); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Layers/thinEffectLayer.js init_observable(); init_math_color(); init_engineStore(); init_buffer(); init_effectRenderer(); init_effectFallbacks(); init_drawWrapper(); init_clipPlaneMaterialHelper(); init_materialHelper_functions(); init_objectRenderer(); init_engine(); var ThinGlowBlurPostProcess = class _ThinGlowBlurPostProcess extends EffectWrapper { static { __name(this, "ThinGlowBlurPostProcess"); } constructor(name260, engine = null, direction, kernel, options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinGlowBlurPostProcess.FragmentUrl, uniforms: _ThinGlowBlurPostProcess.Uniforms }); this.direction = direction; this.kernel = kernel; this.textureWidth = 0; this.textureHeight = 0; } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_glowBlurPostProcess_fragment(), glowBlurPostProcess_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_glowBlurPostProcess_fragment2(), glowBlurPostProcess_fragment_exports2))); } super._gatherImports(useWebGPU, list); } bind() { super.bind(); this._drawWrapper.effect.setFloat2("screenSize", this.textureWidth, this.textureHeight); this._drawWrapper.effect.setVector2("direction", this.direction); this._drawWrapper.effect.setFloat("blurWidth", this.kernel); } }; ThinGlowBlurPostProcess.FragmentUrl = "glowBlurPostProcess"; ThinGlowBlurPostProcess.Uniforms = ["screenSize", "direction", "blurWidth"]; var ThinEffectLayer = class _ThinEffectLayer { static { __name(this, "ThinEffectLayer"); } /** * Gets/sets the camera attached to the layer. */ get camera() { return this._options.camera; } set camera(camera) { this._options.camera = camera; } /** * Gets the rendering group id the layer should render in. */ get renderingGroupId() { return this._options.renderingGroupId; } set renderingGroupId(renderingGroupId) { this._options.renderingGroupId = renderingGroupId; } /** * Gets the object renderer used to render objects in the layer */ get objectRenderer() { return this._objectRenderer; } /** * Gets the shader language used in this material. */ get shaderLanguage() { return this._shaderLanguage; } /** * Sets a specific material to be used to render a mesh/a list of meshes in the layer * @param mesh mesh or array of meshes * @param material material to use by the layer when rendering the mesh(es). If undefined is passed, the specific material created by the layer will be used. */ setMaterialForRendering(mesh, material) { this._objectRenderer.setMaterialForRendering(mesh, material); if (Array.isArray(mesh)) { for (let i = 0; i < mesh.length; ++i) { const currentMesh = mesh[i]; if (!material) { delete this._materialForRendering[currentMesh.uniqueId]; } else { this._materialForRendering[currentMesh.uniqueId] = [currentMesh, material]; } } } else { if (!material) { delete this._materialForRendering[mesh.uniqueId]; } else { this._materialForRendering[mesh.uniqueId] = [mesh, material]; } } } /** * Gets the intensity of the effect for a specific mesh. * @param mesh The mesh to get the effect intensity for * @returns The intensity of the effect for the mesh */ getEffectIntensity(mesh) { return this._effectIntensity[mesh.uniqueId] ?? 1; } /** * Sets the intensity of the effect for a specific mesh. * @param mesh The mesh to set the effect intensity for * @param intensity The intensity of the effect for the mesh */ setEffectIntensity(mesh, intensity) { this._effectIntensity[mesh.uniqueId] = intensity; } /** * Instantiates a new effect Layer * @param name The name of the layer * @param scene The scene to use the layer in * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false * @param dontCheckIfReady Specifies if the layer should disable checking whether all the post processes are ready (default: false). To save performance, this should be set to true and you should call `isReady` manually before rendering to the layer. * @param _additionalImportShadersAsync Additional shaders to import when the layer is created */ constructor(name260, scene, forceGLSL = false, dontCheckIfReady = false, _additionalImportShadersAsync) { this._additionalImportShadersAsync = _additionalImportShadersAsync; this._vertexBuffers = {}; this._dontCheckIfReady = false; this._shouldRender = true; this._emissiveTextureAndColor = { texture: null, color: new Color4() }; this._effectIntensity = {}; this._postProcesses = []; this.neutralColor = new Color4(); this.isEnabled = true; this.disableBoundingBoxesFromEffectLayer = false; this.onDisposeObservable = new Observable(); this.onBeforeRenderLayerObservable = new Observable(); this.onBeforeComposeObservable = new Observable(); this.onBeforeRenderMeshToEffect = new Observable(); this.onAfterRenderMeshToEffect = new Observable(); this.onAfterComposeObservable = new Observable(); this.onBeforeBlurObservable = new Observable(); this.onAfterBlurObservable = new Observable(); this._shaderLanguage = 0; this._materialForRendering = {}; this._shadersLoaded = false; this.name = name260; this._scene = scene || EngineStore.LastCreatedScene; this._dontCheckIfReady = dontCheckIfReady; const engine = this._scene.getEngine(); if (engine.isWebGPU && !forceGLSL && !_ThinEffectLayer.ForceGLSL) { this._shaderLanguage = 1; } this._engine = this._scene.getEngine(); this._mergeDrawWrapper = []; this._generateIndexBuffer(); this._generateVertexBuffer(); } /** * Get the effect name of the layer. * @returns The effect name */ getEffectName() { return ""; } /** * 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 * @returns true if ready otherwise, false */ isReady(_subMesh, _useInstances) { return true; } /** * Returns whether or not the layer needs stencil enabled during the mesh rendering. * @returns true if the effect requires stencil during the main canvas render pass. */ needStencil() { return false; } /** @internal */ _createMergeEffect() { throw new Error("Effect Layer: no merge effect defined"); } /** @internal */ _createTextureAndPostProcesses() { } /** @internal */ _internalCompose(_effect, _renderIndex) { } /** @internal */ _setEmissiveTextureAndColor(_mesh, _subMesh, _material) { } /** @internal */ _numInternalDraws() { return 1; } /** @internal */ _init(options) { this._options = { mainTextureRatio: 0.5, mainTextureFixedSize: 0, mainTextureType: 0, alphaBlendingMode: 2, camera: null, renderingGroupId: -1, ...options }; this._createObjectRenderer(); } _generateIndexBuffer() { const 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); } _generateVertexBuffer() { const vertices = []; vertices.push(1, 1); vertices.push(-1, 1); vertices.push(-1, -1); vertices.push(1, -1); const vertexBuffer = new VertexBuffer(this._engine, vertices, VertexBuffer.PositionKind, false, false, 2); this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer; } _createObjectRenderer() { this._objectRenderer = new ObjectRenderer(`ObjectRenderer for thin effect layer ${this.name}`, this._scene, { doNotChangeAspectRatio: true }); this._objectRenderer.activeCamera = this._options.camera; this._objectRenderer.renderParticles = false; this._objectRenderer.renderList = null; const hasBoundingBoxRenderer = !!this._scene.getBoundingBoxRenderer; let boundingBoxRendererEnabled = false; if (hasBoundingBoxRenderer) { this._objectRenderer.onBeforeRenderObservable.add(() => { boundingBoxRendererEnabled = this._scene.getBoundingBoxRenderer().enabled; this._scene.getBoundingBoxRenderer().enabled = !this.disableBoundingBoxesFromEffectLayer && boundingBoxRendererEnabled; }); this._objectRenderer.onAfterRenderObservable.add(() => { this._scene.getBoundingBoxRenderer().enabled = boundingBoxRendererEnabled; }); } this._objectRenderer.customIsReadyFunction = (mesh, refreshRate, preWarm) => { if ((preWarm || refreshRate === 0) && mesh.subMeshes) { for (let i = 0; i < mesh.subMeshes.length; ++i) { const subMesh = mesh.subMeshes[i]; const material = subMesh.getMaterial(); const renderingMesh = subMesh.getRenderingMesh(); if (!material) { continue; } const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh()); const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances; this._setEmissiveTextureAndColor(renderingMesh, subMesh, material); if (!this._isSubMeshReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) { return false; } } } return true; }; this._objectRenderer.customRenderFunction = (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) => { this.onBeforeRenderLayerObservable.notifyObservers(this); let index; const 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]); } const previousAlphaMode = engine.getAlphaMode(); for (index = 0; index < transparentSubMeshes.length; index++) { const subMesh = transparentSubMeshes.data[index]; const material = subMesh.getMaterial(); if (material && material.needDepthPrePass) { const engine2 = material.getScene().getEngine(); engine2.setColorWrite(false); this._renderSubMesh(subMesh); engine2.setColorWrite(true); } this._renderSubMesh(subMesh, true); } engine.setAlphaMode(previousAlphaMode); }; } /** @internal */ _addCustomEffectDefines(_defines) { } /** @internal */ _internalIsSubMeshReady(subMesh, useInstances, emissiveTexture) { const engine = this._scene.getEngine(); const mesh = subMesh.getMesh(); const renderingMaterial = mesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine.currentRenderPassId]; if (renderingMaterial) { return renderingMaterial.isReadyForSubMesh(mesh, subMesh, useInstances); } const material = subMesh.getMaterial(); if (!material) { return false; } if (this._useMeshMaterial(subMesh.getRenderingMesh())) { return material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances); } const defines = []; const attribs = [VertexBuffer.PositionKind]; let uv1 = false; let uv2 = false; const color = false; if (material) { const needAlphaTest = material.needAlphaTestingForMesh(mesh); const diffuseTexture = material.getAlphaTestTexture(); const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture); if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) { defines.push("#define DIFFUSE"); if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && diffuseTexture.coordinatesIndex === 1) { defines.push("#define DIFFUSEUV2"); uv2 = true; } else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { defines.push("#define DIFFUSEUV1"); uv1 = true; } if (needAlphaTest) { defines.push("#define ALPHATEST"); defines.push("#define ALPHATESTVALUE 0.4"); } if (!diffuseTexture.gammaSpace) { defines.push("#define DIFFUSE_ISLINEAR"); } } const opacityTexture = material.opacityTexture; if (opacityTexture) { defines.push("#define OPACITY"); if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && opacityTexture.coordinatesIndex === 1) { defines.push("#define OPACITYUV2"); uv2 = true; } else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { defines.push("#define OPACITYUV1"); uv1 = true; } } } if (emissiveTexture) { defines.push("#define EMISSIVE"); if (mesh.isVerticesDataPresent(VertexBuffer.UV2Kind) && emissiveTexture.coordinatesIndex === 1) { defines.push("#define EMISSIVEUV2"); uv2 = true; } else if (mesh.isVerticesDataPresent(VertexBuffer.UVKind)) { defines.push("#define EMISSIVEUV1"); uv1 = true; } if (!emissiveTexture.gammaSpace) { defines.push("#define EMISSIVE_ISLINEAR"); } } if (mesh.useVertexColors && mesh.isVerticesDataPresent(VertexBuffer.ColorKind) && mesh.hasVertexAlpha && material.transparencyMode !== Material.MATERIAL_OPAQUE) { attribs.push(VertexBuffer.ColorKind); defines.push("#define VERTEXALPHA"); } if (uv1) { attribs.push(VertexBuffer.UVKind); defines.push("#define UV1"); } if (uv2) { attribs.push(VertexBuffer.UV2Kind); defines.push("#define UV2"); } const fallbacks = new EffectFallbacks(); if (mesh.useBones && mesh.computeBonesUsingShaders) { attribs.push(VertexBuffer.MatricesIndicesKind); attribs.push(VertexBuffer.MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(VertexBuffer.MatricesIndicesExtraKind); attribs.push(VertexBuffer.MatricesWeightsExtraKind); } defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); const 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"); } const numMorphInfluencers = mesh.morphTargetManager ? PrepareDefinesAndAttributesForMorphTargets( mesh.morphTargetManager, defines, attribs, mesh, true, // usePositionMorph false, // useNormalMorph false, // useTangentMorph uv1, // useUVMorph uv2, // useUV2Morph color // useColorMorph ) : 0; if (useInstances) { defines.push("#define INSTANCES"); PushAttributesForInstances(attribs); if (subMesh.getRenderingMesh().hasThinInstances) { defines.push("#define THIN_INSTANCES"); } } PrepareStringDefinesForClipPlanes(material, this._scene, defines); this._addCustomEffectDefines(defines); const drawWrapper = subMesh._getDrawWrapper(void 0, true); const cachedDefines = drawWrapper.defines; const join = defines.join("\n"); if (cachedDefines !== join) { const uniforms = [ "world", "mBones", "viewProjection", "glowColor", "morphTargetInfluences", "morphTargetCount", "boneTextureWidth", "diffuseMatrix", "emissiveMatrix", "opacityMatrix", "opacityIntensity", "morphTargetTextureInfo", "morphTargetTextureIndices", "glowIntensity" ]; AddClipPlaneUniforms(uniforms); drawWrapper.setEffect(this._engine.createEffect("glowMapGeneration", attribs, uniforms, ["diffuseSampler", "emissiveSampler", "opacitySampler", "boneSampler", "morphTargets"], join, fallbacks, void 0, void 0, { maxSimultaneousMorphTargets: numMorphInfluencers }, this._shaderLanguage, this._shadersLoaded ? void 0 : async () => { await this._importShadersAsync(); this._shadersLoaded = true; }), join); } const effectIsReady = drawWrapper.effect.isReady(); return effectIsReady && (this._dontCheckIfReady || !this._dontCheckIfReady && this.isLayerReady()); } /** @internal */ _isSubMeshReady(subMesh, useInstances, emissiveTexture) { return this._internalIsSubMeshReady(subMesh, useInstances, emissiveTexture); } async _importShadersAsync() { if (this._shaderLanguage === 1) { await Promise.all([Promise.resolve().then(() => (init_glowMapGeneration_vertex(), glowMapGeneration_vertex_exports)), Promise.resolve().then(() => (init_glowMapGeneration_fragment(), glowMapGeneration_fragment_exports))]); } else { await Promise.all([Promise.resolve().then(() => (init_glowMapGeneration_vertex2(), glowMapGeneration_vertex_exports2)), Promise.resolve().then(() => (init_glowMapGeneration_fragment2(), glowMapGeneration_fragment_exports2))]); } this._additionalImportShadersAsync?.(); } /** @internal */ _internalIsLayerReady() { let isReady = true; for (let i = 0; i < this._postProcesses.length; i++) { isReady = this._postProcesses[i].isReady() && isReady; } const numDraws = this._numInternalDraws(); for (let i = 0; i < numDraws; ++i) { let currentEffect = this._mergeDrawWrapper[i]; if (!currentEffect) { currentEffect = this._mergeDrawWrapper[i] = new DrawWrapper(this._engine); currentEffect.setEffect(this._createMergeEffect()); } isReady = currentEffect.effect.isReady() && isReady; } return isReady; } /** * Checks if the layer is ready to be used. * @returns true if the layer is ready to be used */ isLayerReady() { return this._internalIsLayerReady(); } /** * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene. * @returns true if the rendering was successful */ compose() { if (!this._dontCheckIfReady && !this.isLayerReady()) { return false; } const engine = this._scene.getEngine(); const numDraws = this._numInternalDraws(); this.onBeforeComposeObservable.notifyObservers(this); const previousAlphaMode = engine.getAlphaMode(); for (let i = 0; i < numDraws; ++i) { const currentEffect = this._mergeDrawWrapper[i]; engine.enableEffect(currentEffect); engine.setState(false); engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect.effect); engine.setAlphaMode(this._options.alphaBlendingMode); this._internalCompose(currentEffect.effect, i); } engine.setAlphaMode(previousAlphaMode); this.onAfterComposeObservable.notifyObservers(this); return true; } /** @internal */ _internalHasMesh(mesh) { if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) { return true; } return false; } /** * 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 */ hasMesh(mesh) { return this._internalHasMesh(mesh); } /** @internal */ _internalShouldRender() { return this.isEnabled && this._shouldRender; } /** * Returns true if the layer contains information to display, otherwise false. * @returns true if the glow layer should be rendered */ shouldRender() { return this._internalShouldRender(); } /** @internal */ _shouldRenderMesh(_mesh) { return true; } /** @internal */ _internalCanRenderMesh(mesh, material) { return !material.needAlphaBlendingForMesh(mesh); } /** @internal */ _canRenderMesh(mesh, material) { return this._internalCanRenderMesh(mesh, material); } _renderSubMesh(subMesh, enableAlphaMode = false) { if (!this._internalShouldRender()) { return; } const material = subMesh.getMaterial(); const ownerMesh = subMesh.getMesh(); const replacementMesh = subMesh.getReplacementMesh(); const renderingMesh = subMesh.getRenderingMesh(); const effectiveMesh = subMesh.getEffectiveMesh(); const scene = this._scene; const engine = scene.getEngine(); effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false; if (!material) { return; } if (!this._canRenderMesh(renderingMesh, material)) { return; } let sideOrientation = material._getEffectiveOrientation(renderingMesh); const mainDeterminant = effectiveMesh._getWorldMatrixDeterminant(); if (mainDeterminant < 0) { sideOrientation = sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation; } const reverse = sideOrientation === Material.ClockWiseSideOrientation; engine.setState(material.backFaceCulling, material.zOffset, void 0, reverse, material.cullBackFaces, void 0, material.zOffsetUnits); const batch = renderingMesh._getInstancesRenderList(subMesh._id, !!replacementMesh); if (batch.mustReturn) { return; } if (!this._shouldRenderMesh(renderingMesh)) { return; } const hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances; this._setEmissiveTextureAndColor(renderingMesh, subMesh, material); this.onBeforeRenderMeshToEffect.notifyObservers(ownerMesh); if (this._useMeshMaterial(renderingMesh)) { subMesh.getMaterial()._glowModeEnabled = true; renderingMesh.render(subMesh, enableAlphaMode, replacementMesh || void 0); subMesh.getMaterial()._glowModeEnabled = false; } else if (this._isSubMeshReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) { const renderingMaterial = effectiveMesh._internalAbstractMeshDataInfo._materialForRenderPass?.[engine.currentRenderPassId]; let drawWrapper = subMesh._getDrawWrapper(); if (!drawWrapper && renderingMaterial) { drawWrapper = renderingMaterial._getDrawWrapper(); } if (!drawWrapper) { return; } const effect = drawWrapper.effect; engine.enableEffect(drawWrapper); if (!hardwareInstancedRendering) { renderingMesh._bind(subMesh, effect, material.fillMode); } if (!renderingMaterial) { effect.setMatrix("viewProjection", scene.getTransformMatrix()); effect.setMatrix("world", effectiveMesh.getWorldMatrix()); effect.setFloat4("glowColor", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a); } else { renderingMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), effectiveMesh, subMesh); } if (!renderingMaterial) { const needAlphaTest = material.needAlphaTestingForMesh(effectiveMesh); const diffuseTexture = material.getAlphaTestTexture(); const needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha && (material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture); if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) { effect.setTexture("diffuseSampler", diffuseTexture); const textureMatrix = diffuseTexture.getTextureMatrix(); if (textureMatrix) { effect.setMatrix("diffuseMatrix", textureMatrix); } } const opacityTexture = material.opacityTexture; if (opacityTexture) { effect.setTexture("opacitySampler", opacityTexture); effect.setFloat("opacityIntensity", opacityTexture.level); const textureMatrix = opacityTexture.getTextureMatrix(); if (textureMatrix) { effect.setMatrix("opacityMatrix", textureMatrix); } } if (this._emissiveTextureAndColor.texture) { effect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture); effect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix()); } if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) { const skeleton = renderingMesh.skeleton; if (skeleton.isUsingTextureForMatrices) { const boneTexture = skeleton.getTransformMatrixTexture(renderingMesh); if (!boneTexture) { return; } effect.setTexture("boneSampler", boneTexture); effect.setFloat("boneTextureWidth", 4 * (skeleton.bones.length + 1)); } else { effect.setMatrices("mBones", skeleton.getTransformMatrices(renderingMesh)); } } BindMorphTargetParameters(renderingMesh, effect); if (renderingMesh.morphTargetManager && renderingMesh.morphTargetManager.isUsingTextureForTargets) { renderingMesh.morphTargetManager._bind(effect); } if (enableAlphaMode) { engine.setAlphaMode(material.alphaMode); } effect.setFloat("glowIntensity", this.getEffectIntensity(renderingMesh)); BindClipPlane(effect, material, scene); } renderingMesh._processRendering(effectiveMesh, subMesh, effect, material.fillMode, batch, hardwareInstancedRendering, (isInstance, world) => effect.setMatrix("world", world)); } else { this._objectRenderer.resetRefreshCounter(); } this.onAfterRenderMeshToEffect.notifyObservers(ownerMesh); } /** @internal */ _useMeshMaterial(_mesh) { return false; } /** @internal */ _rebuild() { const vb = this._vertexBuffers[VertexBuffer.PositionKind]; if (vb) { vb._rebuild(); } this._generateIndexBuffer(); } /** * Dispose the effect layer and free resources. */ dispose() { const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind]; if (vertexBuffer) { vertexBuffer.dispose(); this._vertexBuffers[VertexBuffer.PositionKind] = null; } if (this._indexBuffer) { this._scene.getEngine()._releaseBuffer(this._indexBuffer); this._indexBuffer = null; } for (const drawWrapper of this._mergeDrawWrapper) { drawWrapper.dispose(); } this._mergeDrawWrapper = []; this._objectRenderer.dispose(); this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); this.onBeforeRenderLayerObservable.clear(); this.onBeforeComposeObservable.clear(); this.onBeforeRenderMeshToEffect.clear(); this.onAfterRenderMeshToEffect.clear(); this.onAfterComposeObservable.clear(); } }; ThinEffectLayer.ForceGLSL = false; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Layers/effectLayer.js init_tslib_es6(); init_decorators(); init_tools(); init_observable(); init_engineStore(); init_texture(); init_renderTargetTexture(); init_devTools(); init_tools_functions(); init_uniqueIdGenerator(); var EffectLayer = class _EffectLayer { static { __name(this, "EffectLayer"); } get _shouldRender() { return this._thinEffectLayer._shouldRender; } set _shouldRender(value) { this._thinEffectLayer._shouldRender = value; } get _emissiveTextureAndColor() { return this._thinEffectLayer._emissiveTextureAndColor; } set _emissiveTextureAndColor(value) { this._thinEffectLayer._emissiveTextureAndColor = value; } get _effectIntensity() { return this._thinEffectLayer._effectIntensity; } set _effectIntensity(value) { this._thinEffectLayer._effectIntensity = value; } /** * Force all the effect layers to compile to glsl even on WebGPU engines. * False by default. This is mostly meant for backward compatibility. */ static get ForceGLSL() { return ThinEffectLayer.ForceGLSL; } static set ForceGLSL(value) { ThinEffectLayer.ForceGLSL = value; } /** * The name of the layer */ get name() { return this._thinEffectLayer.name; } set name(value) { this._thinEffectLayer.name = value; } /** * The clear color of the texture used to generate the glow map. */ get neutralColor() { return this._thinEffectLayer.neutralColor; } set neutralColor(value) { this._thinEffectLayer.neutralColor = value; } /** * Specifies whether the highlight layer is enabled or not. */ get isEnabled() { return this._thinEffectLayer.isEnabled; } set isEnabled(value) { this._thinEffectLayer.isEnabled = value; } /** * Gets the camera attached to the layer. */ get camera() { return this._thinEffectLayer.camera; } /** * Gets the rendering group id the layer should render in. */ get renderingGroupId() { return this._thinEffectLayer.renderingGroupId; } set renderingGroupId(renderingGroupId) { this._thinEffectLayer.renderingGroupId = renderingGroupId; } /** * Specifies if the bounding boxes should be rendered normally or if they should undergo the effect of the layer */ get disableBoundingBoxesFromEffectLayer() { return this._thinEffectLayer.disableBoundingBoxesFromEffectLayer; } set disableBoundingBoxesFromEffectLayer(value) { this._thinEffectLayer.disableBoundingBoxesFromEffectLayer = value; } /** * Gets the main texture where the effect is rendered */ get mainTexture() { return this._mainTexture; } get _shaderLanguage() { return this._thinEffectLayer.shaderLanguage; } /** * Gets the shader language used in this material. */ get shaderLanguage() { return this._thinEffectLayer.shaderLanguage; } /** * Sets a specific material to be used to render a mesh/a list of meshes in the layer * @param mesh mesh or array of meshes * @param material material to use by the layer when rendering the mesh(es). If undefined is passed, the specific material created by the layer will be used. */ setMaterialForRendering(mesh, material) { this._thinEffectLayer.setMaterialForRendering(mesh, material); } /** * Gets the intensity of the effect for a specific mesh. * @param mesh The mesh to get the effect intensity for * @returns The intensity of the effect for the mesh */ getEffectIntensity(mesh) { return this._thinEffectLayer.getEffectIntensity(mesh); } /** * Sets the intensity of the effect for a specific mesh. * @param mesh The mesh to set the effect intensity for * @param intensity The intensity of the effect for the mesh */ setEffectIntensity(mesh, intensity) { this._thinEffectLayer.setEffectIntensity(mesh, intensity); } /** * 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 * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false * @param thinEffectLayer The thin instance of the effect layer (optional) */ constructor(name260, scene, forceGLSL = false, thinEffectLayer) { this._mainTextureCreatedSize = { width: 0, height: 0 }; this._maxSize = 0; this._mainTextureDesiredSize = { width: 0, height: 0 }; this._postProcesses = []; this._textures = []; this.uniqueId = UniqueIdGenerator.UniqueId; this.onDisposeObservable = new Observable(); this.onBeforeRenderMainTextureObservable = new Observable(); this.onBeforeComposeObservable = new Observable(); this.onBeforeRenderMeshToEffect = new Observable(); this.onAfterRenderMeshToEffect = new Observable(); this.onAfterComposeObservable = new Observable(); this.onSizeChangedObservable = new Observable(); this._internalThinEffectLayer = !thinEffectLayer; if (!thinEffectLayer) { thinEffectLayer = new ThinEffectLayer(name260, scene, forceGLSL, false, this._importShadersAsync.bind(this)); thinEffectLayer.getEffectName = this.getEffectName.bind(this); thinEffectLayer.isReady = this.isReady.bind(this); thinEffectLayer._createMergeEffect = this._createMergeEffect.bind(this); thinEffectLayer._createTextureAndPostProcesses = this._createTextureAndPostProcesses.bind(this); thinEffectLayer._internalCompose = this._internalRender.bind(this); thinEffectLayer._setEmissiveTextureAndColor = this._setEmissiveTextureAndColor.bind(this); thinEffectLayer._numInternalDraws = this._numInternalDraws.bind(this); thinEffectLayer._addCustomEffectDefines = this._addCustomEffectDefines.bind(this); thinEffectLayer.hasMesh = this.hasMesh.bind(this); thinEffectLayer.shouldRender = this.shouldRender.bind(this); thinEffectLayer._shouldRenderMesh = this._shouldRenderMesh.bind(this); thinEffectLayer._canRenderMesh = this._canRenderMesh.bind(this); thinEffectLayer._useMeshMaterial = this._useMeshMaterial.bind(this); } this._thinEffectLayer = thinEffectLayer; this.name = name260; this._scene = scene || EngineStore.LastCreatedScene; _EffectLayer._SceneComponentInitialization(this._scene); this._engine = this._scene.getEngine(); this._maxSize = this._engine.getCaps().maxTextureSize; this._scene.addEffectLayer(this); this._thinEffectLayer.onDisposeObservable.add(() => { this.onDisposeObservable.notifyObservers(this); }); this._thinEffectLayer.onBeforeRenderLayerObservable.add(() => { this.onBeforeRenderMainTextureObservable.notifyObservers(this); }); this._thinEffectLayer.onBeforeComposeObservable.add(() => { this.onBeforeComposeObservable.notifyObservers(this); }); this._thinEffectLayer.onBeforeRenderMeshToEffect.add((mesh) => { this.onBeforeRenderMeshToEffect.notifyObservers(mesh); }); this._thinEffectLayer.onAfterRenderMeshToEffect.add((mesh) => { this.onAfterRenderMeshToEffect.notifyObservers(mesh); }); this._thinEffectLayer.onAfterComposeObservable.add(() => { this.onAfterComposeObservable.notifyObservers(this); }); } get _shadersLoaded() { return this._thinEffectLayer._shadersLoaded; } set _shadersLoaded(value) { this._thinEffectLayer._shadersLoaded = value; } /** * Number of times _internalRender will be called. Some effect layers need to render the mesh several times, so they should override this method with the number of times the mesh should be rendered * @returns Number of times a mesh must be rendered in the layer */ _numInternalDraws() { return this._internalThinEffectLayer ? 1 : this._thinEffectLayer._numInternalDraws(); } /** * 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) */ _init(options) { this._effectLayerOptions = { mainTextureRatio: 0.5, alphaBlendingMode: 2, camera: null, renderingGroupId: -1, mainTextureType: 0, generateStencilBuffer: false, ...options }; this._setMainTextureSize(); this._thinEffectLayer._init(options); this._createMainTexture(); this._createTextureAndPostProcesses(); } /** * Sets the main texture desired size which is the closest power of two * of the engine canvas size. */ _setMainTextureSize() { 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 ? GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width; this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? 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. */ _createMainTexture() { this._mainTexture = new RenderTargetTexture("EffectLayerMainRTT", { width: this._mainTextureDesiredSize.width, height: this._mainTextureDesiredSize.height }, this._scene, { type: this._effectLayerOptions.mainTextureType, samplingMode: Texture.TRILINEAR_SAMPLINGMODE, generateStencilBuffer: this._effectLayerOptions.generateStencilBuffer, existingObjectRenderer: this._thinEffectLayer.objectRenderer }); this._mainTexture.activeCamera = this._effectLayerOptions.camera; this._mainTexture.wrapU = Texture.CLAMP_ADDRESSMODE; this._mainTexture.wrapV = Texture.CLAMP_ADDRESSMODE; this._mainTexture.anisotropicFilteringLevel = 1; this._mainTexture.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE); this._mainTexture.renderParticles = false; this._mainTexture.renderList = null; this._mainTexture.ignoreCameraViewport = true; this._mainTexture.onClearObservable.add((engine) => { engine.clear(this.neutralColor, true, true, true); }); } /** * Adds specific effects defines. * @param defines The defines to add specifics to. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars _addCustomEffectDefines(defines) { } /** * 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 * @returns true if ready otherwise, false */ _isReady(subMesh, useInstances, emissiveTexture) { return this._internalThinEffectLayer ? this._thinEffectLayer._internalIsSubMeshReady(subMesh, useInstances, emissiveTexture) : this._thinEffectLayer._isSubMeshReady(subMesh, useInstances, emissiveTexture); } async _importShadersAsync() { } _arePostProcessAndMergeReady() { return this._internalThinEffectLayer ? this._thinEffectLayer._internalIsLayerReady() : this._thinEffectLayer.isLayerReady(); } /** * Checks if the layer is ready to be used. * @returns true if the layer is ready to be used */ isLayerReady() { return this._arePostProcessAndMergeReady() && this._mainTexture.isReady(); } /** * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene. */ render() { if (!this._thinEffectLayer.compose()) { return; } this._setMainTextureSize(); if ((this._mainTextureCreatedSize.width !== this._mainTextureDesiredSize.width || this._mainTextureCreatedSize.height !== this._mainTextureDesiredSize.height) && this._mainTextureDesiredSize.width !== 0 && this._mainTextureDesiredSize.height !== 0) { this.onSizeChangedObservable.notifyObservers(this); this._disposeTextureAndPostProcesses(); this._createMainTexture(); this._createTextureAndPostProcesses(); this._mainTextureCreatedSize.width = this._mainTextureDesiredSize.width; this._mainTextureCreatedSize.height = this._mainTextureDesiredSize.height; } } /** * 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 */ hasMesh(mesh) { return this._internalThinEffectLayer ? this._thinEffectLayer._internalHasMesh(mesh) : this._thinEffectLayer.hasMesh(mesh); } /** * Returns true if the layer contains information to display, otherwise false. * @returns true if the glow layer should be rendered */ shouldRender() { return this._internalThinEffectLayer ? this._thinEffectLayer._internalShouldRender() : this._thinEffectLayer.shouldRender(); } /** * Returns true if the mesh should render, otherwise false. * @param mesh The mesh to render * @returns true if it should render otherwise false */ // eslint-disable-next-line @typescript-eslint/no-unused-vars _shouldRenderMesh(mesh) { return this._internalThinEffectLayer ? true : this._thinEffectLayer._shouldRenderMesh(mesh); } /** * 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 */ _canRenderMesh(mesh, material) { return this._internalThinEffectLayer ? this._thinEffectLayer._internalCanRenderMesh(mesh, material) : this._thinEffectLayer._canRenderMesh(mesh, material); } /** * Returns true if the mesh should render, otherwise false. * @returns true if it should render otherwise false */ _shouldRenderEmissiveTextureForMesh() { 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 * @returns true if the mesh material should be use */ // eslint-disable-next-line @typescript-eslint/no-unused-vars _useMeshMaterial(mesh) { return this._internalThinEffectLayer ? false : this._thinEffectLayer._useMeshMaterial(mesh); } /** * Rebuild the required buffers. * @internal Internal use only. */ _rebuild() { this._thinEffectLayer._rebuild(); } /** * Dispose only the render target textures and post process. */ _disposeTextureAndPostProcesses() { this._mainTexture.dispose(); for (let i = 0; i < this._postProcesses.length; i++) { if (this._postProcesses[i]) { this._postProcesses[i].dispose(); } } this._postProcesses = []; for (let i = 0; i < this._textures.length; i++) { if (this._textures[i]) { this._textures[i].dispose(); } } this._textures = []; } /** * Dispose the highlight layer and free resources. */ dispose() { this._thinEffectLayer.dispose(); this._disposeTextureAndPostProcesses(); this._scene.removeEffectLayer(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 */ getClassName() { 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 */ static Parse(parsedEffectLayer, scene, rootUrl) { const effectLayerType = Tools.Instantiate(parsedEffectLayer.customType); return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl); } }; EffectLayer._SceneComponentInitialization = (_) => { throw _WarnImport("EffectLayerSceneComponent"); }; __decorate([ serialize() ], EffectLayer.prototype, "name", null); __decorate([ serializeAsColor4() ], EffectLayer.prototype, "neutralColor", null); __decorate([ serialize() ], EffectLayer.prototype, "isEnabled", null); __decorate([ serializeAsCameraReference() ], EffectLayer.prototype, "camera", null); __decorate([ serialize() ], EffectLayer.prototype, "renderingGroupId", null); __decorate([ serialize() ], EffectLayer.prototype, "disableBoundingBoxesFromEffectLayer", null); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Loading/Plugins/babylonFileParser.function.js var BabylonFileParsers = {}; var IndividualBabylonFileParsers = {}; function AddParser(name260, parser) { BabylonFileParsers[name260] = parser; } __name(AddParser, "AddParser"); function GetParser(name260) { if (BabylonFileParsers[name260]) { return BabylonFileParsers[name260]; } return null; } __name(GetParser, "GetParser"); function AddIndividualParser(name260, parser) { IndividualBabylonFileParsers[name260] = parser; } __name(AddIndividualParser, "AddIndividualParser"); function GetIndividualParser(name260) { if (IndividualBabylonFileParsers[name260]) { return IndividualBabylonFileParsers[name260]; } return null; } __name(GetIndividualParser, "GetIndividualParser"); function Parse(jsonData, scene, container, rootUrl) { for (const parserName in BabylonFileParsers) { if (Object.prototype.hasOwnProperty.call(BabylonFileParsers, parserName)) { BabylonFileParsers[parserName](jsonData, scene, container, rootUrl); } } } __name(Parse, "Parse"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Layers/effectLayerSceneComponent.js init_camera(); init_sceneComponent(); init_engineStore(); AddParser(SceneComponentConstants.NAME_EFFECTLAYER, (parsedData, scene, container, rootUrl) => { if (parsedData.effectLayers) { if (!container.effectLayers) { container.effectLayers = []; } for (let index = 0; index < parsedData.effectLayers.length; index++) { const effectLayer = EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl); container.effectLayers.push(effectLayer); } } }); var EffectLayerSceneComponent = class { static { __name(this, "EffectLayerSceneComponent"); } /** * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ constructor(scene) { this.name = SceneComponentConstants.NAME_EFFECTLAYER; this._renderEffects = false; this._needStencil = false; this._previousStencilState = false; this.scene = scene || EngineStore.LastCreatedScene; if (!this.scene) { return; } this._engine = this.scene.getEngine(); } /** * Registers the component in a given scene */ register() { this.scene._isReadyForMeshStage.registerStep(SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh); this.scene._cameraDrawRenderTargetStage.registerStep(SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture); this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil); this.scene._afterRenderingGroupDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup); this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack); this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera); } /** * Rebuilds the elements related to this component in case of * context lost for instance. */ rebuild() { const layers = this.scene.effectLayers; for (const effectLayer of layers) { effectLayer._rebuild(); } } /** * Serializes the component data to the specified json object * @param serializationObject The object to serialize to */ serialize(serializationObject) { serializationObject.effectLayers = []; const layers = this.scene.effectLayers; for (const effectLayer of layers) { 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 */ addFromContainer(container) { if (!container.effectLayers) { return; } for (const o of container.effectLayers) { 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) */ removeFromContainer(container, dispose) { if (!container.effectLayers) { return; } for (const o of container.effectLayers) { this.scene.removeEffectLayer(o); if (dispose) { o.dispose(); } } } /** * Disposes the component and the associated resources. */ dispose() { const layers = this.scene.effectLayers; while (layers.length) { layers[0].dispose(); } } _isReadyForMesh(mesh, hardwareInstancedRendering) { const currentRenderPassId = this._engine.currentRenderPassId; const layers = this.scene.effectLayers; for (const layer of layers) { if (!layer.hasMesh(mesh)) { continue; } const renderTarget = layer._mainTexture; this._engine.currentRenderPassId = renderTarget.renderPassId; for (const subMesh of mesh.subMeshes) { if (!layer.isReady(subMesh, hardwareInstancedRendering)) { this._engine.currentRenderPassId = currentRenderPassId; return false; } } } this._engine.currentRenderPassId = currentRenderPassId; return true; } _renderMainTexture(camera) { this._renderEffects = false; this._needStencil = false; let needRebind = false; const layers = this.scene.effectLayers; if (layers && layers.length > 0) { this._previousStencilState = this._engine.getStencilBuffer(); for (const effectLayer of layers) { if (effectLayer.shouldRender() && (!effectLayer.camera || effectLayer.camera.cameraRigMode === Camera.RIG_MODE_NONE && camera === effectLayer.camera || effectLayer.camera.cameraRigMode !== Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1)) { this._renderEffects = true; this._needStencil = this._needStencil || effectLayer.needStencil(); const renderTarget = effectLayer._mainTexture; if (renderTarget._shouldRender()) { this.scene.incrementRenderId(); renderTarget.render(false, false); needRebind = true; } } } this.scene.incrementRenderId(); } return needRebind; } _setStencil() { if (this._needStencil) { this._engine.setStencilBuffer(true); } } _setStencilBack() { if (this._needStencil) { this._engine.setStencilBuffer(this._previousStencilState); } } _draw(renderingGroupId) { if (this._renderEffects) { this._engine.setDepthBuffer(false); const layers = this.scene.effectLayers; for (let i = 0; i < layers.length; i++) { const effectLayer = layers[i]; if (effectLayer.renderingGroupId === renderingGroupId) { if (effectLayer.shouldRender()) { effectLayer.render(); } } } this._engine.setDepthBuffer(true); } } _drawCamera() { if (this._renderEffects) { this._draw(-1); } } _drawRenderingGroup(index) { if (!this.scene._isInIntermediateRendering() && this._renderEffects) { this._draw(index); } } }; EffectLayer._SceneComponentInitialization = (scene) => { let component = scene._getComponent(SceneComponentConstants.NAME_EFFECTLAYER); if (!component) { component = new EffectLayerSceneComponent(scene); scene._addComponent(component); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Layers/thinGlowLayer.js init_math_vector(); init_buffer(); init_math_color(); init_thinBlurPostProcess(); var ThinGlowLayer = class _ThinGlowLayer extends ThinEffectLayer { static { __name(this, "ThinGlowLayer"); } /** * Gets the ldrMerge option. */ get ldrMerge() { return this._options.ldrMerge; } /** * Sets the kernel size of the blur. */ set blurKernelSize(value) { if (value === this._options.blurKernelSize) { return; } this._options.blurKernelSize = value; const effectiveKernel = this._getEffectiveBlurKernelSize(); this._horizontalBlurPostprocess1.kernel = effectiveKernel; this._verticalBlurPostprocess1.kernel = effectiveKernel; this._horizontalBlurPostprocess2.kernel = effectiveKernel; this._verticalBlurPostprocess2.kernel = effectiveKernel; } /** * Gets the kernel size of the blur. */ get blurKernelSize() { return this._options.blurKernelSize; } /** * Sets the glow intensity. */ set intensity(value) { this._intensity = value; } /** * Gets the glow intensity. */ get intensity() { return this._intensity; } /** * 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) * @param dontCheckIfReady Specifies if the layer should disable checking whether all the post processes are ready (default: false). To save performance, this should be set to true and you should call `isReady` manually before rendering to the layer. */ constructor(name260, scene, options, dontCheckIfReady = false) { super(name260, scene, false, dontCheckIfReady); this._intensity = 1; this._includedOnlyMeshes = []; this._excludedMeshes = []; this._meshesUsingTheirOwnMaterials = []; this._renderPassId = 0; this.neutralColor = new Color4(0, 0, 0, 1); this._options = { mainTextureRatio: 0.5, mainTextureFixedSize: 0, mainTextureType: 0, blurKernelSize: 32, camera: null, renderingGroupId: -1, ldrMerge: false, alphaBlendingMode: 1, ...options }; this._init(this._options); if (dontCheckIfReady) { this._createTextureAndPostProcesses(); } } /** * Gets the class name of the thin glow layer * @returns the string with the class name of the glow layer */ getClassName() { return "GlowLayer"; } async _importShadersAsync() { if (this._shaderLanguage === 1) { await Promise.all([ Promise.resolve().then(() => (init_glowMapMerge_fragment(), glowMapMerge_fragment_exports)), Promise.resolve().then(() => (init_glowMapMerge_vertex(), glowMapMerge_vertex_exports)), Promise.resolve().then(() => (init_glowBlurPostProcess_fragment(), glowBlurPostProcess_fragment_exports)) ]); } else { await Promise.all([Promise.resolve().then(() => (init_glowMapMerge_fragment2(), glowMapMerge_fragment_exports2)), Promise.resolve().then(() => (init_glowMapMerge_vertex2(), glowMapMerge_vertex_exports2)), Promise.resolve().then(() => (init_glowBlurPostProcess_fragment2(), glowBlurPostProcess_fragment_exports2))]); } await super._importShadersAsync(); } getEffectName() { return _ThinGlowLayer.EffectName; } _createMergeEffect() { let defines = "#define EMISSIVE \n"; if (this._options.ldrMerge) { defines += "#define LDR \n"; } return this._engine.createEffect("glowMapMerge", [VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], defines, void 0, void 0, void 0, void 0, this.shaderLanguage, this._shadersLoaded ? void 0 : async () => { await this._importShadersAsync(); this._shadersLoaded = true; }); } _createTextureAndPostProcesses() { const effectiveKernel = this._getEffectiveBlurKernelSize(); this._horizontalBlurPostprocess1 = new ThinBlurPostProcess("GlowLayerHBP1", this._scene.getEngine(), new Vector2(1, 0), effectiveKernel); this._verticalBlurPostprocess1 = new ThinBlurPostProcess("GlowLayerVBP1", this._scene.getEngine(), new Vector2(0, 1), effectiveKernel); this._horizontalBlurPostprocess2 = new ThinBlurPostProcess("GlowLayerHBP2", this._scene.getEngine(), new Vector2(1, 0), effectiveKernel); this._verticalBlurPostprocess2 = new ThinBlurPostProcess("GlowLayerVBP2", this._scene.getEngine(), new Vector2(0, 1), effectiveKernel); this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2]; } _getEffectiveBlurKernelSize() { return this._options.blurKernelSize / 2; } isReady(subMesh, useInstances) { const material = subMesh.getMaterial(); const mesh = subMesh.getRenderingMesh(); if (!material || !mesh) { return false; } const emissiveTexture = material.emissiveTexture; return super._isSubMeshReady(subMesh, useInstances, emissiveTexture); } _canRenderMesh(_mesh, _material) { return true; } _internalCompose(effect) { this.bindTexturesForCompose(effect); effect.setFloat("offset", this._intensity); const engine = this._engine; const previousStencilBuffer = engine.getStencilBuffer(); engine.setStencilBuffer(false); engine.drawElementsType(Material.TriangleFillMode, 0, 6); engine.setStencilBuffer(previousStencilBuffer); } _setEmissiveTextureAndColor(mesh, subMesh, material) { let textureLevel = 1; 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) { const emissiveIntensity = material.emissiveIntensity ?? 1; textureLevel *= emissiveIntensity; 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); } } } _shouldRenderMesh(mesh) { return this.hasMesh(mesh); } _addCustomEffectDefines(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 */ addExcludedMesh(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 */ removeExcludedMesh(mesh) { const 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 */ addIncludedOnlyMesh(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 */ removeIncludedOnlyMesh(mesh) { const index = this._includedOnlyMeshes.indexOf(mesh.uniqueId); if (index !== -1) { this._includedOnlyMeshes.splice(index, 1); } } hasMesh(mesh) { if (!super.hasMesh(mesh)) { return false; } if (this._includedOnlyMeshes.length) { return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1; } if (this._excludedMeshes.length) { return this._excludedMeshes.indexOf(mesh.uniqueId) === -1; } return true; } _useMeshMaterial(mesh) { if (mesh.material?._supportGlowLayer) { return true; } 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 */ referenceMeshToUseItsOwnMaterial(mesh) { mesh.resetDrawCache(this._renderPassId); this._meshesUsingTheirOwnMaterials.push(mesh.uniqueId); mesh.onDisposeObservable.add(() => { this._disposeMesh(mesh); }); } /** * 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 * @param renderPassId The render pass id used when rendering the mesh */ unReferenceMeshFromUsingItsOwnMaterial(mesh, renderPassId) { let index = this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId); while (index >= 0) { this._meshesUsingTheirOwnMaterials.splice(index, 1); index = this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId); } mesh.resetDrawCache(renderPassId); } /** @internal */ _disposeMesh(mesh) { this.removeIncludedOnlyMesh(mesh); this.removeExcludedMesh(mesh); } }; ThinGlowLayer.EffectName = "GlowLayer"; ThinGlowLayer.DefaultBlurKernelSize = 32; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Layers/glowLayer.js init_tslib_es6(); init_decorators(); init_scene(); init_texture(); init_renderTargetTexture(); init_blurPostProcess(); init_typeStore(); init_decorators_serialization(); init_tools_functions(); Scene.prototype.getGlowLayerByName = function(name260) { for (let index = 0; index < this.effectLayers?.length; index++) { if (this.effectLayers[index].name === name260 && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) { return this.effectLayers[index]; } } return null; }; var GlowLayer = class _GlowLayer extends EffectLayer { static { __name(this, "GlowLayer"); } /** * Effect Name of the layer. */ static get EffectName() { return ThinGlowLayer.EffectName; } /** * Sets the kernel size of the blur. */ set blurKernelSize(value) { this._thinEffectLayer.blurKernelSize = value; } /** * Gets the kernel size of the blur. */ get blurKernelSize() { return this._thinEffectLayer.blurKernelSize; } /** * Sets the glow intensity. */ set intensity(value) { this._thinEffectLayer.intensity = value; } /** * Gets the glow intensity. */ get intensity() { return this._thinEffectLayer.intensity; } /** * Callback used to let the user override the color selection on a per mesh basis */ get customEmissiveColorSelector() { return this._thinEffectLayer.customEmissiveColorSelector; } set customEmissiveColorSelector(value) { this._thinEffectLayer.customEmissiveColorSelector = value; } /** * Callback used to let the user override the texture selection on a per mesh basis */ get customEmissiveTextureSelector() { return this._thinEffectLayer.customEmissiveTextureSelector; } set customEmissiveTextureSelector(value) { this._thinEffectLayer.customEmissiveTextureSelector = value; } /** * 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) */ constructor(name260, scene, options) { super(name260, scene, false, new ThinGlowLayer(name260, scene, options)); this._options = { mainTextureRatio: _GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: void 0, camera: null, mainTextureSamples: 1, renderingGroupId: -1, ldrMerge: false, alphaBlendingMode: 1, mainTextureType: 0, generateStencilBuffer: false, ...options }; this._init(this._options); } /** * Get the effect name of the layer. * @returns The effect name */ getEffectName() { return _GlowLayer.EffectName; } /** * @internal * 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. */ _createMergeEffect() { return this._thinEffectLayer._createMergeEffect(); } /** * Creates the render target textures and post processes used in the glow layer. */ _createTextureAndPostProcesses() { this._thinEffectLayer._renderPassId = this._mainTexture.renderPassId; let blurTextureWidth = this._mainTextureDesiredSize.width; let blurTextureHeight = this._mainTextureDesiredSize.height; blurTextureWidth = this._engine.needPOTTextures ? GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth; blurTextureHeight = this._engine.needPOTTextures ? GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight; let textureType = 0; if (this._engine.getCaps().textureHalfFloatRender) { textureType = 2; } else { textureType = 0; } this._blurTexture1 = new RenderTargetTexture("GlowLayerBlurRTT", { width: blurTextureWidth, height: blurTextureHeight }, this._scene, false, true, textureType); this._blurTexture1.wrapU = Texture.CLAMP_ADDRESSMODE; this._blurTexture1.wrapV = Texture.CLAMP_ADDRESSMODE; this._blurTexture1.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE); this._blurTexture1.renderParticles = false; this._blurTexture1.ignoreCameraViewport = true; const blurTextureWidth2 = Math.floor(blurTextureWidth / 2); const blurTextureHeight2 = Math.floor(blurTextureHeight / 2); this._blurTexture2 = new RenderTargetTexture("GlowLayerBlurRTT2", { width: blurTextureWidth2, height: blurTextureHeight2 }, this._scene, false, true, textureType); this._blurTexture2.wrapU = Texture.CLAMP_ADDRESSMODE; this._blurTexture2.wrapV = Texture.CLAMP_ADDRESSMODE; this._blurTexture2.updateSamplingMode(Texture.BILINEAR_SAMPLINGMODE); this._blurTexture2.renderParticles = false; this._blurTexture2.ignoreCameraViewport = true; this._textures = [this._blurTexture1, this._blurTexture2]; this._thinEffectLayer.bindTexturesForCompose = (effect) => { effect.setTexture("textureSampler", this._blurTexture1); effect.setTexture("textureSampler2", this._blurTexture2); effect.setFloat("offset", this.intensity); }; this._thinEffectLayer._createTextureAndPostProcesses(); const thinBlurPostProcesses1 = this._thinEffectLayer._postProcesses[0]; this._horizontalBlurPostprocess1 = new BlurPostProcess("GlowLayerHBP1", thinBlurPostProcesses1.direction, thinBlurPostProcesses1.kernel, { samplingMode: Texture.BILINEAR_SAMPLINGMODE, engine: this._scene.getEngine(), width: blurTextureWidth, height: blurTextureHeight, textureType, effectWrapper: thinBlurPostProcesses1 }); this._horizontalBlurPostprocess1.width = blurTextureWidth; this._horizontalBlurPostprocess1.height = blurTextureHeight; this._horizontalBlurPostprocess1.externalTextureSamplerBinding = true; this._horizontalBlurPostprocess1.onApplyObservable.add((effect) => { effect.setTexture("textureSampler", this._mainTexture); }); const thinBlurPostProcesses2 = this._thinEffectLayer._postProcesses[1]; this._verticalBlurPostprocess1 = new BlurPostProcess("GlowLayerVBP1", thinBlurPostProcesses2.direction, thinBlurPostProcesses2.kernel, { samplingMode: Texture.BILINEAR_SAMPLINGMODE, engine: this._scene.getEngine(), width: blurTextureWidth, height: blurTextureHeight, textureType, effectWrapper: thinBlurPostProcesses2 }); const thinBlurPostProcesses3 = this._thinEffectLayer._postProcesses[2]; this._horizontalBlurPostprocess2 = new BlurPostProcess("GlowLayerHBP2", thinBlurPostProcesses3.direction, thinBlurPostProcesses3.kernel, { samplingMode: Texture.BILINEAR_SAMPLINGMODE, engine: this._scene.getEngine(), width: blurTextureWidth2, height: blurTextureHeight2, textureType, effectWrapper: thinBlurPostProcesses3 }); this._horizontalBlurPostprocess2.width = blurTextureWidth2; this._horizontalBlurPostprocess2.height = blurTextureHeight2; this._horizontalBlurPostprocess2.externalTextureSamplerBinding = true; this._horizontalBlurPostprocess2.onApplyObservable.add((effect) => { effect.setTexture("textureSampler", this._blurTexture1); }); const thinBlurPostProcesses4 = this._thinEffectLayer._postProcesses[3]; this._verticalBlurPostprocess2 = new BlurPostProcess("GlowLayerVBP2", thinBlurPostProcesses4.direction, thinBlurPostProcesses4.kernel, { samplingMode: Texture.BILINEAR_SAMPLINGMODE, engine: this._scene.getEngine(), width: blurTextureWidth2, height: blurTextureHeight2, textureType, effectWrapper: thinBlurPostProcesses4 }); 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(() => { const internalTexture = this._blurTexture1.renderTarget; if (internalTexture) { this._scene.postProcessManager.directRender(this._postProcesses1, internalTexture, true); const internalTexture2 = this._blurTexture2.renderTarget; if (internalTexture2) { this._scene.postProcessManager.directRender(this._postProcesses2, internalTexture2, true); } this._engine.unBindFramebuffer(internalTexture2 ?? internalTexture, true); } }); this._postProcesses.map((pp) => { pp.autoClear = false; }); } /** * 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 * @returns true if ready otherwise, false */ isReady(subMesh, useInstances) { return this._thinEffectLayer.isReady(subMesh, useInstances); } /** * @returns whether or not the layer needs stencil enabled during the mesh rendering. */ needStencil() { 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 */ _canRenderMesh(mesh, material) { return this._thinEffectLayer._canRenderMesh(mesh, material); } /** * Implementation specific of rendering the generating effect on the main canvas. * @param effect The effect used to render through */ _internalRender(effect) { this._thinEffectLayer._internalCompose(effect); } /** * Sets the required values for both the emissive texture and and the main color. * @param mesh * @param subMesh * @param material */ _setEmissiveTextureAndColor(mesh, subMesh, material) { this._thinEffectLayer._setEmissiveTextureAndColor(mesh, subMesh, material); } /** * Returns true if the mesh should render, otherwise false. * @param mesh The mesh to render * @returns true if it should render otherwise false */ _shouldRenderMesh(mesh) { return this._thinEffectLayer._shouldRenderMesh(mesh); } /** * Adds specific effects defines. * @param defines The defines to add specifics to. */ _addCustomEffectDefines(defines) { this._thinEffectLayer._addCustomEffectDefines(defines); } /** * 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 */ addExcludedMesh(mesh) { this._thinEffectLayer.addExcludedMesh(mesh); } /** * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer. * @param mesh The mesh to remove */ removeExcludedMesh(mesh) { this._thinEffectLayer.removeExcludedMesh(mesh); } /** * 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 */ addIncludedOnlyMesh(mesh) { this._thinEffectLayer.addIncludedOnlyMesh(mesh); } /** * 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 */ removeIncludedOnlyMesh(mesh) { this._thinEffectLayer.removeIncludedOnlyMesh(mesh); } /** * 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 */ hasMesh(mesh) { return this._thinEffectLayer.hasMesh(mesh); } /** * Defines whether the current material of the mesh should be use to render the effect. * @param mesh defines the current mesh to render * @returns true if the material of the mesh should be use to render the effect */ _useMeshMaterial(mesh) { return this._thinEffectLayer._useMeshMaterial(mesh); } /** * 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 */ referenceMeshToUseItsOwnMaterial(mesh) { this._thinEffectLayer.referenceMeshToUseItsOwnMaterial(mesh); } /** * 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 */ unReferenceMeshFromUsingItsOwnMaterial(mesh) { this._thinEffectLayer.unReferenceMeshFromUsingItsOwnMaterial(mesh, this._mainTexture.renderPassId); } /** * Free any resources and references associated to a mesh. * Internal use * @param mesh The mesh to free. * @internal */ _disposeMesh(mesh) { this._thinEffectLayer._disposeMesh(mesh); } /** * Gets the class name of the effect layer * @returns the string with the class name of the effect layer */ getClassName() { return "GlowLayer"; } /** * Serializes this glow layer * @returns a serialized glow layer object */ serialize() { const serializationObject = SerializationHelper.Serialize(this); serializationObject.customType = "BABYLON.GlowLayer"; let index; serializationObject.includedMeshes = []; const includedOnlyMeshes = this._thinEffectLayer._includedOnlyMeshes; if (includedOnlyMeshes.length) { for (index = 0; index < includedOnlyMeshes.length; index++) { const mesh = this._scene.getMeshByUniqueId(includedOnlyMeshes[index]); if (mesh) { serializationObject.includedMeshes.push(mesh.id); } } } serializationObject.excludedMeshes = []; const excludedMeshes = this._thinEffectLayer._excludedMeshes; if (excludedMeshes.length) { for (index = 0; index < excludedMeshes.length; index++) { const mesh = this._scene.getMeshByUniqueId(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 */ static Parse(parsedGlowLayer, scene, rootUrl) { const gl = SerializationHelper.Parse(() => new _GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options), parsedGlowLayer, scene, rootUrl); let index; for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) { const mesh = scene.getMeshById(parsedGlowLayer.excludedMeshes[index]); if (mesh) { gl.addExcludedMesh(mesh); } } for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) { const mesh = scene.getMeshById(parsedGlowLayer.includedMeshes[index]); if (mesh) { gl.addIncludedOnlyMesh(mesh); } } return gl; } }; GlowLayer.DefaultBlurKernelSize = 32; GlowLayer.DefaultTextureRatio = 0.5; __decorate([ serialize() ], GlowLayer.prototype, "blurKernelSize", null); __decorate([ serialize() ], GlowLayer.prototype, "intensity", null); __decorate([ serialize("options") ], GlowLayer.prototype, "_options", void 0); RegisterClass("BABYLON.GlowLayer", GlowLayer); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinSharpenPostProcess.js init_effectRenderer(); init_engine(); var ThinSharpenPostProcess = class _ThinSharpenPostProcess extends EffectWrapper { static { __name(this, "ThinSharpenPostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_sharpen_fragment2(), sharpen_fragment_exports2))); } else { list.push(Promise.resolve().then(() => (init_sharpen_fragment(), sharpen_fragment_exports))); } } /** * Constructs a new sharpen post process * @param name Name of the effect * @param engine Engine to use to render the effect. If not provided, the last created engine will be used * @param options Options to configure the effect */ constructor(name260, engine = null, options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinSharpenPostProcess.FragmentUrl, uniforms: _ThinSharpenPostProcess.Uniforms }); this.colorAmount = 1; this.edgeAmount = 0.3; this.textureWidth = 0; this.textureHeight = 0; } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); const effect = this._drawWrapper.effect; effect.setFloat2("screenSize", this.textureWidth, this.textureHeight); effect.setFloat2("sharpnessAmounts", this.edgeAmount, this.colorAmount); } }; ThinSharpenPostProcess.FragmentUrl = "sharpen"; ThinSharpenPostProcess.Uniforms = ["sharpnessAmounts", "screenSize"]; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/sharpenPostProcess.js init_tslib_es6(); init_postProcess(); init_sharpen_fragment(); init_typeStore(); init_decorators(); init_decorators_serialization(); var SharpenPostProcess = class _SharpenPostProcess extends PostProcess { static { __name(this, "SharpenPostProcess"); } /** * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1) */ get colorAmount() { return this._effectWrapper.colorAmount; } set colorAmount(value) { this._effectWrapper.colorAmount = value; } /** * How much sharpness should be applied (default: 0.3) */ get edgeAmount() { return this._effectWrapper.edgeAmount; } set edgeAmount(value) { this._effectWrapper.edgeAmount = value; } /** * Gets a string identifying the name of the class * @returns "SharpenPostProcess" string */ getClassName() { return "SharpenPostProcess"; } /** * Creates a new instance ConvolutionPostProcess * @param name The name of the effect. * @param options The required width/height ratio to downsize to before computing the render pass. * @param camera The camera to apply the render pass to. * @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 blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ constructor(name260, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { const localOptions = { uniforms: ThinSharpenPostProcess.Uniforms, size: typeof options === "number" ? options : void 0, camera, samplingMode, engine, reusable, textureType, blockCompilation, ...options }; super(name260, ThinSharpenPostProcess.FragmentUrl, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinSharpenPostProcess(name260, engine, localOptions) : void 0, ...localOptions }); this.onApply = (_effect) => { this._effectWrapper.textureWidth = this.width; this._effectWrapper.textureHeight = this.height; }; } /** * @internal */ static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { return SerializationHelper.Parse(() => { return new _SharpenPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.textureType, parsedPostProcess.reusable); }, parsedPostProcess, scene, rootUrl); } }; __decorate([ serialize() ], SharpenPostProcess.prototype, "colorAmount", null); __decorate([ serialize() ], SharpenPostProcess.prototype, "edgeAmount", null); RegisterClass("BABYLON.SharpenPostProcess", SharpenPostProcess); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinImageProcessingPostProcess.js init_effectRenderer(); init_engine(); init_engineStore(); init_imageProcessingConfiguration(); var ThinImageProcessingPostProcess = class _ThinImageProcessingPostProcess extends EffectWrapper { static { __name(this, "ThinImageProcessingPostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_imageProcessing_fragment(), imageProcessing_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_imageProcessing_fragment2(), imageProcessing_fragment_exports2))); } } /** * Gets the image processing configuration used either in this material. */ get imageProcessingConfiguration() { 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 imageProcessingConfiguration(value) { value.applyByPostProcess = true; this._attachImageProcessingConfiguration(value); } /** * Attaches a new image processing configuration to the PBR Material. * @param configuration * @param doNotBuild */ _attachImageProcessingConfiguration(configuration, doNotBuild = false) { if (configuration === this._imageProcessingConfiguration) { return; } if (this._imageProcessingConfiguration && this._imageProcessingObserver) { this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); } if (!configuration) { let scene = this.options.scene; if (!scene) { const engine = this.options.engine; if (engine && engine.scenes) { const scenes = engine.scenes; scene = scenes[scenes.length - 1]; } else { scene = EngineStore.LastCreatedScene; } } if (scene) { this._imageProcessingConfiguration = scene.imageProcessingConfiguration; } else { this._imageProcessingConfiguration = new ImageProcessingConfiguration(); } } else { this._imageProcessingConfiguration = configuration; } if (this._imageProcessingConfiguration) { this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(() => { this._updateParameters(); }); } if (!doNotBuild) { this._updateParameters(); } } /** * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true . */ get colorCurves() { return this.imageProcessingConfiguration.colorCurves; } /** * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true . */ set colorCurves(value) { this.imageProcessingConfiguration.colorCurves = value; } /** * Gets whether the color curves effect is enabled. */ get colorCurvesEnabled() { return this.imageProcessingConfiguration.colorCurvesEnabled; } /** * Sets whether the color curves effect is enabled. */ set colorCurvesEnabled(value) { this.imageProcessingConfiguration.colorCurvesEnabled = value; } /** * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. */ get colorGradingTexture() { return this.imageProcessingConfiguration.colorGradingTexture; } /** * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. */ set colorGradingTexture(value) { this.imageProcessingConfiguration.colorGradingTexture = value; } /** * Gets whether the color grading effect is enabled. */ get colorGradingEnabled() { return this.imageProcessingConfiguration.colorGradingEnabled; } /** * Gets whether the color grading effect is enabled. */ set colorGradingEnabled(value) { this.imageProcessingConfiguration.colorGradingEnabled = value; } /** * Gets exposure used in the effect. */ get exposure() { return this.imageProcessingConfiguration.exposure; } /** * Sets exposure used in the effect. */ set exposure(value) { this.imageProcessingConfiguration.exposure = value; } /** * Gets whether tonemapping is enabled or not. */ get toneMappingEnabled() { return this._imageProcessingConfiguration.toneMappingEnabled; } /** * Sets whether tonemapping is enabled or not */ set toneMappingEnabled(value) { this._imageProcessingConfiguration.toneMappingEnabled = value; } /** * Gets the type of tone mapping effect. */ get toneMappingType() { return this._imageProcessingConfiguration.toneMappingType; } /** * Sets the type of tone mapping effect. */ set toneMappingType(value) { this._imageProcessingConfiguration.toneMappingType = value; } /** * Gets contrast used in the effect. */ get contrast() { return this.imageProcessingConfiguration.contrast; } /** * Sets contrast used in the effect. */ set contrast(value) { this.imageProcessingConfiguration.contrast = value; } /** * Gets Vignette stretch size. */ get vignetteStretch() { return this.imageProcessingConfiguration.vignetteStretch; } /** * Sets Vignette stretch size. */ set vignetteStretch(value) { this.imageProcessingConfiguration.vignetteStretch = value; } /** * Gets Vignette center X Offset. * @deprecated use vignetteCenterX instead */ get vignetteCentreX() { return this.imageProcessingConfiguration.vignetteCenterX; } /** * Sets Vignette center X Offset. * @deprecated use vignetteCenterX instead */ set vignetteCentreX(value) { this.imageProcessingConfiguration.vignetteCenterX = value; } /** * Gets Vignette center Y Offset. * @deprecated use vignetteCenterY instead */ get vignetteCentreY() { return this.imageProcessingConfiguration.vignetteCenterY; } /** * Sets Vignette center Y Offset. * @deprecated use vignetteCenterY instead */ set vignetteCentreY(value) { this.imageProcessingConfiguration.vignetteCenterY = value; } /** * Vignette center Y Offset. */ get vignetteCenterY() { return this.imageProcessingConfiguration.vignetteCenterY; } set vignetteCenterY(value) { this.imageProcessingConfiguration.vignetteCenterY = value; } /** * Vignette center X Offset. */ get vignetteCenterX() { return this.imageProcessingConfiguration.vignetteCenterX; } set vignetteCenterX(value) { this.imageProcessingConfiguration.vignetteCenterX = value; } /** * Gets Vignette weight or intensity of the vignette effect. */ get vignetteWeight() { return this.imageProcessingConfiguration.vignetteWeight; } /** * Sets Vignette weight or intensity of the vignette effect. */ set vignetteWeight(value) { this.imageProcessingConfiguration.vignetteWeight = value; } /** * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) * if vignetteEnabled is set to true. */ get vignetteColor() { return this.imageProcessingConfiguration.vignetteColor; } /** * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) * if vignetteEnabled is set to true. */ set vignetteColor(value) { this.imageProcessingConfiguration.vignetteColor = value; } /** * Gets Camera field of view used by the Vignette effect. */ get vignetteCameraFov() { return this.imageProcessingConfiguration.vignetteCameraFov; } /** * Sets Camera field of view used by the Vignette effect. */ set vignetteCameraFov(value) { this.imageProcessingConfiguration.vignetteCameraFov = value; } /** * Gets the vignette blend mode allowing different kind of effect. */ get vignetteBlendMode() { return this.imageProcessingConfiguration.vignetteBlendMode; } /** * Sets the vignette blend mode allowing different kind of effect. */ set vignetteBlendMode(value) { this.imageProcessingConfiguration.vignetteBlendMode = value; } /** * Gets whether the vignette effect is enabled. */ get vignetteEnabled() { return this.imageProcessingConfiguration.vignetteEnabled; } /** * Sets whether the vignette effect is enabled. */ set vignetteEnabled(value) { this.imageProcessingConfiguration.vignetteEnabled = value; } /** * Gets intensity of the dithering effect. */ get ditheringIntensity() { return this.imageProcessingConfiguration.ditheringIntensity; } /** * Sets intensity of the dithering effect. */ set ditheringIntensity(value) { this.imageProcessingConfiguration.ditheringIntensity = value; } /** * Gets whether the dithering effect is enabled. */ get ditheringEnabled() { return this.imageProcessingConfiguration.ditheringEnabled; } /** * Sets whether the dithering effect is enabled. */ set ditheringEnabled(value) { this.imageProcessingConfiguration.ditheringEnabled = value; } /** * Gets whether the input of the processing is in Gamma or Linear Space. */ get fromLinearSpace() { return this._fromLinearSpace; } /** * Sets whether the input of the processing is in Gamma or Linear Space. */ set fromLinearSpace(value) { if (this._fromLinearSpace === value) { return; } this._fromLinearSpace = value; this._updateParameters(); } /** * * Gets the width of the output texture used to store the result of the post process. */ get outputTextureWidth() { return this.imageProcessingConfiguration.outputTextureWidth; } /** * * Sets the width of the output texture used to store the result of the post process. */ set outputTextureWidth(value) { this.imageProcessingConfiguration.outputTextureWidth = value; } /** * * Gets the height of the output texture used to store the result of the post process. */ get outputTextureHeight() { return this.imageProcessingConfiguration.outputTextureHeight; } /** * * Sets the height of the output texture used to store the result of the post process. */ set outputTextureHeight(value) { this.imageProcessingConfiguration.outputTextureHeight = value; } /** * Constructs a new image processing post process * @param name Name of the effect * @param engine Engine to use to render the effect. If not provided, the last created engine will be used * @param options Options to configure the effect */ constructor(name260, engine = null, options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinImageProcessingPostProcess.FragmentUrl }); this._fromLinearSpace = true; this._defines = { IMAGEPROCESSING: false, VIGNETTE: false, VIGNETTEBLENDMODEMULTIPLY: false, VIGNETTEBLENDMODEOPAQUE: false, TONEMAPPING: 0, CONTRAST: false, COLORCURVES: false, COLORGRADING: false, COLORGRADING3D: false, FROMLINEARSPACE: false, SAMPLER3DGREENDEPTH: false, SAMPLER3DBGRMAP: false, DITHER: false, IMAGEPROCESSINGPOSTPROCESS: false, EXPOSURE: false, SKIPFINALCOLORCLAMP: false }; const imageProcessingConfiguration = options?.imageProcessingConfiguration; if (imageProcessingConfiguration) { imageProcessingConfiguration.applyByPostProcess = true; this._attachImageProcessingConfiguration(imageProcessingConfiguration, true); this._updateParameters(); } else { this._attachImageProcessingConfiguration(null, true); this.imageProcessingConfiguration.applyByPostProcess = true; } } /** * @internal */ _updateParameters() { this._defines.FROMLINEARSPACE = this._fromLinearSpace; this.imageProcessingConfiguration.prepareDefines(this._defines, true); let defines = ""; for (const prop in this._defines) { const value = this._defines[prop]; const type = typeof value; switch (type) { case "number": case "string": defines += `#define ${prop} ${value}; `; break; default: if (value) { defines += `#define ${prop}; `; } break; } } const samplers = ["textureSampler"]; const uniforms = ["scale"]; if (ImageProcessingConfiguration) { ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines); ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines); } this.updateEffect(defines, uniforms, samplers); } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); this.imageProcessingConfiguration.bind(this.effect, this.overrideAspectRatio); } dispose() { super.dispose(); if (this._imageProcessingConfiguration && this._imageProcessingObserver) { this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver); } if (this._imageProcessingConfiguration) { this.imageProcessingConfiguration.applyByPostProcess = false; } } }; ThinImageProcessingPostProcess.FragmentUrl = "imageProcessing"; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/imageProcessingPostProcess.js init_tslib_es6(); init_decorators(); init_postProcess(); var ImageProcessingPostProcess = class extends PostProcess { static { __name(this, "ImageProcessingPostProcess"); } get _imageProcessingConfiguration() { return this._effectWrapper.imageProcessingConfiguration; } /** * Gets the image processing configuration used either in this material. */ get imageProcessingConfiguration() { return this._effectWrapper.imageProcessingConfiguration; } /** * Sets the Default image processing configuration used either in the this material. * * If sets to null, the scene one is in use. */ set imageProcessingConfiguration(value) { this._effectWrapper.imageProcessingConfiguration = value; } /** * If the post process is supported. */ get isSupported() { const effect = this.getEffect(); return !effect || effect.isSupported; } /** * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true . */ get colorCurves() { return this.imageProcessingConfiguration.colorCurves; } /** * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true . */ set colorCurves(value) { this.imageProcessingConfiguration.colorCurves = value; } /** * Gets whether the color curves effect is enabled. */ get colorCurvesEnabled() { return this.imageProcessingConfiguration.colorCurvesEnabled; } /** * Sets whether the color curves effect is enabled. */ set colorCurvesEnabled(value) { this.imageProcessingConfiguration.colorCurvesEnabled = value; } /** * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. */ get colorGradingTexture() { return this.imageProcessingConfiguration.colorGradingTexture; } /** * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true. */ set colorGradingTexture(value) { this.imageProcessingConfiguration.colorGradingTexture = value; } /** * Gets whether the color grading effect is enabled. */ get colorGradingEnabled() { return this.imageProcessingConfiguration.colorGradingEnabled; } /** * Gets whether the color grading effect is enabled. */ set colorGradingEnabled(value) { this.imageProcessingConfiguration.colorGradingEnabled = value; } /** * Gets exposure used in the effect. */ get exposure() { return this.imageProcessingConfiguration.exposure; } /** * Sets exposure used in the effect. */ set exposure(value) { this.imageProcessingConfiguration.exposure = value; } /** * Gets whether tonemapping is enabled or not. */ get toneMappingEnabled() { return this._imageProcessingConfiguration.toneMappingEnabled; } /** * Sets whether tonemapping is enabled or not */ set toneMappingEnabled(value) { this._imageProcessingConfiguration.toneMappingEnabled = value; } /** * Gets the type of tone mapping effect. */ get toneMappingType() { return this._imageProcessingConfiguration.toneMappingType; } /** * Sets the type of tone mapping effect. */ set toneMappingType(value) { this._imageProcessingConfiguration.toneMappingType = value; } /** * Gets contrast used in the effect. */ get contrast() { return this.imageProcessingConfiguration.contrast; } /** * Sets contrast used in the effect. */ set contrast(value) { this.imageProcessingConfiguration.contrast = value; } /** * Gets Vignette stretch size. */ get vignetteStretch() { return this.imageProcessingConfiguration.vignetteStretch; } /** * Sets Vignette stretch size. */ set vignetteStretch(value) { this.imageProcessingConfiguration.vignetteStretch = value; } /** * Gets Vignette center X Offset. * @deprecated use vignetteCenterX instead */ get vignetteCentreX() { return this.imageProcessingConfiguration.vignetteCenterX; } /** * Sets Vignette center X Offset. * @deprecated use vignetteCenterX instead */ set vignetteCentreX(value) { this.imageProcessingConfiguration.vignetteCenterX = value; } /** * Gets Vignette center Y Offset. * @deprecated use vignetteCenterY instead */ get vignetteCentreY() { return this.imageProcessingConfiguration.vignetteCenterY; } /** * Sets Vignette center Y Offset. * @deprecated use vignetteCenterY instead */ set vignetteCentreY(value) { this.imageProcessingConfiguration.vignetteCenterY = value; } /** * Vignette center Y Offset. */ get vignetteCenterY() { return this.imageProcessingConfiguration.vignetteCenterY; } set vignetteCenterY(value) { this.imageProcessingConfiguration.vignetteCenterY = value; } /** * Vignette center X Offset. */ get vignetteCenterX() { return this.imageProcessingConfiguration.vignetteCenterX; } set vignetteCenterX(value) { this.imageProcessingConfiguration.vignetteCenterX = value; } /** * Gets Vignette weight or intensity of the vignette effect. */ get vignetteWeight() { return this.imageProcessingConfiguration.vignetteWeight; } /** * Sets Vignette weight or intensity of the vignette effect. */ set vignetteWeight(value) { this.imageProcessingConfiguration.vignetteWeight = value; } /** * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) * if vignetteEnabled is set to true. */ get vignetteColor() { return this.imageProcessingConfiguration.vignetteColor; } /** * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode) * if vignetteEnabled is set to true. */ set vignetteColor(value) { this.imageProcessingConfiguration.vignetteColor = value; } /** * Gets Camera field of view used by the Vignette effect. */ get vignetteCameraFov() { return this.imageProcessingConfiguration.vignetteCameraFov; } /** * Sets Camera field of view used by the Vignette effect. */ set vignetteCameraFov(value) { this.imageProcessingConfiguration.vignetteCameraFov = value; } /** * Gets the vignette blend mode allowing different kind of effect. */ get vignetteBlendMode() { return this.imageProcessingConfiguration.vignetteBlendMode; } /** * Sets the vignette blend mode allowing different kind of effect. */ set vignetteBlendMode(value) { this.imageProcessingConfiguration.vignetteBlendMode = value; } /** * Gets whether the vignette effect is enabled. */ get vignetteEnabled() { return this.imageProcessingConfiguration.vignetteEnabled; } /** * Sets whether the vignette effect is enabled. */ set vignetteEnabled(value) { this.imageProcessingConfiguration.vignetteEnabled = value; } /** * Gets intensity of the dithering effect. */ get ditheringIntensity() { return this.imageProcessingConfiguration.ditheringIntensity; } /** * Sets intensity of the dithering effect. */ set ditheringIntensity(value) { this.imageProcessingConfiguration.ditheringIntensity = value; } /** * Gets whether the dithering effect is enabled. */ get ditheringEnabled() { return this.imageProcessingConfiguration.ditheringEnabled; } /** * Sets whether the dithering effect is enabled. */ set ditheringEnabled(value) { this.imageProcessingConfiguration.ditheringEnabled = value; } /** * Gets whether the input of the processing is in Gamma or Linear Space. */ get fromLinearSpace() { return this._effectWrapper.fromLinearSpace; } /** * Sets whether the input of the processing is in Gamma or Linear Space. */ set fromLinearSpace(value) { this._effectWrapper.fromLinearSpace = value; } constructor(name260, options, camera = null, samplingMode, engine, reusable, textureType = 0, imageProcessingConfiguration) { const localOptions = { size: typeof options === "number" ? options : void 0, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration, scene: camera?.getScene(), ...options, blockCompilation: true }; super(name260, ThinImageProcessingPostProcess.FragmentUrl, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinImageProcessingPostProcess(name260, engine, localOptions) : void 0, ...localOptions }); this.onApply = () => { this._effectWrapper.overrideAspectRatio = this.aspectRatio; }; } /** * "ImageProcessingPostProcess" * @returns "ImageProcessingPostProcess" */ getClassName() { return "ImageProcessingPostProcess"; } /** * @internal */ _updateParameters() { this._effectWrapper._updateParameters(); } dispose(camera) { super.dispose(camera); if (this._imageProcessingConfiguration) { this.imageProcessingConfiguration.applyByPostProcess = false; } } }; __decorate([ serialize() ], ImageProcessingPostProcess.prototype, "fromLinearSpace", null); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinChromaticAberrationPostProcess.js init_effectRenderer(); init_engine(); init_math_vector(); var ThinChromaticAberrationPostProcess = class _ThinChromaticAberrationPostProcess extends EffectWrapper { static { __name(this, "ThinChromaticAberrationPostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_chromaticAberration_fragment(), chromaticAberration_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_chromaticAberration_fragment2(), chromaticAberration_fragment_exports2))); } } /** * Constructs a new chromatic aberration post process * @param name Name of the effect * @param engine Engine to use to render the effect. If not provided, the last created engine will be used * @param options Options to configure the effect */ constructor(name260, engine = null, options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinChromaticAberrationPostProcess.FragmentUrl, uniforms: _ThinChromaticAberrationPostProcess.Uniforms }); this.aberrationAmount = 30; this.radialIntensity = 0; this.direction = new Vector2(0.707, 0.707); this.centerPosition = new Vector2(0.5, 0.5); } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); const effect = this._drawWrapper.effect; effect.setFloat("chromatic_aberration", this.aberrationAmount); effect.setFloat("screen_width", this.screenWidth); effect.setFloat("screen_height", this.screenHeight); effect.setFloat("radialIntensity", this.radialIntensity); effect.setFloat2("direction", this.direction.x, this.direction.y); effect.setFloat2("centerPosition", this.centerPosition.x, this.centerPosition.y); } }; ThinChromaticAberrationPostProcess.FragmentUrl = "chromaticAberration"; ThinChromaticAberrationPostProcess.Uniforms = ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"]; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/chromaticAberrationPostProcess.js init_tslib_es6(); init_postProcess(); init_typeStore(); init_decorators(); init_decorators_serialization(); var ChromaticAberrationPostProcess = class _ChromaticAberrationPostProcess extends PostProcess { static { __name(this, "ChromaticAberrationPostProcess"); } /** * The amount of separation of rgb channels (default: 30) */ get aberrationAmount() { return this._effectWrapper.aberrationAmount; } set aberrationAmount(value) { this._effectWrapper.aberrationAmount = value; } /** * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0) */ get radialIntensity() { return this._effectWrapper.radialIntensity; } set radialIntensity(value) { this._effectWrapper.radialIntensity = value; } /** * The normalized direction in which the rgb channels should be separated. If set to 0,0 radial direction will be used. (default: Vector2(0.707,0.707)) */ get direction() { return this._effectWrapper.direction; } set direction(value) { this._effectWrapper.direction = value; } /** * The center position where the radialIntensity should be around. [0.5,0.5 is center of screen, 1,1 is top right corner] (default: Vector2(0.5 ,0.5)) */ get centerPosition() { return this._effectWrapper.centerPosition; } set centerPosition(value) { this._effectWrapper.centerPosition = value; } /** The width of the screen to apply the effect on */ get screenWidth() { return this._effectWrapper.screenWidth; } set screenWidth(value) { this._effectWrapper.screenWidth = value; } /** The height of the screen to apply the effect on */ get screenHeight() { return this._effectWrapper.screenHeight; } set screenHeight(value) { this._effectWrapper.screenHeight = value; } /** * Gets a string identifying the name of the class * @returns "ChromaticAberrationPostProcess" string */ getClassName() { return "ChromaticAberrationPostProcess"; } /** * Creates a new instance ChromaticAberrationPostProcess * @param name The name of the effect. * @param screenWidth The width of the screen to apply the effect on. * @param screenHeight The height of the screen to apply the effect on. * @param options The required width/height ratio to downsize to before computing the render pass. * @param camera The camera to apply the render pass to. * @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 blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ constructor(name260, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { const localOptions = { uniforms: ThinChromaticAberrationPostProcess.Uniforms, size: typeof options === "number" ? options : void 0, camera, samplingMode, engine, reusable, textureType, blockCompilation, ...options }; super(name260, ThinChromaticAberrationPostProcess.FragmentUrl, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinChromaticAberrationPostProcess(name260, engine, localOptions) : void 0, ...localOptions }); this.screenWidth = screenWidth; this.screenHeight = screenHeight; } /** * @internal */ static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { return SerializationHelper.Parse(() => { return new _ChromaticAberrationPostProcess(parsedPostProcess.name, parsedPostProcess.screenWidth, parsedPostProcess.screenHeight, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable, parsedPostProcess.textureType, false); }, parsedPostProcess, scene, rootUrl); } }; __decorate([ serialize() ], ChromaticAberrationPostProcess.prototype, "aberrationAmount", null); __decorate([ serialize() ], ChromaticAberrationPostProcess.prototype, "radialIntensity", null); __decorate([ serialize() ], ChromaticAberrationPostProcess.prototype, "direction", null); __decorate([ serialize() ], ChromaticAberrationPostProcess.prototype, "centerPosition", null); __decorate([ serialize() ], ChromaticAberrationPostProcess.prototype, "screenWidth", null); __decorate([ serialize() ], ChromaticAberrationPostProcess.prototype, "screenHeight", null); RegisterClass("BABYLON.ChromaticAberrationPostProcess", ChromaticAberrationPostProcess); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinGrainPostProcess.js init_effectRenderer(); init_engine(); var ThinGrainPostProcess = class _ThinGrainPostProcess extends EffectWrapper { static { __name(this, "ThinGrainPostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_grain_fragment(), grain_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_grain_fragment2(), grain_fragment_exports2))); } } /** * Constructs a new grain post process * @param name Name of the effect * @param engine Engine to use to render the effect. If not provided, the last created engine will be used * @param options Options to configure the effect */ constructor(name260, engine = null, options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinGrainPostProcess.FragmentUrl, uniforms: _ThinGrainPostProcess.Uniforms }); this.intensity = 30; this.animated = false; } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); this._drawWrapper.effect.setFloat("intensity", this.intensity); this._drawWrapper.effect.setFloat("animatedSeed", this.animated ? Math.random() + 1 : 1); } }; ThinGrainPostProcess.FragmentUrl = "grain"; ThinGrainPostProcess.Uniforms = ["intensity", "animatedSeed"]; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/grainPostProcess.js init_tslib_es6(); init_postProcess(); init_typeStore(); init_decorators(); init_decorators_serialization(); var GrainPostProcess = class _GrainPostProcess extends PostProcess { static { __name(this, "GrainPostProcess"); } /** * The intensity of the grain added (default: 30) */ get intensity() { return this._effectWrapper.intensity; } set intensity(value) { this._effectWrapper.intensity = value; } /** * If the grain should be randomized on every frame */ get animated() { return this._effectWrapper.animated; } set animated(value) { this._effectWrapper.animated = value; } /** * Gets a string identifying the name of the class * @returns "GrainPostProcess" string */ getClassName() { return "GrainPostProcess"; } /** * Creates a new instance of @see GrainPostProcess * @param name The name of the effect. * @param options The required width/height ratio to downsize to before computing the render pass. * @param camera The camera to apply the render pass to. * @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 blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ constructor(name260, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { const localOptions = { uniforms: ThinGrainPostProcess.Uniforms, size: typeof options === "number" ? options : void 0, camera, samplingMode, engine, reusable, textureType, blockCompilation, ...options }; super(name260, ThinGrainPostProcess.FragmentUrl, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinGrainPostProcess(name260, engine, localOptions) : void 0, ...localOptions }); } /** * @internal */ static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { return SerializationHelper.Parse(() => { return new _GrainPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); }, parsedPostProcess, scene, rootUrl); } }; __decorate([ serialize() ], GrainPostProcess.prototype, "intensity", null); __decorate([ serialize() ], GrainPostProcess.prototype, "animated", null); RegisterClass("BABYLON.GrainPostProcess", GrainPostProcess); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinFXAAPostProcess.js init_effectRenderer(); init_engine(); init_math_vector(); var ThinFXAAPostProcess = class _ThinFXAAPostProcess extends EffectWrapper { static { __name(this, "ThinFXAAPostProcess"); } static _GetDefines(engine) { if (!engine) { return null; } const driverInfo = engine.extractDriverInfo(); if (driverInfo.toLowerCase().indexOf("mali") > -1) { return "#define MALI 1\n"; } return null; } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.all([Promise.resolve().then(() => (init_fxaa_fragment(), fxaa_fragment_exports)), Promise.resolve().then(() => (init_fxaa_vertex(), fxaa_vertex_exports))])); } else { list.push(Promise.all([Promise.resolve().then(() => (init_fxaa_fragment2(), fxaa_fragment_exports2)), Promise.resolve().then(() => (init_fxaa_vertex2(), fxaa_vertex_exports2))])); } } /** * Constructs a new FXAA post process * @param name Name of the effect * @param engine Engine to use to render the effect. If not provided, the last created engine will be used * @param options Options to configure the effect */ constructor(name260, engine = null, options) { const localOptions = { ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, vertexShader: _ThinFXAAPostProcess.VertexUrl, fragmentShader: _ThinFXAAPostProcess.FragmentUrl, uniforms: _ThinFXAAPostProcess.Uniforms }; super({ ...localOptions, defines: _ThinFXAAPostProcess._GetDefines(localOptions.engine) }); this.texelSize = new Vector2(0, 0); } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); this._drawWrapper.effect.setFloat2("texelSize", this.texelSize.x, this.texelSize.y); } }; ThinFXAAPostProcess.VertexUrl = "fxaa"; ThinFXAAPostProcess.FragmentUrl = "fxaa"; ThinFXAAPostProcess.Uniforms = ["texelSize"]; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/fxaaPostProcess.js init_texture(); init_postProcess(); init_typeStore(); init_decorators_serialization(); var FxaaPostProcess = class _FxaaPostProcess extends PostProcess { static { __name(this, "FxaaPostProcess"); } /** * Gets a string identifying the name of the class * @returns "FxaaPostProcess" string */ getClassName() { return "FxaaPostProcess"; } constructor(name260, options, camera = null, samplingMode, engine, reusable, textureType = 0) { const localOptions = { uniforms: ThinFXAAPostProcess.Uniforms, size: typeof options === "number" ? options : void 0, camera, samplingMode: samplingMode || Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType, ...options }; super(name260, ThinFXAAPostProcess.FragmentUrl, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinFXAAPostProcess(name260, engine, localOptions) : void 0, ...localOptions }); this.onApplyObservable.add((_effect) => { this._effectWrapper.texelSize = this.texelSize; }); } /** * @internal */ static _Parse(parsedPostProcess, targetCamera, scene, rootUrl) { return SerializationHelper.Parse(() => { return new _FxaaPostProcess(parsedPostProcess.name, parsedPostProcess.options, targetCamera, parsedPostProcess.renderTargetSamplingMode, scene.getEngine(), parsedPostProcess.reusable); }, parsedPostProcess, scene, rootUrl); } }; RegisterClass("BABYLON.FxaaPostProcess", FxaaPostProcess); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinCircleOfConfusionPostProcess.js init_effectRenderer(); init_engine(); var ThinCircleOfConfusionPostProcess = class _ThinCircleOfConfusionPostProcess extends EffectWrapper { static { __name(this, "ThinCircleOfConfusionPostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_circleOfConfusion_fragment(), circleOfConfusion_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_circleOfConfusion_fragment2(), circleOfConfusion_fragment_exports2))); } } /** * Constructs a new circle of confusion post process * @param name Name of the effect * @param engine Engine to use to render the effect. If not provided, the last created engine will be used * @param options Options to configure the effect */ constructor(name260, engine = null, options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinCircleOfConfusionPostProcess.FragmentUrl, uniforms: _ThinCircleOfConfusionPostProcess.Uniforms, samplers: _ThinCircleOfConfusionPostProcess.Samplers, defines: options?.depthNotNormalized ? _ThinCircleOfConfusionPostProcess.DefinesDepthNotNormalized : void 0 }); this.lensSize = 50; this.fStop = 1.4; this.focusDistance = 2e3; this.focalLength = 50; } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); const options = this.options; const effect = this._drawWrapper.effect; if (!options.depthNotNormalized) { effect.setFloat2("cameraMinMaxZ", this.camera.minZ, this.camera.maxZ - this.camera.minZ); } const aperture = this.lensSize / this.fStop; const cocPrecalculation = aperture * this.focalLength / (this.focusDistance - this.focalLength); effect.setFloat("focusDistance", this.focusDistance); effect.setFloat("cocPrecalculation", cocPrecalculation); } }; ThinCircleOfConfusionPostProcess.FragmentUrl = "circleOfConfusion"; ThinCircleOfConfusionPostProcess.Uniforms = ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"]; ThinCircleOfConfusionPostProcess.Samplers = ["depthSampler"]; ThinCircleOfConfusionPostProcess.DefinesDepthNotNormalized = "#define COC_DEPTH_NOT_NORMALIZED"; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/circleOfConfusionPostProcess.js init_tslib_es6(); init_postProcess(); init_logger(); init_typeStore(); init_decorators(); var CircleOfConfusionPostProcess = class extends PostProcess { static { __name(this, "CircleOfConfusionPostProcess"); } /** * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diameter of the resulting aperture can be computed by lensSize/fStop. */ get lensSize() { return this._effectWrapper.lensSize; } set lensSize(value) { this._effectWrapper.lensSize = value; } /** * F-Stop of the effect's camera. The diameter of the resulting aperture can be computed by lensSize/fStop. (default: 1.4) */ get fStop() { return this._effectWrapper.fStop; } set fStop(value) { this._effectWrapper.fStop = value; } /** * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000) */ get focusDistance() { return this._effectWrapper.focusDistance; } set focusDistance(value) { this._effectWrapper.focusDistance = value; } /** * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50) */ get focalLength() { return this._effectWrapper.focalLength; } set focalLength(value) { this._effectWrapper.focalLength = value; } /** * Gets a string identifying the name of the class * @returns "CircleOfConfusionPostProcess" string */ getClassName() { return "CircleOfConfusionPostProcess"; } /** * Creates a new instance CircleOfConfusionPostProcess * @param name The name of the effect. * @param depthTexture The depth texture of the scene to compute the circle of confusion. This must be set in order for this to function but may be set after initialization if needed. * @param options The required width/height ratio to downsize to before computing the render pass. * @param camera The camera to apply the render pass to. * @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 blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ constructor(name260, depthTexture, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { const localOptions = { uniforms: ThinCircleOfConfusionPostProcess.Uniforms, samplers: ThinCircleOfConfusionPostProcess.Samplers, defines: typeof options === "object" && options.depthNotNormalized ? ThinCircleOfConfusionPostProcess.DefinesDepthNotNormalized : void 0, size: typeof options === "number" ? options : void 0, camera, samplingMode, engine, reusable, textureType, blockCompilation, ...options }; super(name260, ThinCircleOfConfusionPostProcess.FragmentUrl, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinCircleOfConfusionPostProcess(name260, engine, localOptions) : void 0, ...localOptions }); this._depthTexture = null; this._depthTexture = depthTexture; this.onApplyObservable.add((effect) => { if (!this._depthTexture) { Logger.Warn("No depth texture set on CircleOfConfusionPostProcess"); return; } effect.setTexture("depthSampler", this._depthTexture); this._effectWrapper.camera = this._depthTexture.activeCamera; }); } /** * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function. */ set depthTexture(value) { this._depthTexture = value; } }; __decorate([ serialize() ], CircleOfConfusionPostProcess.prototype, "lensSize", null); __decorate([ serialize() ], CircleOfConfusionPostProcess.prototype, "fStop", null); __decorate([ serialize() ], CircleOfConfusionPostProcess.prototype, "focusDistance", null); __decorate([ serialize() ], CircleOfConfusionPostProcess.prototype, "focalLength", null); RegisterClass("BABYLON.CircleOfConfusionPostProcess", CircleOfConfusionPostProcess); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinDepthOfFieldBlurPostProcess.js init_thinBlurPostProcess(); var ThinDepthOfFieldBlurPostProcess = class extends ThinBlurPostProcess { static { __name(this, "ThinDepthOfFieldBlurPostProcess"); } constructor(name260, engine = null, direction, kernel, options) { super(name260, engine, direction, kernel, { ...options, defines: `#define DOF 1 ` }); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/depthOfFieldBlurPostProcess.js init_texture(); init_blurPostProcess(); init_typeStore(); var DepthOfFieldBlurPostProcess = class extends BlurPostProcess { static { __name(this, "DepthOfFieldBlurPostProcess"); } /** * Gets a string identifying the name of the class * @returns "DepthOfFieldBlurPostProcess" string */ getClassName() { return "DepthOfFieldBlurPostProcess"; } /** * Creates a new instance DepthOfFieldBlurPostProcess * @param name The name of the effect. * @param _scene The scene the effect belongs to (not used, you can pass null) * @param direction The direction the blur should be applied. * @param kernel The size of the kernel used to blur. * @param options The required width/height ratio to downsize to before computing the render pass. * @param camera The camera to apply the render pass to. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring across edges * @param imageToBlur The image to apply the blur to (default: Current rendered frame) * @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 blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) * @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA) */ constructor(name260, _scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur = null, samplingMode = Texture.BILINEAR_SAMPLINGMODE, engine, reusable, textureType = 0, blockCompilation = false, textureFormat = 5) { const localOptions = { size: typeof options === "number" ? options : void 0, camera, // eslint-disable-next-line @typescript-eslint/no-unused-vars samplingMode: samplingMode = 2, engine, reusable, textureType, defines: `#define DOF 1 `, blockCompilation, textureFormat, ...options }; super(name260, direction, kernel, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinDepthOfFieldBlurPostProcess(name260, engine, direction, kernel, localOptions) : void 0, ...localOptions }); this.externalTextureSamplerBinding = !!imageToBlur; this.onApplyObservable.add((effect) => { if (imageToBlur != null) { effect.setTextureFromPostProcess("textureSampler", imageToBlur); } effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion); }); } }; RegisterClass("BABYLON.DepthOfFieldBlurPostProcess", DepthOfFieldBlurPostProcess); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinDepthOfFieldMergePostProcess.js init_effectRenderer(); init_engine(); var ThinDepthOfFieldMergePostProcess = class _ThinDepthOfFieldMergePostProcess extends EffectWrapper { static { __name(this, "ThinDepthOfFieldMergePostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_depthOfFieldMerge_fragment(), depthOfFieldMerge_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_depthOfFieldMerge_fragment2(), depthOfFieldMerge_fragment_exports2))); } } constructor(name260, engine = null, options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinDepthOfFieldMergePostProcess.FragmentUrl, samplers: _ThinDepthOfFieldMergePostProcess.Samplers }); } }; ThinDepthOfFieldMergePostProcess.FragmentUrl = "depthOfFieldMerge"; ThinDepthOfFieldMergePostProcess.Samplers = ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"]; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/depthOfFieldMergePostProcess.js init_postProcess(); var DepthOfFieldMergePostProcess = class extends PostProcess { static { __name(this, "DepthOfFieldMergePostProcess"); } /** * Gets a string identifying the name of the class * @returns "DepthOfFieldMergePostProcess" string */ getClassName() { return "DepthOfFieldMergePostProcess"; } /** * Creates a new instance of DepthOfFieldMergePostProcess * @param name The name of the effect. * @param originalFromInput Post process which's input will be used for the merge. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel. * @param _blurSteps Blur post processes from low to high which will be mixed with the original image. * @param options The required width/height ratio to downsize to before computing the render pass. * @param camera The camera to apply the render pass to. * @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 blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ constructor(name260, originalFromInput, circleOfConfusion, _blurSteps, options, camera, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { const blockCompilationFinal = typeof options === "number" ? blockCompilation : !!options.blockCompilation; const localOptions = { samplers: ThinDepthOfFieldMergePostProcess.Samplers, size: typeof options === "number" ? options : void 0, camera, samplingMode, engine, reusable, textureType, ...options, blockCompilation: true }; super(name260, ThinDepthOfFieldMergePostProcess.FragmentUrl, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinDepthOfFieldMergePostProcess(name260, engine, localOptions) : void 0, ...localOptions }); this._blurSteps = _blurSteps; this.externalTextureSamplerBinding = true; this.onApplyObservable.add((effect) => { effect.setTextureFromPostProcess("textureSampler", originalFromInput); effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion); for (let i = 0; i < _blurSteps.length; i++) { const step = _blurSteps[i]; effect.setTextureFromPostProcessOutput("blurStep" + (_blurSteps.length - i - 1), step); } }); if (!blockCompilationFinal) { this.updateEffect(); } } /** * Updates the effect with the current post process compile time values and recompiles the shader. * @param defines Define statements that should be added at the beginning of the shader. (default: null) * @param uniforms Set of uniform variables that will be passed to the shader. (default: null) * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null) * @param indexParameters The index parameters to be used for babylons include syntax "#include[0..varyingCount]". (default: undefined) See usage in babylon.blurPostProcess.ts and kernelBlur.vertex.fx * @param onCompiled Called when the shader has been compiled. * @param onError Called if there is an error when compiling a shader. */ updateEffect(defines = null, uniforms = null, samplers = null, indexParameters, onCompiled, onError) { if (!defines) { defines = ""; defines += "#define BLUR_LEVEL " + (this._blurSteps.length - 1) + "\n"; } super.updateEffect(defines, uniforms, samplers, indexParameters, onCompiled, onError); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinDepthOfFieldEffect.js init_math_vector(); var ThinDepthOfFieldEffectBlurLevel; (function(ThinDepthOfFieldEffectBlurLevel2) { ThinDepthOfFieldEffectBlurLevel2[ThinDepthOfFieldEffectBlurLevel2["Low"] = 0] = "Low"; ThinDepthOfFieldEffectBlurLevel2[ThinDepthOfFieldEffectBlurLevel2["Medium"] = 1] = "Medium"; ThinDepthOfFieldEffectBlurLevel2[ThinDepthOfFieldEffectBlurLevel2["High"] = 2] = "High"; })(ThinDepthOfFieldEffectBlurLevel || (ThinDepthOfFieldEffectBlurLevel = {})); var ThinDepthOfFieldEffect = class { static { __name(this, "ThinDepthOfFieldEffect"); } /** * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter) */ set focalLength(value) { this._circleOfConfusion.focalLength = value; } get focalLength() { return this._circleOfConfusion.focalLength; } /** * F-Stop of the effect's camera. The diameter of the resulting aperture can be computed by lensSize/fStop. (default: 1.4) */ set fStop(value) { this._circleOfConfusion.fStop = value; } get fStop() { return this._circleOfConfusion.fStop; } /** * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000) */ set focusDistance(value) { this._circleOfConfusion.focusDistance = value; } get focusDistance() { return this._circleOfConfusion.focusDistance; } /** * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diameter of the resulting aperture can be computed by lensSize/fStop. */ set lensSize(value) { this._circleOfConfusion.lensSize = value; } get lensSize() { return this._circleOfConfusion.lensSize; } /** * Creates a new instance of @see ThinDepthOfFieldEffect * @param name The name of the depth of field render effect * @param engine The engine which the render effect will be applied. (default: current engine) * @param blurLevel The quality of the effect. (default: DepthOfFieldEffectBlurLevel.Low) * @param depthNotNormalized If the (view) depth used in circle of confusion post-process is normalized (0.0 to 1.0 from near to far) or not (0 to camera max distance) (default: false) * @param blockCompilation If shaders should not be compiled when the effect is created (default: false) */ constructor(name260, engine, blurLevel = 0, depthNotNormalized = false, blockCompilation = false) { this._depthOfFieldBlurX = []; this._depthOfFieldBlurY = []; this._circleOfConfusion = new ThinCircleOfConfusionPostProcess(name260, engine, { depthNotNormalized, blockCompilation }); this.blurLevel = blurLevel; let blurCount = 1; let kernelSize = 15; switch (blurLevel) { case 2: { blurCount = 3; kernelSize = 51; break; } case 1: { blurCount = 2; kernelSize = 31; break; } default: { kernelSize = 15; blurCount = 1; break; } } const adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1); let ratio = 1; for (let i = 0; i < blurCount; i++) { this._depthOfFieldBlurY.push([new ThinDepthOfFieldBlurPostProcess(name260, engine, new Vector2(0, 1), adjustedKernelSize, { blockCompilation }), ratio]); ratio = 0.75 / Math.pow(2, i); this._depthOfFieldBlurX.push([new ThinDepthOfFieldBlurPostProcess(name260, engine, new Vector2(1, 0), adjustedKernelSize, { blockCompilation }), ratio]); } this._dofMerge = new ThinDepthOfFieldMergePostProcess(name260, engine, { blockCompilation }); } /** * Checks if the effect is ready to be used * @returns if the effect is ready */ isReady() { let isReady = this._circleOfConfusion.isReady() && this._dofMerge.isReady(); for (let i = 0; i < this._depthOfFieldBlurX.length; i++) { isReady = isReady && this._depthOfFieldBlurX[i][0].isReady() && this._depthOfFieldBlurY[i][0].isReady(); } return isReady; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/depthOfFieldEffect.js init_texture(); var DepthOfFieldEffectBlurLevel; (function(DepthOfFieldEffectBlurLevel2) { DepthOfFieldEffectBlurLevel2[DepthOfFieldEffectBlurLevel2["Low"] = 0] = "Low"; DepthOfFieldEffectBlurLevel2[DepthOfFieldEffectBlurLevel2["Medium"] = 1] = "Medium"; DepthOfFieldEffectBlurLevel2[DepthOfFieldEffectBlurLevel2["High"] = 2] = "High"; })(DepthOfFieldEffectBlurLevel || (DepthOfFieldEffectBlurLevel = {})); var DepthOfFieldEffect = class extends PostProcessRenderEffect { static { __name(this, "DepthOfFieldEffect"); } /** * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter) */ set focalLength(value) { this._thinDepthOfFieldEffect.focalLength = value; } get focalLength() { return this._thinDepthOfFieldEffect.focalLength; } /** * F-Stop of the effect's camera. The diameter of the resulting aperture can be computed by lensSize/fStop. (default: 1.4) */ set fStop(value) { this._thinDepthOfFieldEffect.fStop = value; } get fStop() { return this._thinDepthOfFieldEffect.fStop; } /** * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000) */ set focusDistance(value) { this._thinDepthOfFieldEffect.focusDistance = value; } get focusDistance() { return this._thinDepthOfFieldEffect.focusDistance; } /** * Max lens size in scene units/1000 (eg. millimeter). Standard cameras are 50mm. (default: 50) The diameter of the resulting aperture can be computed by lensSize/fStop. */ set lensSize(value) { this._thinDepthOfFieldEffect.lensSize = value; } get lensSize() { return this._thinDepthOfFieldEffect.lensSize; } /** * Creates a new instance DepthOfFieldEffect * @param sceneOrEngine The scene or engine the effect belongs to. * @param depthTexture The depth texture of the scene to compute the circle of confusion.This must be set in order for this to function but may be set after initialization if needed. * @param blurLevel * @param pipelineTextureType The type of texture to be used when performing the post processing. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) * @param depthNotNormalized If the depth from the depth texture is already normalized or if the normalization should be done at runtime in the shader (default: false) */ constructor(sceneOrEngine, depthTexture, blurLevel = 0, pipelineTextureType = 0, blockCompilation = false, depthNotNormalized = false) { const engine = sceneOrEngine._renderForCamera ? sceneOrEngine.getEngine() : sceneOrEngine; super(engine, "depth of field", () => { return this._effects; }, true); this._effects = []; this._thinDepthOfFieldEffect = new ThinDepthOfFieldEffect("Depth of Field", engine, blurLevel, false, blockCompilation); const circleOfConfusionTextureFormat = engine.isWebGPU || engine.version > 1 ? 6 : 5; this._circleOfConfusion = new CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, { size: 1, samplingMode: Texture.BILINEAR_SAMPLINGMODE, engine, textureType: pipelineTextureType, blockCompilation, depthNotNormalized, effectWrapper: this._thinDepthOfFieldEffect._circleOfConfusion }, null); this._depthOfFieldBlurY = []; this._depthOfFieldBlurX = []; const blurCount = this._thinDepthOfFieldEffect._depthOfFieldBlurX.length; for (let i = 0; i < blurCount; i++) { const [thinBlurY, ratioY] = this._thinDepthOfFieldEffect._depthOfFieldBlurY[i]; const blurY = new DepthOfFieldBlurPostProcess("vertical blur", null, thinBlurY.direction, thinBlurY.kernel, { size: ratioY, samplingMode: Texture.BILINEAR_SAMPLINGMODE, engine, textureType: pipelineTextureType, blockCompilation, textureFormat: i == 0 ? circleOfConfusionTextureFormat : 5, effectWrapper: thinBlurY }, null, this._circleOfConfusion, i == 0 ? this._circleOfConfusion : null); blurY.autoClear = false; const [thinBlurX, ratioX] = this._thinDepthOfFieldEffect._depthOfFieldBlurX[i]; const blurX = new DepthOfFieldBlurPostProcess("horizontal blur", null, thinBlurX.direction, thinBlurX.kernel, { size: ratioX, samplingMode: Texture.BILINEAR_SAMPLINGMODE, engine, textureType: pipelineTextureType, blockCompilation, effectWrapper: thinBlurX }, null, this._circleOfConfusion, null); blurX.autoClear = false; this._depthOfFieldBlurY.push(blurY); this._depthOfFieldBlurX.push(blurX); } this._effects = [this._circleOfConfusion]; for (let i = 0; i < this._depthOfFieldBlurX.length; i++) { this._effects.push(this._depthOfFieldBlurY[i]); this._effects.push(this._depthOfFieldBlurX[i]); } this._dofMerge = new DepthOfFieldMergePostProcess("dofMerge", this._circleOfConfusion, this._circleOfConfusion, this._depthOfFieldBlurX, { size: this._thinDepthOfFieldEffect._depthOfFieldBlurX[blurCount - 1][1], samplingMode: Texture.BILINEAR_SAMPLINGMODE, engine, textureType: pipelineTextureType, blockCompilation, effectWrapper: this._thinDepthOfFieldEffect._dofMerge }, null); this._dofMerge.autoClear = false; this._effects.push(this._dofMerge); } /** * Get the current class name of the current effect * @returns "DepthOfFieldEffect" */ getClassName() { return "DepthOfFieldEffect"; } /** * Depth texture to be used to compute the circle of confusion. This must be set here or in the constructor in order for the post process to function. */ set depthTexture(value) { this._circleOfConfusion.depthTexture = value; } /** * Disposes each of the internal effects for a given camera. * @param camera The camera to dispose the effect on. */ disposeEffects(camera) { for (let effectIndex = 0; effectIndex < this._effects.length; effectIndex++) { this._effects[effectIndex].dispose(camera); } } /** * @internal Internal */ _updateEffects() { for (let effectIndex = 0; effectIndex < this._effects.length; effectIndex++) { this._effects[effectIndex].updateEffect(); } } /** * Internal * @returns if all the contained post processes are ready. * @internal */ _isReady() { return this._thinDepthOfFieldEffect.isReady(); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinExtractHighlightsPostProcess.js init_effectRenderer(); init_math_constants(); init_engine(); var ThinExtractHighlightsPostProcess = class _ThinExtractHighlightsPostProcess extends EffectWrapper { static { __name(this, "ThinExtractHighlightsPostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_extractHighlights_fragment(), extractHighlights_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_extractHighlights_fragment2(), extractHighlights_fragment_exports2))); } } /** * Constructs a new extract highlights post process * @param name Name of the effect * @param engine Engine to use to render the effect. If not provided, the last created engine will be used * @param options Options to configure the effect */ constructor(name260, engine = null, options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinExtractHighlightsPostProcess.FragmentUrl, uniforms: _ThinExtractHighlightsPostProcess.Uniforms }); this.threshold = 0.9; this._exposure = 1; } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); const effect = this._drawWrapper.effect; effect.setFloat("threshold", Math.pow(this.threshold, ToGammaSpace)); effect.setFloat("exposure", this._exposure); } }; ThinExtractHighlightsPostProcess.FragmentUrl = "extractHighlights"; ThinExtractHighlightsPostProcess.Uniforms = ["threshold", "exposure"]; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/extractHighlightsPostProcess.js init_tslib_es6(); init_postProcess(); init_decorators(); init_typeStore(); var ExtractHighlightsPostProcess = class extends PostProcess { static { __name(this, "ExtractHighlightsPostProcess"); } /** * The luminance threshold, pixels below this value will be set to black. */ get threshold() { return this._effectWrapper.threshold; } set threshold(value) { this._effectWrapper.threshold = value; } /** @internal */ get _exposure() { return this._effectWrapper._exposure; } /** @internal */ set _exposure(value) { this._effectWrapper._exposure = value; } /** * Gets a string identifying the name of the class * @returns "ExtractHighlightsPostProcess" string */ getClassName() { return "ExtractHighlightsPostProcess"; } constructor(name260, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { const localOptions = { uniforms: ThinExtractHighlightsPostProcess.Uniforms, size: typeof options === "number" ? options : void 0, camera, samplingMode, engine, reusable, textureType, blockCompilation, ...options }; super(name260, ThinExtractHighlightsPostProcess.FragmentUrl, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinExtractHighlightsPostProcess(name260, engine, localOptions) : void 0, ...localOptions }); this._inputPostProcess = null; this.onApplyObservable.add((effect) => { this.externalTextureSamplerBinding = !!this._inputPostProcess; if (this._inputPostProcess) { effect.setTextureFromPostProcess("textureSampler", this._inputPostProcess); } }); } }; __decorate([ serialize() ], ExtractHighlightsPostProcess.prototype, "threshold", null); RegisterClass("BABYLON.ExtractHighlightsPostProcess", ExtractHighlightsPostProcess); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinBloomMergePostProcess.js init_effectRenderer(); init_engine(); var ThinBloomMergePostProcess = class _ThinBloomMergePostProcess extends EffectWrapper { static { __name(this, "ThinBloomMergePostProcess"); } _gatherImports(useWebGPU, list) { if (useWebGPU) { this._webGPUReady = true; list.push(Promise.resolve().then(() => (init_bloomMerge_fragment(), bloomMerge_fragment_exports))); } else { list.push(Promise.resolve().then(() => (init_bloomMerge_fragment2(), bloomMerge_fragment_exports2))); } } constructor(name260, engine = null, options) { super({ ...options, name: name260, engine: engine || Engine.LastCreatedEngine, useShaderStore: true, useAsPostProcess: true, fragmentShader: _ThinBloomMergePostProcess.FragmentUrl, uniforms: _ThinBloomMergePostProcess.Uniforms, samplers: _ThinBloomMergePostProcess.Samplers }); this.weight = 1; } bind(noDefaultBindings = false) { super.bind(noDefaultBindings); this._drawWrapper.effect.setFloat("bloomWeight", this.weight); } }; ThinBloomMergePostProcess.FragmentUrl = "bloomMerge"; ThinBloomMergePostProcess.Uniforms = ["bloomWeight"]; ThinBloomMergePostProcess.Samplers = ["bloomBlur"]; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/bloomMergePostProcess.js init_tslib_es6(); init_postProcess(); init_typeStore(); init_decorators(); var BloomMergePostProcess = class extends PostProcess { static { __name(this, "BloomMergePostProcess"); } /** Weight of the bloom to be added to the original input. */ get weight() { return this._effectWrapper.weight; } set weight(value) { this._effectWrapper.weight = value; } /** * Gets a string identifying the name of the class * @returns "BloomMergePostProcess" string */ getClassName() { return "BloomMergePostProcess"; } /** * Creates a new instance of @see BloomMergePostProcess * @param name The name of the effect. * @param originalFromInput Post process which's input will be used for the merge. * @param blurred Blurred highlights post process which's output will be used. * @param weight Weight of the bloom to be added to the original input. * @param options The required width/height ratio to downsize to before computing the render pass. * @param camera The camera to apply the render pass to. * @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 blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ constructor(name260, originalFromInput, blurred, weight, options, camera = null, samplingMode, engine, reusable, textureType = 0, blockCompilation = false) { const blockCompilationFinal = typeof options === "number" ? blockCompilation : !!options.blockCompilation; const localOptions = { uniforms: ThinBloomMergePostProcess.Uniforms, samplers: ThinBloomMergePostProcess.Samplers, size: typeof options === "number" ? options : void 0, camera, samplingMode, engine, reusable, textureType, ...options, blockCompilation: true }; super(name260, ThinBloomMergePostProcess.FragmentUrl, { effectWrapper: typeof options === "number" || !options.effectWrapper ? new ThinBloomMergePostProcess(name260, engine, localOptions) : void 0, ...localOptions }); this.weight = weight; this.externalTextureSamplerBinding = true; this.onApplyObservable.add((effect) => { effect.setTextureFromPostProcess("textureSampler", originalFromInput); effect.setTextureFromPostProcessOutput("bloomBlur", blurred); }); if (!blockCompilationFinal) { this.updateEffect(); } } }; __decorate([ serialize() ], BloomMergePostProcess.prototype, "weight", null); RegisterClass("BABYLON.BloomMergePostProcess", BloomMergePostProcess); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/thinBloomEffect.js init_math_vector(); init_thinBlurPostProcess(); var ThinBloomEffect = class { static { __name(this, "ThinBloomEffect"); } /** * The luminance threshold to find bright areas of the image to bloom. */ get threshold() { return this._downscale.threshold; } set threshold(value) { this._downscale.threshold = value; } /** * The strength of the bloom. */ get weight() { return this._merge.weight; } set weight(value) { this._merge.weight = value; } /** * Specifies the size of the bloom blur kernel, relative to the final output size */ get kernel() { return this._blurX.kernel / this.scale; } set kernel(value) { this._blurX.kernel = value * this.scale; this._blurY.kernel = value * this.scale; } /** * Creates a new instance of @see ThinBloomEffect * @param name The name of the bloom render effect * @param engine The engine which the render effect will be applied. (default: current engine) * @param scale The ratio of the blur texture to the input texture that should be used to compute the bloom. * @param blockCompilation If shaders should not be compiled when the effect is created (default: false) */ constructor(name260, engine, scale, blockCompilation = false) { this.scale = scale; this._downscale = new ThinExtractHighlightsPostProcess(name260 + "_downscale", engine, { blockCompilation }); this._blurX = new ThinBlurPostProcess(name260 + "_blurX", engine, new Vector2(1, 0), 10, { blockCompilation }); this._blurY = new ThinBlurPostProcess(name260 + "_blurY", engine, new Vector2(0, 1), 10, { blockCompilation }); this._merge = new ThinBloomMergePostProcess(name260 + "_merge", engine, { blockCompilation }); } /** * Checks if the effect is ready to be used * @returns if the effect is ready */ isReady() { return this._downscale.isReady() && this._blurX.isReady() && this._blurY.isReady() && this._merge.isReady(); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/bloomEffect.js init_blurPostProcess(); init_texture(); var BloomEffect = class extends PostProcessRenderEffect { static { __name(this, "BloomEffect"); } /** * The luminance threshold to find bright areas of the image to bloom. */ get threshold() { return this._thinBloomEffect.threshold; } set threshold(value) { this._thinBloomEffect.threshold = value; } /** * The strength of the bloom. */ get weight() { return this._thinBloomEffect.weight; } set weight(value) { this._thinBloomEffect.weight = value; } /** * Specifies the size of the bloom blur kernel, relative to the final output size */ get kernel() { return this._thinBloomEffect.kernel; } set kernel(value) { this._thinBloomEffect.kernel = value; } get bloomScale() { return this._thinBloomEffect.scale; } /** * Creates a new instance of @see BloomEffect * @param sceneOrEngine The scene or engine the effect belongs to. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom. * @param bloomWeight The strength of bloom. * @param bloomKernel The size of the kernel to be used when applying the blur. * @param pipelineTextureType The type of texture to be used when performing the post processing. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false) */ constructor(sceneOrEngine, bloomScale, bloomWeight, bloomKernel, pipelineTextureType = 0, blockCompilation = false) { const engine = sceneOrEngine._renderForCamera ? sceneOrEngine.getEngine() : sceneOrEngine; super(engine, "bloom", () => { return this._effects; }, true); this._effects = []; this._thinBloomEffect = new ThinBloomEffect("bloom", engine, bloomScale, blockCompilation); this._downscale = new ExtractHighlightsPostProcess("highlights", { size: 1, samplingMode: Texture.BILINEAR_SAMPLINGMODE, engine, textureType: pipelineTextureType, blockCompilation, effectWrapper: this._thinBloomEffect._downscale }); this._blurX = new BlurPostProcess("horizontal blur", this._thinBloomEffect._blurX.direction, this._thinBloomEffect._blurX.kernel, { size: bloomScale, samplingMode: Texture.BILINEAR_SAMPLINGMODE, engine, textureType: pipelineTextureType, blockCompilation, effectWrapper: this._thinBloomEffect._blurX }); this._blurX.alwaysForcePOT = true; this._blurX.autoClear = false; this._blurY = new BlurPostProcess("vertical blur", this._thinBloomEffect._blurY.direction, this._thinBloomEffect._blurY.kernel, { size: bloomScale, samplingMode: Texture.BILINEAR_SAMPLINGMODE, engine, textureType: pipelineTextureType, blockCompilation, effectWrapper: this._thinBloomEffect._blurY }); this._blurY.alwaysForcePOT = true; this._blurY.autoClear = false; this.kernel = bloomKernel; this._effects = [this._downscale, this._blurX, this._blurY]; this._merge = new BloomMergePostProcess("bloomMerge", this._downscale, this._blurY, bloomWeight, { size: bloomScale, samplingMode: Texture.BILINEAR_SAMPLINGMODE, engine, textureType: pipelineTextureType, blockCompilation, effectWrapper: this._thinBloomEffect._merge }); this._merge.autoClear = false; this._effects.push(this._merge); } /** * Disposes each of the internal effects for a given camera. * @param camera The camera to dispose the effect on. */ disposeEffects(camera) { for (let effectIndex = 0; effectIndex < this._effects.length; effectIndex++) { this._effects[effectIndex].dispose(camera); } } /** * @internal Internal */ _updateEffects() { for (let effectIndex = 0; effectIndex < this._effects.length; effectIndex++) { this._effects[effectIndex].updateEffect(); } } /** * Internal * @returns if all the contained post processes are ready. * @internal */ _isReady() { return this._thinBloomEffect.isReady(); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/PostProcesses/RenderPipeline/Pipelines/defaultRenderingPipeline.js init_tslib_es6(); init_decorators(); init_decorators_serialization(); init_observable(); init_logger(); init_texture(); init_typeStore(); init_engineStore(); init_tools(); var DefaultRenderingPipeline = class _DefaultRenderingPipeline extends PostProcessRenderPipeline { static { __name(this, "DefaultRenderingPipeline"); } /** * Enable or disable automatic building of the pipeline when effects are enabled and disabled. * If false, you will have to manually call prepare() to update the pipeline. */ get automaticBuild() { return this._buildAllowed; } set automaticBuild(value) { this._buildAllowed = value; } /** * Gets active scene */ get scene() { return this._scene; } /** * Enable or disable the sharpen process from the pipeline */ set sharpenEnabled(enabled) { if (this._sharpenEnabled === enabled) { return; } this._sharpenEnabled = enabled; this._buildPipeline(); } get sharpenEnabled() { return this._sharpenEnabled; } /** * Specifies the size of the bloom blur kernel, relative to the final output size */ get bloomKernel() { return this._bloomKernel; } set bloomKernel(value) { this._bloomKernel = value; this.bloom.kernel = value / this._hardwareScaleLevel; } /** * The strength of the bloom. */ set bloomWeight(value) { if (this._bloomWeight === value) { return; } this.bloom.weight = value; this._bloomWeight = value; } get bloomWeight() { return this._bloomWeight; } /** * The luminance threshold to find bright areas of the image to bloom. */ set bloomThreshold(value) { if (this._bloomThreshold === value) { return; } this.bloom.threshold = value; this._bloomThreshold = value; } get bloomThreshold() { return this._bloomThreshold; } /** * The scale of the bloom, lower value will provide better performance. */ set bloomScale(value) { if (this._bloomScale === value) { return; } this._bloomScale = value; this._rebuildBloom(); this._buildPipeline(); } get bloomScale() { return this._bloomScale; } /** * Enable or disable the bloom from the pipeline */ set bloomEnabled(enabled) { if (this._bloomEnabled === enabled) { return; } this._bloomEnabled = enabled; this._buildPipeline(); } get bloomEnabled() { return this._bloomEnabled; } _rebuildBloom() { const oldBloom = this.bloom; this.bloom = new BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel / this._hardwareScaleLevel, this._defaultPipelineTextureType, false); this.bloom.threshold = oldBloom.threshold; for (let i = 0; i < this._cameras.length; i++) { oldBloom.disposeEffects(this._cameras[i]); } } /** * If the depth of field is enabled. */ get depthOfFieldEnabled() { return this._depthOfFieldEnabled; } set depthOfFieldEnabled(enabled) { if (this._depthOfFieldEnabled === enabled) { return; } this._depthOfFieldEnabled = enabled; this._buildPipeline(); } /** * Blur level of the depth of field effect. (Higher blur will effect performance) */ get depthOfFieldBlurLevel() { return this._depthOfFieldBlurLevel; } set depthOfFieldBlurLevel(value) { if (this._depthOfFieldBlurLevel === value) { return; } this._depthOfFieldBlurLevel = value; const oldDof = this.depthOfField; this.depthOfField = new DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false); this.depthOfField.focalLength = oldDof.focalLength; this.depthOfField.focusDistance = oldDof.focusDistance; this.depthOfField.fStop = oldDof.fStop; this.depthOfField.lensSize = oldDof.lensSize; for (let i = 0; i < this._cameras.length; i++) { oldDof.disposeEffects(this._cameras[i]); } this._buildPipeline(); } /** * If the anti aliasing is enabled. */ set fxaaEnabled(enabled) { if (this._fxaaEnabled === enabled) { return; } this._fxaaEnabled = enabled; this._buildPipeline(); } get fxaaEnabled() { return this._fxaaEnabled; } /** * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1) */ set samples(sampleCount) { if (this._samples === sampleCount) { return; } this._samples = sampleCount; this._buildPipeline(); } get samples() { return this._samples; } /** * If image processing is enabled. */ set imageProcessingEnabled(enabled) { if (this._imageProcessingEnabled === enabled) { return; } this._scene.imageProcessingConfiguration.isEnabled = enabled; } get imageProcessingEnabled() { return this._imageProcessingEnabled; } /** * If glow layer is enabled. (Adds a glow effect to emmissive materials) */ set glowLayerEnabled(enabled) { if (enabled && !this._glowLayer) { this._glowLayer = new GlowLayer("", this._scene); } else if (!enabled && this._glowLayer) { this._glowLayer.dispose(); this._glowLayer = null; } } get glowLayerEnabled() { return this._glowLayer != null; } /** * Gets the glow layer (or null if not defined) */ get glowLayer() { return this._glowLayer; } /** * Enable or disable the chromaticAberration process from the pipeline */ set chromaticAberrationEnabled(enabled) { if (this._chromaticAberrationEnabled === enabled) { return; } this._chromaticAberrationEnabled = enabled; this._buildPipeline(); } get chromaticAberrationEnabled() { return this._chromaticAberrationEnabled; } /** * Enable or disable the grain process from the pipeline */ set grainEnabled(enabled) { if (this._grainEnabled === enabled) { return; } this._grainEnabled = enabled; this._buildPipeline(); } get grainEnabled() { return this._grainEnabled; } /** * Instantiates a DefaultRenderingPipeline. * @param name The rendering pipeline name (default: "") * @param hdr If high dynamic range textures should be used (default: true) * @param scene The scene linked to this pipeline (default: the last created scene) * @param cameras The array of cameras that the rendering pipeline will be attached to (default: scene.cameras) * @param automaticBuild If false, you will have to manually call prepare() to update the pipeline (default: true) */ constructor(name260 = "", hdr = true, scene = EngineStore.LastCreatedScene, cameras, automaticBuild = true) { super(scene.getEngine(), name260); this._camerasToBeAttached = []; this.SharpenPostProcessId = "SharpenPostProcessEffect"; this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect"; this.FxaaPostProcessId = "FxaaPostProcessEffect"; this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect"; this.GrainPostProcessId = "GrainPostProcessEffect"; this._glowLayer = null; this.animations = []; this._imageProcessingConfigurationObserver = null; this._sharpenEnabled = false; this._bloomEnabled = false; this._depthOfFieldEnabled = false; this._depthOfFieldBlurLevel = 0; this._fxaaEnabled = false; this._imageProcessingEnabled = true; this._bloomScale = 0.5; this._chromaticAberrationEnabled = false; this._grainEnabled = false; this._buildAllowed = true; this.onBuildObservable = new Observable(); this._resizeObserver = null; this._hardwareScaleLevel = 1; this._bloomKernel = 64; this._bloomWeight = 0.15; this._bloomThreshold = 0.9; this._samples = 1; this._hasCleared = false; this._prevPostProcess = null; this._prevPrevPostProcess = null; this._depthOfFieldSceneObserver = null; this._activeCameraChangedObserver = null; this._activeCamerasChangedObserver = null; this._cameras = cameras || scene.cameras; this._cameras = this._cameras.slice(); this._camerasToBeAttached = this._cameras.slice(); this._buildAllowed = automaticBuild; this._scene = scene; const caps = this._scene.getEngine().getCaps(); this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender); if (this._hdr) { if (caps.textureHalfFloatRender) { this._defaultPipelineTextureType = 2; } else if (caps.textureFloatRender) { this._defaultPipelineTextureType = 1; } } else { this._defaultPipelineTextureType = 0; } scene.postProcessRenderPipelineManager.addPipeline(this); const engine = this._scene.getEngine(); this.sharpen = new SharpenPostProcess("sharpen", 1, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType, true); this._sharpenEffect = new PostProcessRenderEffect(engine, this.SharpenPostProcessId, () => { return this.sharpen; }, true); this.depthOfField = new DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, true); this._hardwareScaleLevel = engine.getHardwareScalingLevel(); this._resizeObserver = engine.onResizeObservable.add(() => { this._hardwareScaleLevel = engine.getHardwareScalingLevel(); this.bloomKernel = this._bloomKernel; }); this.bloom = new BloomEffect(this._scene, this._bloomScale, this._bloomWeight, this.bloomKernel / this._hardwareScaleLevel, this._defaultPipelineTextureType, true); this.chromaticAberration = new ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType, true); this._chromaticAberrationEffect = new PostProcessRenderEffect(engine, this.ChromaticAberrationPostProcessId, () => { return this.chromaticAberration; }, true); this.grain = new GrainPostProcess("Grain", 1, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType, true); this._grainEffect = new PostProcessRenderEffect(engine, this.GrainPostProcessId, () => { return this.grain; }, true); let avoidReentrancyAtConstructionTime = true; this._imageProcessingConfigurationObserver = this._scene.imageProcessingConfiguration.onUpdateParameters.add(() => { this.bloom._downscale._exposure = this._scene.imageProcessingConfiguration.exposure; if (this.imageProcessingEnabled !== this._scene.imageProcessingConfiguration.isEnabled) { this._imageProcessingEnabled = this._scene.imageProcessingConfiguration.isEnabled; if (avoidReentrancyAtConstructionTime) { Tools.SetImmediate(() => { this._buildPipeline(); }); } else { this._buildPipeline(); } } }); this._buildPipeline(); avoidReentrancyAtConstructionTime = false; } /** * Get the class name * @returns "DefaultRenderingPipeline" */ getClassName() { return "DefaultRenderingPipeline"; } /** * Force the compilation of the entire pipeline. */ prepare() { const previousState = this._buildAllowed; this._buildAllowed = true; this._buildPipeline(); this._buildAllowed = previousState; } _setAutoClearAndTextureSharing(postProcess, skipTextureSharing = false) { if (this._hasCleared) { postProcess.autoClear = false; } else { postProcess.autoClear = true; this._scene.autoClear = false; this._hasCleared = true; } if (!skipTextureSharing) { if (this._prevPrevPostProcess) { postProcess.shareOutputWith(this._prevPrevPostProcess); } else { postProcess.useOwnOutput(); } if (this._prevPostProcess) { this._prevPrevPostProcess = this._prevPostProcess; } this._prevPostProcess = postProcess; } } _buildPipeline() { if (!this._buildAllowed) { return; } this._scene.autoClear = true; const engine = this._scene.getEngine(); this._disposePostProcesses(); if (this._cameras !== null) { this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); this._cameras = this._camerasToBeAttached.slice(); } this._reset(); this._prevPostProcess = null; this._prevPrevPostProcess = null; this._hasCleared = false; if (this.depthOfFieldEnabled) { if (this._cameras.length > 1) { for (const camera of this._cameras) { const depthRenderer = this._scene.enableDepthRenderer(camera); depthRenderer.useOnlyInActiveCamera = true; } this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add((scene) => { if (this._cameras.indexOf(scene.activeCamera) > -1) { this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap(); } }); } else { this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver); const depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]); this.depthOfField.depthTexture = depthRenderer.getDepthMap(); } if (!this.depthOfField._isReady()) { this.depthOfField._updateEffects(); } this.addEffect(this.depthOfField); this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true); } else { this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver); } if (this.bloomEnabled) { if (!this.bloom._isReady()) { this.bloom._updateEffects(); } this.addEffect(this.bloom); this._setAutoClearAndTextureSharing(this.bloom._effects[0], true); } if (this._imageProcessingEnabled) { this.imageProcessing = new ImageProcessingPostProcess("imageProcessing", 1, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType, this.scene.imageProcessingConfiguration); if (this._hdr) { this.addEffect(new PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, () => { return this.imageProcessing; }, true)); this._setAutoClearAndTextureSharing(this.imageProcessing); } else { this._scene.imageProcessingConfiguration.applyByPostProcess = false; } if (!this._cameras || this._cameras.length === 0) { this._scene.imageProcessingConfiguration.applyByPostProcess = false; } if (!this.imageProcessing.getEffect()) { this.imageProcessing._updateParameters(); } } if (this.sharpenEnabled) { if (!this.sharpen.isReady()) { this.sharpen.updateEffect(); } this.addEffect(this._sharpenEffect); this._setAutoClearAndTextureSharing(this.sharpen); } if (this.grainEnabled) { if (!this.grain.isReady()) { this.grain.updateEffect(); } this.addEffect(this._grainEffect); this._setAutoClearAndTextureSharing(this.grain); } if (this.chromaticAberrationEnabled) { if (!this.chromaticAberration.isReady()) { this.chromaticAberration.updateEffect(); } this.addEffect(this._chromaticAberrationEffect); this._setAutoClearAndTextureSharing(this.chromaticAberration); } if (this.fxaaEnabled) { this.fxaa = new FxaaPostProcess("fxaa", 1, null, Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType); this.addEffect(new PostProcessRenderEffect(engine, this.FxaaPostProcessId, () => { return this.fxaa; }, true)); this._setAutoClearAndTextureSharing(this.fxaa, true); } if (this._cameras !== null) { this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras); } if (this._scene.activeCameras && this._scene.activeCameras.length > 1 || this._scene.activeCamera && this._cameras.indexOf(this._scene.activeCamera) === -1) { this._scene.autoClear = true; } if (!this._activeCameraChangedObserver) { this._activeCameraChangedObserver = this._scene.onActiveCameraChanged.add(() => { if (this._scene.activeCamera && this._cameras.indexOf(this._scene.activeCamera) === -1) { this._scene.autoClear = true; } }); } if (!this._activeCamerasChangedObserver) { this._activeCamerasChangedObserver = this._scene.onActiveCamerasChanged.add(() => { if (this._scene.activeCameras && this._scene.activeCameras.length > 1) { this._scene.autoClear = true; } }); } this._adaptPostProcessesToViewPort(); if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) { Logger.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0"); } this.onBuildObservable.notifyObservers(this); } _disposePostProcesses(disposeNonRecreated = false) { for (let i = 0; i < this._cameras.length; i++) { const camera = this._cameras[i]; if (this.imageProcessing) { this.imageProcessing.dispose(camera); } if (this.fxaa) { this.fxaa.dispose(camera); } if (disposeNonRecreated) { if (this.sharpen) { this.sharpen.dispose(camera); } if (this.depthOfField) { this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver); this.depthOfField.disposeEffects(camera); } if (this.bloom) { this.bloom.disposeEffects(camera); } if (this.chromaticAberration) { this.chromaticAberration.dispose(camera); } if (this.grain) { this.grain.dispose(camera); } if (this._glowLayer) { this._glowLayer.dispose(); } } } this.imageProcessing = null; this.fxaa = null; if (disposeNonRecreated) { this.sharpen = null; this._sharpenEffect = null; this.depthOfField = null; this.bloom = null; this.chromaticAberration = null; this._chromaticAberrationEffect = null; this.grain = null; this._grainEffect = null; this._glowLayer = null; } } /** * Adds a camera to the pipeline * @param camera the camera to be added */ addCamera(camera) { this._camerasToBeAttached.push(camera); this._buildPipeline(); } /** * Removes a camera from the pipeline * @param camera the camera to remove */ removeCamera(camera) { const index = this._camerasToBeAttached.indexOf(camera); this._camerasToBeAttached.splice(index, 1); this._buildPipeline(); } /** * Dispose of the pipeline and stop all post processes */ dispose() { this._buildAllowed = false; this.onBuildObservable.clear(); this._disposePostProcesses(true); this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras); this._scene._postProcessRenderPipelineManager.removePipeline(this.name); this._scene.autoClear = true; if (this._resizeObserver) { this._scene.getEngine().onResizeObservable.remove(this._resizeObserver); this._resizeObserver = null; } this._scene.onActiveCameraChanged.remove(this._activeCameraChangedObserver); this._scene.onActiveCamerasChanged.remove(this._activeCamerasChangedObserver); this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver); super.dispose(); } /** * Serialize the rendering pipeline (Used when exporting) * @returns the serialized object */ serialize() { const serializationObject = SerializationHelper.Serialize(this); serializationObject.customType = "DefaultRenderingPipeline"; return serializationObject; } /** * Parse the serialized pipeline * @param source Source pipeline. * @param scene The scene to load the pipeline to. * @param rootUrl The URL of the serialized pipeline. * @returns An instantiated pipeline from the serialized object. */ static Parse(source, scene, rootUrl) { return SerializationHelper.Parse(() => new _DefaultRenderingPipeline(source._name, source._name._hdr, scene), source, scene, rootUrl); } }; __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "bloomKernel", null); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "_hdr", void 0); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "bloomWeight", null); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "bloomThreshold", null); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "bloomScale", null); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "bloomEnabled", null); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "samples", null); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null); __decorate([ serialize() ], DefaultRenderingPipeline.prototype, "grainEnabled", null); RegisterClass("BABYLON.DefaultRenderingPipeline", DefaultRenderingPipeline); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/rendering/default-pipeline.js init_math_color(); init_math_vector(); init_texture(); var defaultRenderingPipeline = null; var defaultPipelineCameraConfigurations = /* @__PURE__ */ new Map(); function getDefaultRenderingPipeline() { return defaultRenderingPipeline; } __name(getDefaultRenderingPipeline, "getDefaultRenderingPipeline"); function setDefaultRenderingPipelineRef(pipeline) { defaultRenderingPipeline = pipeline; } __name(setDefaultRenderingPipelineRef, "setDefaultRenderingPipelineRef"); function disposeDefaultRenderingPipeline() { if (defaultRenderingPipeline) { defaultRenderingPipeline.dispose(); defaultRenderingPipeline = null; } } __name(disposeDefaultRenderingPipeline, "disposeDefaultRenderingPipeline"); function createDefaultRenderingPipeline(scene, camera) { defaultRenderingPipeline = new DefaultRenderingPipeline("DefaultRenderingPipeline", true, scene, [camera]); defaultRenderingPipeline.samples = 4; defaultRenderingPipeline.depthOfField.lensSize = 512; defaultRenderingPipeline.depthOfField.fStop = 0.25; defaultRenderingPipeline.depthOfField.focusDistance = 55e3; return defaultRenderingPipeline; } __name(createDefaultRenderingPipeline, "createDefaultRenderingPipeline"); function serializeDefaultRenderingPipeline() { if (!defaultRenderingPipeline) { return null; } return { samples: defaultRenderingPipeline.samples, fxaaEnabled: defaultRenderingPipeline.fxaaEnabled, imageProcessingEnabled: defaultRenderingPipeline.imageProcessingEnabled, exposure: defaultRenderingPipeline.imageProcessing?.exposure, contrast: defaultRenderingPipeline.imageProcessing?.contrast, fromLinearSpace: defaultRenderingPipeline.imageProcessing?.fromLinearSpace, toneMappingEnabled: defaultRenderingPipeline.imageProcessing?.toneMappingEnabled, toneMappingType: defaultRenderingPipeline.imageProcessing?.toneMappingType, ditheringEnabled: defaultRenderingPipeline.imageProcessing?.ditheringEnabled, ditheringIntensity: defaultRenderingPipeline.imageProcessing?.ditheringIntensity, bloomEnabled: defaultRenderingPipeline.bloomEnabled, bloomThreshold: defaultRenderingPipeline.bloomThreshold, bloomWeight: defaultRenderingPipeline.bloomWeight, bloomScale: defaultRenderingPipeline.bloomScale, bloomKernel: defaultRenderingPipeline.bloomKernel, sharpenEnabled: defaultRenderingPipeline.sharpenEnabled, sharpenEdgeAmount: defaultRenderingPipeline.sharpen.edgeAmount, sharpenColorAmount: defaultRenderingPipeline.sharpen.colorAmount, grainEnabled: defaultRenderingPipeline.grainEnabled, grainIntensity: defaultRenderingPipeline.grain.intensity, grainAnimated: defaultRenderingPipeline.grain.animated, depthOfFieldEnabled: defaultRenderingPipeline.depthOfFieldEnabled, depthOfFieldBlurLevel: defaultRenderingPipeline.depthOfFieldBlurLevel, lensSize: defaultRenderingPipeline.depthOfField.lensSize, fStop: defaultRenderingPipeline.depthOfField.fStop, focusDistance: defaultRenderingPipeline.depthOfField.focusDistance, focalLength: defaultRenderingPipeline.depthOfField.focalLength, // Since v5.0.0-alpha.9 vignetteEnabled: defaultRenderingPipeline.imageProcessing?.vignetteEnabled, vignetteColor: defaultRenderingPipeline.imageProcessing?.vignetteColor.asArray(), vignetteWeight: defaultRenderingPipeline.imageProcessing?.vignetteWeight, chromaticAberrationEnabled: defaultRenderingPipeline.chromaticAberrationEnabled, aberrationAmount: defaultRenderingPipeline.chromaticAberration.aberrationAmount, radialIntensity: defaultRenderingPipeline.chromaticAberration.radialIntensity, direction: defaultRenderingPipeline.chromaticAberration.direction.asArray(), centerPosition: defaultRenderingPipeline.chromaticAberration.centerPosition.asArray(), glowLayerEnabled: defaultRenderingPipeline.glowLayerEnabled, glowLayerIntensity: defaultRenderingPipeline.glowLayer?.intensity, glowLayerBlurKernelSize: defaultRenderingPipeline.glowLayer?.blurKernelSize, // Since v5.0.0-alpha.10 colorGradingEnabled: defaultRenderingPipeline.imageProcessing.colorGradingEnabled, colorGradingTexture: defaultRenderingPipeline.imageProcessing.colorGradingTexture?.serialize(), colorGradingWithGreenDepth: defaultRenderingPipeline.imageProcessing.imageProcessingConfiguration.colorGradingWithGreenDepth, colorCurvesEnabled: defaultRenderingPipeline.imageProcessing.colorCurvesEnabled, globalHue: defaultRenderingPipeline.imageProcessing.colorCurves?.globalHue, globalDensity: defaultRenderingPipeline.imageProcessing.colorCurves?.globalDensity, globalExposure: defaultRenderingPipeline.imageProcessing.colorCurves?.globalExposure, globalSaturation: defaultRenderingPipeline.imageProcessing.colorCurves?.globalSaturation, highlightsHue: defaultRenderingPipeline.imageProcessing.colorCurves?.highlightsHue, highlightsDensity: defaultRenderingPipeline.imageProcessing.colorCurves?.highlightsDensity, highlightsExposure: defaultRenderingPipeline.imageProcessing.colorCurves?.highlightsExposure, highlightsSaturation: defaultRenderingPipeline.imageProcessing.colorCurves?.highlightsSaturation, midtonesHue: defaultRenderingPipeline.imageProcessing.colorCurves?.midtonesHue, midtonesDensity: defaultRenderingPipeline.imageProcessing.colorCurves?.midtonesDensity, midtonesExposure: defaultRenderingPipeline.imageProcessing.colorCurves?.midtonesExposure, midtonesSaturation: defaultRenderingPipeline.imageProcessing.colorCurves?.midtonesSaturation, shadowsHue: defaultRenderingPipeline.imageProcessing.colorCurves?.shadowsHue, shadowsDensity: defaultRenderingPipeline.imageProcessing.colorCurves?.shadowsDensity, shadowsExposure: defaultRenderingPipeline.imageProcessing.colorCurves?.shadowsExposure, shadowsSaturation: defaultRenderingPipeline.imageProcessing.colorCurves?.shadowsSaturation }; } __name(serializeDefaultRenderingPipeline, "serializeDefaultRenderingPipeline"); function parseDefaultRenderingPipeline(scene, camera, data, rootUrl) { if (defaultRenderingPipeline) { return defaultRenderingPipeline; } const pipeline = createDefaultRenderingPipeline(scene, camera); pipeline.samples = data.samples; pipeline.fxaaEnabled = data.fxaaEnabled; pipeline.imageProcessingEnabled = data.imageProcessingEnabled; if (pipeline.imageProcessing) { pipeline.imageProcessing.exposure = data.exposure; pipeline.imageProcessing.contrast = data.contrast; pipeline.imageProcessing.fromLinearSpace = data.fromLinearSpace; pipeline.imageProcessing.toneMappingEnabled = data.toneMappingEnabled; pipeline.imageProcessing.toneMappingType = data.toneMappingType; pipeline.imageProcessing.ditheringEnabled = data.ditheringEnabled; pipeline.imageProcessing.ditheringIntensity = data.ditheringIntensity; pipeline.imageProcessing.vignetteEnabled = data.vignetteEnabled ?? false; pipeline.imageProcessing.vignetteColor = Color4.FromArray(data.vignetteColor ?? [0, 0, 0]); pipeline.imageProcessing.vignetteWeight = data.vignetteWeight ?? 0.3; pipeline.imageProcessing.colorGradingEnabled = data.colorGradingEnabled ?? false; pipeline.imageProcessing.imageProcessingConfiguration.colorGradingWithGreenDepth = data.colorGradingWithGreenDepth ?? true; if (data.colorGradingTexture) { let texture = null; if (data.colorGradingTexture.customType === "BABYLON.ColorGradingTexture") { const absoluteUrl = rootUrl + data.colorGradingTexture.name; texture = new ColorGradingTexture(absoluteUrl, scene); texture.level = data.colorGradingTexture.level; } else { const parsedTexture = Texture.Parse(data.colorGradingTexture, scene, rootUrl); if (isTexture(parsedTexture)) { texture = parsedTexture; } } pipeline.imageProcessing.colorGradingTexture = texture; } pipeline.imageProcessing.colorCurvesEnabled = data.colorCurvesEnabled ?? false; if (pipeline.imageProcessing.colorCurves) { pipeline.imageProcessing.colorCurves.globalHue = data.globalHue ?? 30; pipeline.imageProcessing.colorCurves.globalDensity = data.globalDensity ?? 0; pipeline.imageProcessing.colorCurves.globalExposure = data.globalExposure ?? 0; pipeline.imageProcessing.colorCurves.globalSaturation = data.globalSaturation ?? 0; pipeline.imageProcessing.colorCurves.highlightsHue = data.highlightsHue ?? 30; pipeline.imageProcessing.colorCurves.highlightsDensity = data.highlightsDensity ?? 0; pipeline.imageProcessing.colorCurves.highlightsExposure = data.highlightsExposure ?? 0; pipeline.imageProcessing.colorCurves.highlightsSaturation = data.highlightsSaturation ?? 0; pipeline.imageProcessing.colorCurves.midtonesHue = data.midtonesHue ?? 30; pipeline.imageProcessing.colorCurves.midtonesDensity = data.midtonesDensity ?? 0; pipeline.imageProcessing.colorCurves.midtonesExposure = data.midtonesExposure ?? 0; pipeline.imageProcessing.colorCurves.midtonesSaturation = data.midtonesSaturation ?? 0; pipeline.imageProcessing.colorCurves.shadowsHue = data.shadowsHue ?? 30; pipeline.imageProcessing.colorCurves.shadowsDensity = data.shadowsDensity ?? 0; pipeline.imageProcessing.colorCurves.shadowsExposure = data.shadowsExposure ?? 0; pipeline.imageProcessing.colorCurves.shadowsSaturation = data.shadowsSaturation ?? 0; } } pipeline.bloomEnabled = data.bloomEnabled; pipeline.bloomThreshold = data.bloomThreshold; pipeline.bloomWeight = data.bloomWeight; pipeline.bloomScale = data.bloomScale; pipeline.bloomKernel = data.bloomKernel; pipeline.sharpenEnabled = data.sharpenEnabled; pipeline.sharpen.edgeAmount = data.sharpenEdgeAmount; pipeline.sharpen.colorAmount = data.sharpenColorAmount; pipeline.grainEnabled = data.grainEnabled; pipeline.grain.intensity = data.grainIntensity; pipeline.grain.animated = data.grainAnimated; pipeline.depthOfFieldEnabled = data.depthOfFieldEnabled; pipeline.depthOfFieldBlurLevel = data.depthOfFieldBlurLevel; pipeline.depthOfField.lensSize = data.lensSize; pipeline.depthOfField.fStop = data.fStop; pipeline.depthOfField.focusDistance = data.focusDistance; pipeline.depthOfField.focalLength = data.focalLength; pipeline.chromaticAberrationEnabled = data.chromaticAberrationEnabled ?? false; pipeline.chromaticAberration.aberrationAmount = data.aberrationAmount ?? 10; pipeline.chromaticAberration.radialIntensity = data.radialIntensity ?? 1; pipeline.chromaticAberration.direction = Vector2.FromArray(data.direction ?? [0, 0]); pipeline.chromaticAberration.centerPosition = Vector2.FromArray(data.centerPosition ?? [0, 0]); pipeline.glowLayerEnabled = data.glowLayerEnabled ?? false; if (pipeline.glowLayer) { pipeline.glowLayer.intensity = data.glowLayerIntensity ?? 1; pipeline.glowLayer.blurKernelSize = data.glowLayerBlurKernelSize ?? 32; } return pipeline; } __name(parseDefaultRenderingPipeline, "parseDefaultRenderingPipeline"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/rendering/tools.js function saveRenderingConfigurationForCamera(camera) { ssaoRenderingPipelineCameraConfigurations.set(camera, serializeSSAO2RenderingPipeline()); vlsPostProcessCameraConfigurations.set(camera, serializeVLSPostProcess()); ssrRenderingPipelineCameraConfigurations.set(camera, serializeSSRRenderingPipeline()); motionBlurPostProcessCameraConfigurations.set(camera, serializeMotionBlurPostProcess()); defaultPipelineCameraConfigurations.set(camera, serializeDefaultRenderingPipeline()); } __name(saveRenderingConfigurationForCamera, "saveRenderingConfigurationForCamera"); function applyRenderingConfigurationForCamera(camera, rootUrl) { disposeSSAO2RenderingPipeline(); disposeVLSPostProcess(camera.getScene()); disposeSSRRenderingPipeline(); disposeMotionBlurPostProcess(); disposeDefaultRenderingPipeline(); const ssao2RenderingPipeline = ssaoRenderingPipelineCameraConfigurations.get(camera); if (ssao2RenderingPipeline) { parseSSAO2RenderingPipeline(camera.getScene(), camera, ssao2RenderingPipeline); } const vlsPostProcess2 = vlsPostProcessCameraConfigurations.get(camera); if (vlsPostProcess2) { parseVLSPostProcess(camera.getScene(), vlsPostProcess2); } const ssrRenderingPipeline2 = ssrRenderingPipelineCameraConfigurations.get(camera); if (ssrRenderingPipeline2) { parseSSRRenderingPipeline(camera.getScene(), camera, ssrRenderingPipeline2); } const motionBlurPostProcess2 = motionBlurPostProcessCameraConfigurations.get(camera); if (motionBlurPostProcess2) { parseMotionBlurPostProcess(camera.getScene(), camera, motionBlurPostProcess2); } const defaultRenderingPipeline2 = defaultPipelineCameraConfigurations.get(camera); if (defaultRenderingPipeline2) { parseDefaultRenderingPipeline(camera.getScene(), camera, defaultRenderingPipeline2, rootUrl); } } __name(applyRenderingConfigurationForCamera, "applyRenderingConfigurationForCamera"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Physics/v2/IPhysicsEnginePlugin.js var PhysicsConstraintAxisLimitMode; (function(PhysicsConstraintAxisLimitMode2) { PhysicsConstraintAxisLimitMode2[PhysicsConstraintAxisLimitMode2["FREE"] = 0] = "FREE"; PhysicsConstraintAxisLimitMode2[PhysicsConstraintAxisLimitMode2["LIMITED"] = 1] = "LIMITED"; PhysicsConstraintAxisLimitMode2[PhysicsConstraintAxisLimitMode2["LOCKED"] = 2] = "LOCKED"; })(PhysicsConstraintAxisLimitMode || (PhysicsConstraintAxisLimitMode = {})); var PhysicsConstraintAxis; (function(PhysicsConstraintAxis2) { PhysicsConstraintAxis2[PhysicsConstraintAxis2["LINEAR_X"] = 0] = "LINEAR_X"; PhysicsConstraintAxis2[PhysicsConstraintAxis2["LINEAR_Y"] = 1] = "LINEAR_Y"; PhysicsConstraintAxis2[PhysicsConstraintAxis2["LINEAR_Z"] = 2] = "LINEAR_Z"; PhysicsConstraintAxis2[PhysicsConstraintAxis2["ANGULAR_X"] = 3] = "ANGULAR_X"; PhysicsConstraintAxis2[PhysicsConstraintAxis2["ANGULAR_Y"] = 4] = "ANGULAR_Y"; PhysicsConstraintAxis2[PhysicsConstraintAxis2["ANGULAR_Z"] = 5] = "ANGULAR_Z"; PhysicsConstraintAxis2[PhysicsConstraintAxis2["LINEAR_DISTANCE"] = 6] = "LINEAR_DISTANCE"; })(PhysicsConstraintAxis || (PhysicsConstraintAxis = {})); var PhysicsConstraintType; (function(PhysicsConstraintType2) { PhysicsConstraintType2[PhysicsConstraintType2["BALL_AND_SOCKET"] = 1] = "BALL_AND_SOCKET"; PhysicsConstraintType2[PhysicsConstraintType2["DISTANCE"] = 2] = "DISTANCE"; PhysicsConstraintType2[PhysicsConstraintType2["HINGE"] = 3] = "HINGE"; PhysicsConstraintType2[PhysicsConstraintType2["SLIDER"] = 4] = "SLIDER"; PhysicsConstraintType2[PhysicsConstraintType2["LOCK"] = 5] = "LOCK"; PhysicsConstraintType2[PhysicsConstraintType2["PRISMATIC"] = 6] = "PRISMATIC"; PhysicsConstraintType2[PhysicsConstraintType2["SIX_DOF"] = 7] = "SIX_DOF"; })(PhysicsConstraintType || (PhysicsConstraintType = {})); var PhysicsShapeType; (function(PhysicsShapeType2) { PhysicsShapeType2[PhysicsShapeType2["SPHERE"] = 0] = "SPHERE"; PhysicsShapeType2[PhysicsShapeType2["CAPSULE"] = 1] = "CAPSULE"; PhysicsShapeType2[PhysicsShapeType2["CYLINDER"] = 2] = "CYLINDER"; PhysicsShapeType2[PhysicsShapeType2["BOX"] = 3] = "BOX"; PhysicsShapeType2[PhysicsShapeType2["CONVEX_HULL"] = 4] = "CONVEX_HULL"; PhysicsShapeType2[PhysicsShapeType2["CONTAINER"] = 5] = "CONTAINER"; PhysicsShapeType2[PhysicsShapeType2["MESH"] = 6] = "MESH"; PhysicsShapeType2[PhysicsShapeType2["HEIGHTFIELD"] = 7] = "HEIGHTFIELD"; })(PhysicsShapeType || (PhysicsShapeType = {})); var PhysicsConstraintMotorType; (function(PhysicsConstraintMotorType2) { PhysicsConstraintMotorType2[PhysicsConstraintMotorType2["NONE"] = 0] = "NONE"; PhysicsConstraintMotorType2[PhysicsConstraintMotorType2["VELOCITY"] = 1] = "VELOCITY"; PhysicsConstraintMotorType2[PhysicsConstraintMotorType2["POSITION"] = 2] = "POSITION"; })(PhysicsConstraintMotorType || (PhysicsConstraintMotorType = {})); var PhysicsEventType; (function(PhysicsEventType2) { PhysicsEventType2["COLLISION_STARTED"] = "COLLISION_STARTED"; PhysicsEventType2["COLLISION_CONTINUED"] = "COLLISION_CONTINUED"; PhysicsEventType2["COLLISION_FINISHED"] = "COLLISION_FINISHED"; PhysicsEventType2["TRIGGER_ENTERED"] = "TRIGGER_ENTERED"; PhysicsEventType2["TRIGGER_EXITED"] = "TRIGGER_EXITED"; })(PhysicsEventType || (PhysicsEventType = {})); var PhysicsMotionType; (function(PhysicsMotionType2) { PhysicsMotionType2[PhysicsMotionType2["STATIC"] = 0] = "STATIC"; PhysicsMotionType2[PhysicsMotionType2["ANIMATED"] = 1] = "ANIMATED"; PhysicsMotionType2[PhysicsMotionType2["DYNAMIC"] = 2] = "DYNAMIC"; })(PhysicsMotionType || (PhysicsMotionType = {})); var PhysicsPrestepType; (function(PhysicsPrestepType2) { PhysicsPrestepType2[PhysicsPrestepType2["DISABLED"] = 0] = "DISABLED"; PhysicsPrestepType2[PhysicsPrestepType2["TELEPORT"] = 1] = "TELEPORT"; PhysicsPrestepType2[PhysicsPrestepType2["ACTION"] = 2] = "ACTION"; })(PhysicsPrestepType || (PhysicsPrestepType = {})); var PhysicsActivationControl; (function(PhysicsActivationControl2) { PhysicsActivationControl2[PhysicsActivationControl2["SIMULATION_CONTROLLED"] = 0] = "SIMULATION_CONTROLLED"; PhysicsActivationControl2[PhysicsActivationControl2["ALWAYS_ACTIVE"] = 1] = "ALWAYS_ACTIVE"; PhysicsActivationControl2[PhysicsActivationControl2["ALWAYS_INACTIVE"] = 2] = "ALWAYS_INACTIVE"; })(PhysicsActivationControl || (PhysicsActivationControl = {})); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Physics/v2/physicsBody.js init_math_vector(); var PhysicsBody = class _PhysicsBody { static { __name(this, "PhysicsBody"); } /** * Disable pre-step that consists in updating Physics Body from Transform Node Translation/Orientation. * True by default for maximum performance. */ get disablePreStep() { return this._prestepType == PhysicsPrestepType.DISABLED; } set disablePreStep(value) { this._prestepType = value ? PhysicsPrestepType.DISABLED : PhysicsPrestepType.TELEPORT; } /** * Constructs a new physics body for the given node. * @param transformNode - The Transform Node to construct the physics body for. For better performance, it is advised that this node does not have a parent. * @param motionType - The motion type of the physics body. The options are: * - PhysicsMotionType.STATIC - Static bodies are not moving and unaffected by forces or collisions. They are good for level boundaries or terrain. * - PhysicsMotionType.DYNAMIC - Dynamic bodies are fully simulated. They can move and collide with other objects. * - PhysicsMotionType.ANIMATED - They behave like dynamic bodies, but they won't be affected by other bodies, but still push other bodies out of the way. * @param startsAsleep - Whether the physics body should start in a sleeping state (not a guarantee). Defaults to false. * @param scene - The scene containing the physics engine. * * This code is useful for creating a physics body for a given Transform Node in a scene. * It checks the version of the physics engine and the physics plugin, and initializes the body accordingly. * It also sets the node's rotation quaternion if it is not already set. Finally, it adds the body to the physics engine. */ constructor(transformNode, motionType, startsAsleep, scene) { this._pluginData = void 0; this._pluginDataInstances = []; this._collisionCBEnabled = false; this._collisionEndedCBEnabled = false; this.disableSync = false; this._isDisposed = false; this._shape = null; this._prestepType = PhysicsPrestepType.DISABLED; if (!scene) { return; } const physicsEngine = scene.getPhysicsEngine(); if (!physicsEngine) { throw new Error("No Physics Engine available."); } this._physicsEngine = physicsEngine; if (physicsEngine.getPluginVersion() != 2) { throw new Error("Plugin version is incorrect. Expected version 2."); } const physicsPlugin = physicsEngine.getPhysicsPlugin(); if (!physicsPlugin) { throw new Error("No Physics Plugin available."); } this._physicsPlugin = physicsPlugin; if (!transformNode.rotationQuaternion) { transformNode.rotationQuaternion = Quaternion.FromEulerAngles(transformNode.rotation.x, transformNode.rotation.y, transformNode.rotation.z); } this.startAsleep = startsAsleep; this.disableSync = motionType == 0; const m = transformNode; if (m.hasThinInstances) { this._physicsPlugin.initBodyInstances(this, motionType, m); } else { if (transformNode.parent) { transformNode.computeWorldMatrix(true); } this._physicsPlugin.initBody(this, motionType, transformNode.absolutePosition, transformNode.absoluteRotationQuaternion); } this.transformNode = transformNode; transformNode.physicsBody = this; physicsEngine.addBody(this); this._nodeDisposeObserver = transformNode.onDisposeObservable.add(() => { this.dispose(); }); } /** * Returns the string "PhysicsBody". * @returns "PhysicsBody" */ getClassName() { return "PhysicsBody"; } /** * Clone the PhysicsBody to a new body and assign it to the transformNode parameter * @param transformNode transformNode that will be used for the cloned PhysicsBody * @returns the newly cloned PhysicsBody */ clone(transformNode) { const clonedBody = new _PhysicsBody(transformNode, this.getMotionType(), this.startAsleep, this.transformNode.getScene()); clonedBody.shape = this.shape; clonedBody.setMassProperties(this.getMassProperties()); clonedBody.setLinearDamping(this.getLinearDamping()); clonedBody.setAngularDamping(this.getAngularDamping()); return clonedBody; } /** * If a physics body is connected to an instanced node, update the number physic instances to match the number of node instances. */ updateBodyInstances() { const m = this.transformNode; if (m.hasThinInstances) { this._physicsPlugin.updateBodyInstances(this, m); } } /** * This returns the number of internal instances of the physics body */ get numInstances() { return this._pluginDataInstances.length; } /** * Get the motion type of the physics body. Can be STATIC, DYNAMIC, or ANIMATED. */ get motionType() { return this._physicsPlugin.getMotionType(this); } /** * Sets the shape of the physics body. * @param shape - The shape of the physics body. * * This method is useful for setting the shape of the physics body, which is necessary for the physics engine to accurately simulate the body's behavior. * The shape is used to calculate the body's mass, inertia, and other properties. */ set shape(shape) { this._shape = shape; if (shape) { this._physicsPlugin.setShape(this, shape); } } /** * Retrieves the physics shape associated with this object. * * @returns The physics shape associated with this object, or `undefined` if no * shape is associated. * * This method is useful for retrieving the physics shape associated with this object, * which can be used to apply physical forces to the object or to detect collisions. */ get shape() { return this._shape; } /** * Returns the bounding box of the physics body. * @returns The bounding box of the physics body. */ getBoundingBox() { return this._physicsPlugin.getBodyBoundingBox(this); } /** * Sets the event mask for the physics engine. * * @param eventMask - A bitmask that determines which events will be sent to the physics engine. * @param instanceIndex - If this body is instanced, the index of the instance to set the event mask for. * * This method is useful for setting the event mask for the physics engine, which determines which events * will be sent to the physics engine. This allows the user to control which events the physics engine will respond to. */ setEventMask(eventMask, instanceIndex) { this._physicsPlugin.setEventMask(this, eventMask, instanceIndex); } /** * Gets the event mask of the physics engine. * @param instanceIndex - If this body is instanced, the index of the instance to get the event mask for. * @returns The event mask of the physics engine. * * This method is useful for getting the event mask of the physics engine, * which is used to determine which events the engine will respond to. * This is important for ensuring that the engine is responding to the correct events and not * wasting resources on unnecessary events. */ getEventMask(instanceIndex) { return this._physicsPlugin.getEventMask(this, instanceIndex); } /** * Sets the motion type of the physics body. Can be STATIC, DYNAMIC, or ANIMATED. * @param motionType - The motion type to set. * @param instanceIndex - If this body is instanced, the index of the instance to set the motion type for. If body is instanced but instanceIndex is undefined, the motion type will be set for all instances. */ setMotionType(motionType, instanceIndex) { this.disableSync = instanceIndex === void 0 && motionType == 0; this._physicsPlugin.setMotionType(this, motionType, instanceIndex); } /** * Gets the motion type of the physics body. Can be STATIC, DYNAMIC, or ANIMATED. * @param instanceIndex - If this body is instanced, the index of the instance to get the motion type for. * @returns The motion type of the physics body. */ getMotionType(instanceIndex) { return this._physicsPlugin.getMotionType(this, instanceIndex); } /** * Set the prestep type of the body * @param prestepType prestep type provided by PhysicsPrestepType */ setPrestepType(prestepType) { this._prestepType = prestepType; } /** * Get the current prestep type of the body * @returns the type of prestep associated with the body and its instance index */ getPrestepType() { return this._prestepType; } /** * Computes the mass properties of the physics object, based on the set of physics shapes this body uses. * This method is useful for computing the initial mass properties of a physics object, such as its mass, * inertia, and center of mass; these values are important for accurately simulating the physics of the * object in the physics engine, and computing values based on the shape will provide you with reasonable * initial values, which you can then customize. * @param instanceIndex - The index of the instance to compute the mass properties for. * @returns The mass properties of the object. */ computeMassProperties(instanceIndex) { return this._physicsPlugin.computeMassProperties(this, instanceIndex); } /** * Sets the mass properties of the physics object. * * @param massProps - The mass properties to set. * @param instanceIndex - The index of the instance to set the mass properties for. If not defined, the mass properties will be set for all instances. * * This method is useful for setting the mass properties of a physics object, such as its mass, * inertia, and center of mass. This is important for accurately simulating the physics of the object in the physics engine. */ setMassProperties(massProps, instanceIndex) { this._physicsPlugin.setMassProperties(this, massProps, instanceIndex); } /** * Retrieves the mass properties of the object. * @param instanceIndex - If this body is instanced, the index of the instance to get the mass properties for. * @returns The mass properties of the object. * * This method is useful for physics simulations, as it allows the user to * retrieve the mass properties of the object, such as its mass, center of mass, * and moment of inertia. This information is necessary for accurate physics * simulations. */ getMassProperties(instanceIndex) { return this._physicsPlugin.getMassProperties(this, instanceIndex); } /** * Sets the linear damping of the physics body. * * @param damping - The linear damping value. * @param instanceIndex - If this body is instanced, the index of the instance to set the linear damping for. * * This method is useful for controlling the linear damping of the physics body, * which is the rate at which the body's velocity decreases over time. This is useful for simulating * the effects of air resistance or other forms of friction. */ setLinearDamping(damping, instanceIndex) { this._physicsPlugin.setLinearDamping(this, damping, instanceIndex); } /** * Gets the linear damping of the physics body. * @param instanceIndex - If this body is instanced, the index of the instance to get the linear damping for. * @returns The linear damping of the physics body. * * This method is useful for retrieving the linear damping of the physics body, which is the amount of * resistance the body has to linear motion. This is useful for simulating realistic physics behavior * in a game. */ getLinearDamping(instanceIndex) { return this._physicsPlugin.getLinearDamping(this, instanceIndex); } /** * Sets the angular damping of the physics body. * @param damping The angular damping of the body. * @param instanceIndex - If this body is instanced, the index of the instance to set the angular damping for. * * This method is useful for controlling the angular velocity of a physics body. * By setting the damping, the body's angular velocity will be reduced over time, simulating the effect of friction. * This can be used to create realistic physical behavior in a physics engine. */ setAngularDamping(damping, instanceIndex) { this._physicsPlugin.setAngularDamping(this, damping, instanceIndex); } /** * Gets the angular damping of the physics body. * @param instanceIndex - If this body is instanced, the index of the instance to get the angular damping for. * * @returns The angular damping of the physics body. * * This method is useful for getting the angular damping of the physics body, * which is the rate of reduction of the angular velocity over time. * This is important for simulating realistic physics behavior in a game. */ getAngularDamping(instanceIndex) { return this._physicsPlugin.getAngularDamping(this, instanceIndex); } /** * Sets the linear velocity of the physics object. * @param linVel - The linear velocity to set. * @param instanceIndex - If this body is instanced, the index of the instance to set the linear velocity for. * * This method is useful for setting the linear velocity of a physics object, * which is necessary for simulating realistic physics in a game engine. * By setting the linear velocity, the physics object will move in the direction and speed specified by the vector. * This allows for realistic physics simulations, such as simulating the motion of a ball rolling down a hill. */ setLinearVelocity(linVel, instanceIndex) { this._physicsPlugin.setLinearVelocity(this, linVel, instanceIndex); } /** * Gets the linear velocity of the physics body and stores it in the given vector3. * @param linVel - The vector3 to store the linear velocity in. * @param instanceIndex - If this body is instanced, the index of the instance to get the linear velocity for. * * This method is useful for getting the linear velocity of a physics body in a physics engine. * This can be used to determine the speed and direction of the body, which can be used to calculate the motion of the body. */ getLinearVelocityToRef(linVel, instanceIndex) { this._physicsPlugin.getLinearVelocityToRef(this, linVel, instanceIndex); } /** * Gets the linear velocity of the physics body as a new vector3. * @param instanceIndex - If this body is instanced, the index of the instance to get the linear velocity for. * @returns The linear velocity of the physics body. * * This method is useful for getting the linear velocity of a physics body in a physics engine. * This can be used to determine the speed and direction of the body, which can be used to calculate the motion of the body. */ getLinearVelocity(instanceIndex) { const ref = new Vector3(); this.getLinearVelocityToRef(ref, instanceIndex); return ref; } /** * Sets the angular velocity of the physics object. * @param angVel - The angular velocity to set. * @param instanceIndex - If this body is instanced, the index of the instance to set the angular velocity for. * * This method is useful for setting the angular velocity of a physics object, which is necessary for * simulating realistic physics behavior. The angular velocity is used to determine the rate of rotation of the object, * which is important for simulating realistic motion. */ setAngularVelocity(angVel, instanceIndex) { this._physicsPlugin.setAngularVelocity(this, angVel, instanceIndex); } /** * Gets the angular velocity of the physics body and stores it in the given vector3. * @param angVel - The vector3 to store the angular velocity in. * @param instanceIndex - If this body is instanced, the index of the instance to get the angular velocity for. * * This method is useful for getting the angular velocity of a physics body, which can be used to determine the body's * rotational speed. This information can be used to create realistic physics simulations. */ getAngularVelocityToRef(angVel, instanceIndex) { this._physicsPlugin.getAngularVelocityToRef(this, angVel, instanceIndex); } /** * Gets the angular velocity of the physics body as a new vector3. * @param instanceIndex - If this body is instanced, the index of the instance to get the angular velocity for. * @returns The angular velocity of the physics body. * * This method is useful for getting the angular velocity of a physics body, which can be used to determine the body's * rotational speed. This information can be used to create realistic physics simulations. */ getAngularVelocity(instanceIndex) { const ref = new Vector3(); this.getAngularVelocityToRef(ref, instanceIndex); return ref; } /** * Applies an impulse to the physics object. * * @param impulse The impulse vector. * @param location The location of the impulse. * @param instanceIndex For a instanced body, the instance to where the impulse should be applied. If not specified, the impulse is applied to all instances. * * This method is useful for applying an impulse to a physics object, which can be used to simulate physical forces such as gravity, * collisions, and explosions. This can be used to create realistic physics simulations in a game or other application. */ applyImpulse(impulse, location2, instanceIndex) { this._physicsPlugin.applyImpulse(this, impulse, location2, instanceIndex); } /** * Add torque to a physics body * @param angularImpulse The angular impulse vector. * @param instanceIndex For a instanced body, the instance to where the impulse should be applied. If not specified, the impulse is applied to all instances. */ applyAngularImpulse(angularImpulse, instanceIndex) { this._physicsPlugin.applyAngularImpulse(this, angularImpulse, instanceIndex); } /** * Applies a force to the physics object. * * @param force The force vector. * @param location The location of the force. * @param instanceIndex For a instanced body, the instance to where the force should be applied. If not specified, the force is applied to all instances. * * This method is useful for applying a force to a physics object, which can be used to simulate physical forces such as gravity, * collisions, and explosions. This can be used to create realistic physics simulations in a game or other application. */ applyForce(force, location2, instanceIndex) { this._physicsPlugin.applyForce(this, force, location2, instanceIndex); } /** * Retrieves the geometry of the body from the physics plugin. * * @returns The geometry of the body. * * This method is useful for retrieving the geometry of the body from the physics plugin, which can be used for various physics calculations. */ getGeometry() { return this._physicsPlugin.getBodyGeometry(this); } /** * Returns an observable that will be notified for when a collision starts or continues for this PhysicsBody * @returns Observable */ getCollisionObservable() { return this._physicsPlugin.getCollisionObservable(this); } /** * Returns an observable that will be notified when the body has finished colliding with another body * @returns */ getCollisionEndedObservable() { return this._physicsPlugin.getCollisionEndedObservable(this); } /** * Enable or disable collision callback for this PhysicsBody. * @param enabled true if PhysicsBody's collision will rise a collision event and notifies the observable */ setCollisionCallbackEnabled(enabled) { this._collisionCBEnabled = enabled; this._physicsPlugin.setCollisionCallbackEnabled(this, enabled); } /** * Enable or disable collision ended callback for this PhysicsBody. * @param enabled true if PhysicsBody's collision ended will rise a collision event and notifies the observable */ setCollisionEndedCallbackEnabled(enabled) { this._collisionEndedCBEnabled = enabled; this._physicsPlugin.setCollisionEndedCallbackEnabled(this, enabled); } /** * Get the center of the object in world space. * @param instanceIndex - If this body is instanced, the index of the instance to get the center for. * @returns geometric center of the associated mesh */ getObjectCenterWorld(instanceIndex) { const ref = new Vector3(); return this.getObjectCenterWorldToRef(ref, instanceIndex); } /** * Get the center of the object in world space. * @param ref - The vector3 to store the result in. * @param instanceIndex - If this body is instanced, the index of the instance to get the center for. * @returns geometric center of the associated mesh */ getObjectCenterWorldToRef(ref, instanceIndex) { if (this._pluginDataInstances?.length > 0) { const index = instanceIndex || 0; const matrixData = this.transformNode._thinInstanceDataStorage.matrixData; if (matrixData) { ref.set(matrixData[index * 16 + 12], matrixData[index * 16 + 13], matrixData[index * 16 + 14]); } } else { ref.copyFrom(this.transformNode.position); } return ref; } /** * Adds a constraint to the physics engine. * * @param childBody - The body to which the constraint will be applied. * @param constraint - The constraint to be applied. * @param instanceIndex - If this body is instanced, the index of the instance to which the constraint will be applied. If not specified, no constraint will be applied. * @param childInstanceIndex - If the child body is instanced, the index of the instance to which the constraint will be applied. If not specified, no constraint will be applied. * */ addConstraint(childBody, constraint, instanceIndex, childInstanceIndex) { this._physicsPlugin.addConstraint(this, childBody, constraint, instanceIndex, childInstanceIndex); } /** * Sync with a bone * @param bone The bone that the impostor will be synced to. * @param boneMesh The mesh that the bone is influencing. * @param jointPivot The pivot of the joint / bone in local space. * @param distToJoint Optional distance from the impostor to the joint. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone. * @param boneAxis Optional vector3 axis the bone is aligned with */ syncWithBone(bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) { const mesh = this.transformNode; if (mesh.rotationQuaternion) { if (adjustRotation) { const tempQuat = TmpVectors.Quaternion[0]; bone.getRotationQuaternionToRef(1, boneMesh, tempQuat); tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion); } else { bone.getRotationQuaternionToRef(1, boneMesh, mesh.rotationQuaternion); } } const pos = TmpVectors.Vector3[0]; const boneDir = TmpVectors.Vector3[1]; if (!boneAxis) { boneAxis = TmpVectors.Vector3[2]; boneAxis.x = 0; boneAxis.y = 1; boneAxis.z = 0; } bone.getDirectionToRef(boneAxis, boneMesh, boneDir); bone.getAbsolutePositionToRef(boneMesh, pos); if ((distToJoint === void 0 || distToJoint === null) && jointPivot) { distToJoint = jointPivot.length(); } if (distToJoint !== void 0 && distToJoint !== null) { pos.x += boneDir.x * distToJoint; pos.y += boneDir.y * distToJoint; pos.z += boneDir.z * distToJoint; } mesh.setAbsolutePosition(pos); } /** * Executes a callback on the body or all of the instances of a body * @param callback the callback to execute */ iterateOverAllInstances(callback) { if (this._pluginDataInstances?.length > 0) { for (let i = 0; i < this._pluginDataInstances.length; i++) { callback(this, i); } } else { callback(this, void 0); } } /** * Sets the gravity factor of the physics body * @param factor the gravity factor to set * @param instanceIndex the instance of the body to set, if undefined all instances will be set */ setGravityFactor(factor, instanceIndex) { this._physicsPlugin.setGravityFactor(this, factor, instanceIndex); } /** * Gets the gravity factor of the physics body * @param instanceIndex the instance of the body to get, if undefined the value of first instance will be returned * @returns the gravity factor */ getGravityFactor(instanceIndex) { return this._physicsPlugin.getGravityFactor(this, instanceIndex); } /** * Set the target transformation (position and rotation) of the body, such that the body will set its velocity to reach that target * @param position The target position * @param rotation The target rotation * @param instanceIndex The index of the instance in an instanced body */ setTargetTransform(position, rotation, instanceIndex) { this._physicsPlugin.setTargetTransform(this, position, rotation, instanceIndex); } /** * Returns if the body has been disposed. * @returns true if disposed, false otherwise. */ get isDisposed() { return this._isDisposed; } /** * Disposes the body from the physics engine. * * This method is useful for cleaning up the physics engine when a body is no longer needed. Disposing the body will free up resources and prevent memory leaks. */ dispose() { if (this._isDisposed) { return; } if (this._collisionCBEnabled) { this.setCollisionCallbackEnabled(false); } if (this._collisionEndedCBEnabled) { this.setCollisionEndedCallbackEnabled(false); } if (this._nodeDisposeObserver) { this.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver); this._nodeDisposeObserver = null; } this._physicsEngine.removeBody(this); this._physicsPlugin.removeBody(this); this._physicsPlugin.disposeBody(this); this.transformNode.physicsBody = null; this._pluginData = null; this._pluginDataInstances.length = 0; this._isDisposed = true; this.shape = null; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Physics/v2/physicsShape.js init_math_vector(); var PhysicsShape = class { static { __name(this, "PhysicsShape"); } /** * Constructs a new physics shape. * @param options The options for the physics shape. These are: * * type: The type of the shape. This can be one of the following: SPHERE, BOX, CAPSULE, CYLINDER, CONVEX_HULL, MESH, HEIGHTFIELD, CONTAINER * * parameters: The parameters of the shape. * * pluginData: The plugin data of the shape. This is used if you already have a reference to the object on the plugin side. * You need to specify either type or pluginData. * @param scene The scene the shape belongs to. * * This code is useful for creating a new physics shape with the given type, options, and scene. * It also checks that the physics engine and plugin version are correct. * If not, it throws an error. This ensures that the shape is created with the correct parameters and is compatible with the physics engine. */ constructor(options, scene) { this._pluginData = void 0; this._isTrigger = false; this._isDisposed = false; if (!scene) { return; } const physicsEngine = scene.getPhysicsEngine(); if (!physicsEngine) { throw new Error("No Physics Engine available."); } if (physicsEngine.getPluginVersion() != 2) { throw new Error("Plugin version is incorrect. Expected version 2."); } const physicsPlugin = physicsEngine.getPhysicsPlugin(); if (!physicsPlugin) { throw new Error("No Physics Plugin available."); } this._physicsPlugin = physicsPlugin; if (options.pluginData !== void 0 && options.pluginData !== null) { this._pluginData = options.pluginData; this._type = this._physicsPlugin.getShapeType(this); } else if (options.type !== void 0 && options.type !== null) { this._type = options.type; const parameters = options.parameters ?? {}; this._physicsPlugin.initShape(this, options.type, parameters); } } /** * Returns the string "PhysicsShape". * @returns "PhysicsShape" */ getClassName() { return "PhysicsShape"; } /** * Returns the type of the physics shape. * @returns The type of the physics shape. */ get type() { return this._type; } /** * Set the membership mask of a shape. This is a bitfield of arbitrary * "categories" to which the shape is a member. This is used in combination * with the collide mask to determine if this shape should collide with * another. * * @param membershipMask Bitfield of categories of this shape. */ set filterMembershipMask(membershipMask) { this._physicsPlugin.setShapeFilterMembershipMask(this, membershipMask); } /** * Get the membership mask of a shape. * @returns Bitmask of categories which this shape is a member of. */ get filterMembershipMask() { return this._physicsPlugin.getShapeFilterMembershipMask(this); } /** * Sets the collide mask of a shape. This is a bitfield of arbitrary * "categories" to which this shape collides with. Given two shapes, * the engine will check if the collide mask and membership overlap: * shapeA.filterMembershipMask & shapeB.filterCollideMask * * If this value is zero (i.e. shapeB only collides with categories * which shapeA is _not_ a member of) then the shapes will not collide. * * Note, the engine will also perform the same test with shapeA and * shapeB swapped; the shapes will not collide if either shape has * a collideMask which prevents collision with the other shape. * * @param collideMask Bitmask of categories this shape should collide with */ set filterCollideMask(collideMask) { this._physicsPlugin.setShapeFilterCollideMask(this, collideMask); } /** * * @returns Bitmask of categories that this shape should collide with */ get filterCollideMask() { return this._physicsPlugin.getShapeFilterCollideMask(this); } /** * * @param material */ set material(material) { this._physicsPlugin.setMaterial(this, material); this._material = material; } /** * Returns the material of the physics shape. * @returns The material of the physics shape. */ get material() { if (!this._material) { this._material = this._physicsPlugin.getMaterial(this); } return this._material; } /** * Sets the density of the physics shape. * @param density The density of the physics shape. */ set density(density) { this._physicsPlugin.setDensity(this, density); } /** * Returns the density of the physics shape. * @returns The density of the physics shape. */ get density() { return this._physicsPlugin.getDensity(this); } /** * Utility to add a child shape to this container, * automatically computing the relative transform between * the container shape and the child instance. * * @param parentTransform The transform node associated with this shape * @param newChild The new PhysicsShape to add * @param childTransform The transform node associated with the child shape */ addChildFromParent(parentTransform, newChild, childTransform) { const childToWorld = childTransform.computeWorldMatrix(true); const parentToWorld = parentTransform.computeWorldMatrix(true); const childToParent = TmpVectors.Matrix[0]; childToWorld.multiplyToRef(Matrix.Invert(parentToWorld), childToParent); const translation = TmpVectors.Vector3[0]; const rotation = TmpVectors.Quaternion[0]; const scale = TmpVectors.Vector3[1]; childToParent.decompose(scale, rotation, translation); this._physicsPlugin.addChild(this, newChild, translation, rotation, scale); } /** * Adds a child shape to a container with an optional transform * @param newChild The new PhysicsShape to add * @param translation Optional position of the child shape relative to this shape * @param rotation Optional rotation of the child shape relative to this shape * @param scale Optional scale of the child shape relative to this shape */ addChild(newChild, translation, rotation, scale) { this._physicsPlugin.addChild(this, newChild, translation, rotation, scale); } /** * Removes a child shape from this shape. * @param childIndex The index of the child shape to remove */ removeChild(childIndex) { this._physicsPlugin.removeChild(this, childIndex); } /** * Returns the number of children of a physics shape. * @returns The number of children of a physics shape. */ getNumChildren() { return this._physicsPlugin.getNumChildren(this); } /** * Returns the bounding box of the physics shape. * @returns The bounding box of the physics shape. */ getBoundingBox() { return this._physicsPlugin.getBoundingBox(this); } set isTrigger(isTrigger) { if (this._isTrigger === isTrigger) { return; } this._isTrigger = isTrigger; this._physicsPlugin.setTrigger(this, isTrigger); } get isTrigger() { return this._isTrigger; } /** * Dispose the shape and release its associated resources. */ dispose() { if (this._isDisposed) { return; } this._physicsPlugin.disposeShape(this); this._isDisposed = true; } }; var PhysicsShapeSphere = class _PhysicsShapeSphere extends PhysicsShape { static { __name(this, "PhysicsShapeSphere"); } /** * Constructor for the Sphere Shape * @param center local center of the sphere * @param radius radius * @param scene scene to attach to */ constructor(center, radius, scene) { super({ type: 0, parameters: { center, radius } }, scene); } /** * Derive an approximate sphere from the mesh. * @param mesh node from which to derive the sphere shape * @returns PhysicsShapeSphere */ static FromMesh(mesh) { const bounds = mesh.getBoundingInfo(); const centerLocal = bounds.boundingSphere.center; const he = bounds.boundingBox.extendSize; const radius = Math.max(he.x, he.y, he.z); return new _PhysicsShapeSphere(centerLocal, radius, mesh.getScene()); } }; var PhysicsShapeCapsule = class _PhysicsShapeCapsule extends PhysicsShape { static { __name(this, "PhysicsShapeCapsule"); } /** * * @param pointA Starting point that defines the capsule segment * @param pointB ending point of that same segment * @param radius radius * @param scene scene to attach to */ constructor(pointA, pointB, radius, scene) { super({ type: 1, parameters: { pointA, pointB, radius } }, scene); } /** * Derive an approximate capsule from the mesh. Note, this is * not the optimal bounding capsule. * @param mesh Node from which to derive a cylinder shape * @returns Physics Shape Capsule */ static FromMesh(mesh) { const boundsLocal = mesh.getBoundingInfo(); const radius = boundsLocal.boundingBox.extendSize.x; const pointFromCenter = new Vector3(0, boundsLocal.boundingBox.extendSize.y - radius, 0); const pointA = boundsLocal.boundingBox.center.add(pointFromCenter); const pointB = boundsLocal.boundingBox.center.subtract(pointFromCenter); return new _PhysicsShapeCapsule(pointA, pointB, radius, mesh.getScene()); } }; var PhysicsShapeCylinder = class _PhysicsShapeCylinder extends PhysicsShape { static { __name(this, "PhysicsShapeCylinder"); } /** * * @param pointA Starting point that defines the cylinder segment * @param pointB ending point of that same segment * @param radius radius * @param scene scene to attach to */ constructor(pointA, pointB, radius, scene) { super({ type: 2, parameters: { pointA, pointB, radius } }, scene); } /** * Derive an approximate cylinder from the mesh. Note, this is * not the optimal bounding cylinder. * @param mesh Node from which to derive a cylinder shape * @returns Physics Shape Cylinder */ static FromMesh(mesh) { const boundsLocal = mesh.getBoundingInfo(); const radius = boundsLocal.boundingBox.extendSize.x; const pointFromCenter = new Vector3(0, boundsLocal.boundingBox.extendSize.y, 0); const pointA = boundsLocal.boundingBox.center.add(pointFromCenter); const pointB = boundsLocal.boundingBox.center.subtract(pointFromCenter); return new _PhysicsShapeCylinder(pointA, pointB, radius, mesh.getScene()); } }; var PhysicsShapeBox = class _PhysicsShapeBox extends PhysicsShape { static { __name(this, "PhysicsShapeBox"); } /** * * @param center local center of the box * @param rotation local orientation * @param extents size of the box in each direction * @param scene scene to attach to */ constructor(center, rotation, extents, scene) { super({ type: 3, parameters: { center, rotation, extents } }, scene); } /** * * @param mesh * @returns PhysicsShapeBox */ static FromMesh(mesh) { const bounds = mesh.getBoundingInfo(); const centerLocal = bounds.boundingBox.center; const extents = bounds.boundingBox.extendSize.scale(2); return new _PhysicsShapeBox(centerLocal, Quaternion.Identity(), extents, mesh.getScene()); } }; var PhysicsShapeConvexHull = class extends PhysicsShape { static { __name(this, "PhysicsShapeConvexHull"); } /** * * @param mesh the mesh to be used as topology infos for the convex hull * @param scene scene to attach to */ constructor(mesh, scene) { super({ type: 4, parameters: { mesh } }, scene); } }; var PhysicsShapeMesh = class extends PhysicsShape { static { __name(this, "PhysicsShapeMesh"); } /** * * @param mesh the mesh topology that will be used to create the shape * @param scene scene to attach to */ constructor(mesh, scene) { super({ type: 6, parameters: { mesh } }, scene); } }; var PhysicsShapeContainer = class extends PhysicsShape { static { __name(this, "PhysicsShapeContainer"); } /** * Constructor of the Shape container * @param scene scene to attach to */ constructor(scene) { super({ type: 5, parameters: {} }, scene); } }; var PhysicsShapeHeightField = class extends PhysicsShape { static { __name(this, "PhysicsShapeHeightField"); } /** * Constructor of the Shape heightfield * @param heightFieldSizeX The size of the heightfield in the X axis * @param heightFieldSizeZ The size of the heightfield in the Z axis * @param numHeightFieldSamplesX The number of samples along the X axis * @param numHeightFieldSamplesZ The number of samples along the Z axis * @param heightFieldData The data for the heightfield * @param scene scene to attach to */ constructor(heightFieldSizeX, heightFieldSizeZ, numHeightFieldSamplesX, numHeightFieldSamplesZ, heightFieldData, scene) { super({ type: 7, parameters: { heightFieldSizeX, heightFieldSizeZ, numHeightFieldSamplesX, numHeightFieldSamplesZ, heightFieldData } }, scene); } }; var PhysicsShapeGroundMesh = class extends PhysicsShape { static { __name(this, "PhysicsShapeGroundMesh"); } /** * Constructor of the Shape heightfield * @param groundMesh ground mesh used for display * @param scene scene to attach to */ constructor(groundMesh, scene) { super({ type: 7, parameters: { groundMesh } }, scene); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Physics/v2/physicsAggregate.js init_logger(); init_math_vector(); init_math_scalar_functions(); init_boundingBox(); var PhysicsAggregate = class { static { __name(this, "PhysicsAggregate"); } constructor(transformNode, type, _options = { mass: 0 }, _scene) { this.transformNode = transformNode; this.type = type; this._options = _options; this._scene = _scene; this._disposeShapeWhenDisposed = true; if (!this.transformNode) { Logger.Error("No object was provided. A physics object is obligatory"); return; } const m = transformNode; if (this.transformNode.parent && this._options.mass !== 0 && m.hasThinInstances) { Logger.Warn("A physics body has been created for an object which has a parent and thin instances. Babylon physics currently works in local space so unexpected issues may occur."); } if (!this._scene && transformNode.getScene) { this._scene = transformNode.getScene(); } if (!this._scene) { return; } this._options.mass = _options.mass === void 0 ? 0 : _options.mass; this._options.friction = _options.friction === void 0 ? 0.2 : _options.friction; this._options.restitution = _options.restitution === void 0 ? 0.2 : _options.restitution; const motionType = this._options.mass === 0 ? 0 : 2; const startAsleep = this._options.startAsleep ?? false; this.body = new PhysicsBody(transformNode, motionType, startAsleep, this._scene); this._addSizeOptions(); if (type.getClassName && type.getClassName() === "PhysicsShape") { this.shape = type; this._disposeShapeWhenDisposed = false; } else { this.shape = new PhysicsShape({ type, parameters: this._options }, this._scene); } if (this._options.isTriggerShape) { this.shape.isTrigger = true; } this.material = { friction: this._options.friction, restitution: this._options.restitution }; this.body.shape = this.shape; this.shape.material = this.material; this.body.setMassProperties({ mass: this._options.mass }); this._nodeDisposeObserver = this.transformNode.onDisposeObservable.add(() => { this.dispose(); }); } _getObjectBoundingBox() { if (this.transformNode.getRawBoundingInfo) { return this.transformNode.getRawBoundingInfo().boundingBox; } else { return new BoundingBox(new Vector3(-0.5, -0.5, -0.5), new Vector3(0.5, 0.5, 0.5)); } } _hasVertices(node) { return node?.getTotalVertices() > 0; } _addSizeOptions() { this.transformNode.computeWorldMatrix(true); const bb = this._getObjectBoundingBox(); const extents = TmpVectors.Vector3[0]; extents.copyFrom(bb.extendSize); extents.scaleInPlace(2); extents.multiplyInPlace(this.transformNode.absoluteScaling); extents.x = Math.abs(extents.x); extents.y = Math.abs(extents.y); extents.z = Math.abs(extents.z); const min = TmpVectors.Vector3[1]; min.copyFrom(bb.minimum); min.multiplyInPlace(this.transformNode.absoluteScaling); if (!this._options.center) { const center = new Vector3(); center.copyFrom(bb.center); center.multiplyInPlace(this.transformNode.absoluteScaling); this._options.center = center; } switch (this.type) { case 0: if (!this._options.radius && WithinEpsilon(extents.x, extents.y, 1e-4) && WithinEpsilon(extents.x, extents.z, 1e-4)) { this._options.radius = extents.x / 2; } else if (!this._options.radius) { Logger.Warn("Non uniform scaling is unsupported for sphere shapes. Setting the radius to the biggest bounding box extent."); this._options.radius = Math.max(extents.x, extents.y, extents.z) / 2; } break; case 1: { const capRadius = extents.x / 2; this._options.radius = this._options.radius ?? capRadius; this._options.pointA = this._options.pointA ?? new Vector3(0, min.y + capRadius, 0); this._options.pointB = this._options.pointB ?? new Vector3(0, min.y + extents.y - capRadius, 0); } break; case 2: { const capRadius = extents.x / 2; this._options.radius = this._options.radius ?? capRadius; this._options.pointA = this._options.pointA ?? new Vector3(0, min.y, 0); this._options.pointB = this._options.pointB ?? new Vector3(0, min.y + extents.y, 0); } break; case 6: case 4: case 7: if (!this._options.mesh && this._hasVertices(this.transformNode)) { this._options.mesh = this.transformNode; } else if (!this._options.mesh || !this._hasVertices(this._options.mesh)) { throw new Error("No valid mesh was provided for mesh or convex hull shape parameter. Please provide a mesh with valid geometry (number of vertices greater than 0)."); } break; case 3: this._options.extents = this._options.extents ?? new Vector3(extents.x, extents.y, extents.z); this._options.rotation = this._options.rotation ?? Quaternion.Identity(); break; } } /** * Releases the body, shape and material */ dispose() { if (this._nodeDisposeObserver) { this.body.transformNode.onDisposeObservable.remove(this._nodeDisposeObserver); this._nodeDisposeObserver = null; } this.body.dispose(); if (this._disposeShapeWhenDisposed) { this.shape.dispose(); } } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/loading/physics.js init_math_vector(); function configurePhysicsAggregate(transformNode) { const data = transformNode.metadata?.physicsAggregate; if (!data) { return; } let mesh = void 0; if (isMesh(transformNode)) { mesh = transformNode; } else if (isInstancedMesh(transformNode)) { mesh = transformNode.sourceMesh; } const aggregate = new PhysicsAggregate(transformNode, data.shape.type, { mesh, mass: data.massProperties.mass }); aggregate.body.setMassProperties({ mass: data.massProperties.mass, inertia: data.massProperties.inertia ? Vector3.FromArray(data.massProperties.inertia) : void 0, centerOfMass: data.massProperties.centerOfMass ? Vector3.FromArray(data.massProperties.centerOfMass) : void 0, inertiaOrientation: data.massProperties.inertiaOrientation ? Quaternion.FromArray(data.massProperties.inertiaOrientation) : void 0 }); aggregate.shape.density = data.shape.density; aggregate.body.setMotionType(data.body.motionType); aggregate.shape.material = data.material; transformNode.physicsAggregate = aggregate; transformNode.metadata.physicsAggregate = void 0; } __name(configurePhysicsAggregate, "configurePhysicsAggregate"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/loading/rendering.js function applyRenderingConfigurations(scene, rendering) { const postProcessConfigurations = Array.isArray(rendering) ? rendering : []; postProcessConfigurations.forEach((configuration) => { const camera = scene.getCameraById(configuration.cameraId); if (!camera) { return; } if (configuration.ssao2RenderingPipeline) { ssaoRenderingPipelineCameraConfigurations.set(camera, configuration.ssao2RenderingPipeline); } if (configuration.vlsPostProcess) { vlsPostProcessCameraConfigurations.set(camera, configuration.vlsPostProcess); } if (configuration.ssrRenderingPipeline) { ssrRenderingPipelineCameraConfigurations.set(camera, configuration.ssrRenderingPipeline); } if (configuration.motionBlurPostProcess) { motionBlurPostProcessCameraConfigurations.set(camera, configuration.motionBlurPostProcess); } if (configuration.defaultRenderingPipeline) { defaultPipelineCameraConfigurations.set(camera, configuration.defaultRenderingPipeline); } }); } __name(applyRenderingConfigurations, "applyRenderingConfigurations"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Meshes/Builders/sphereBuilder.js init_math_vector(); init_compatibilityOptions(); function CreateSphereVertexData(options) { const segments = (options.segments || 32) | 0; const diameterX = options.diameterX || options.diameter || 1; const diameterY = options.diameterY || options.diameter || 1; const diameterZ = options.diameterZ || options.diameter || 1; const arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1; const slice = options.slice && options.slice <= 0 ? 1 : options.slice || 1; const sideOrientation = options.sideOrientation === 0 ? 0 : options.sideOrientation || VertexData.DEFAULTSIDE; const dedupTopBottomIndices = !!options.dedupTopBottomIndices; const radius = new Vector3(diameterX / 2, diameterY / 2, diameterZ / 2); const totalZRotationSteps = 2 + segments; const totalYRotationSteps = 2 * totalZRotationSteps; const indices = []; const positions = []; const normals = []; const uvs = []; for (let zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) { const normalizedZ = zRotationStep / totalZRotationSteps; const angleZ = normalizedZ * Math.PI * slice; for (let yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) { const normalizedY = yRotationStep / totalYRotationSteps; const angleY = normalizedY * Math.PI * 2 * arc; const rotationZ = Matrix.RotationZ(-angleZ); const rotationY = Matrix.RotationY(angleY); const afterRotZ = Vector3.TransformCoordinates(Vector3.Up(), rotationZ); const complete = Vector3.TransformCoordinates(afterRotZ, rotationY); const vertex = complete.multiply(radius); const normal = complete.divide(radius).normalize(); positions.push(vertex.x, vertex.y, vertex.z); normals.push(normal.x, normal.y, normal.z); uvs.push(normalizedY, useOpenGLOrientationForUV ? 1 - normalizedZ : normalizedZ); } if (zRotationStep > 0) { const verticesCount = positions.length / 3; for (let firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); firstIndex + totalYRotationSteps + 2 < verticesCount; firstIndex++) { if (dedupTopBottomIndices) { if (zRotationStep > 1) { indices.push(firstIndex); indices.push(firstIndex + 1); indices.push(firstIndex + totalYRotationSteps + 1); } if (zRotationStep < totalZRotationSteps || slice < 1) { indices.push(firstIndex + totalYRotationSteps + 1); indices.push(firstIndex + 1); indices.push(firstIndex + totalYRotationSteps + 2); } } else { indices.push(firstIndex); indices.push(firstIndex + 1); indices.push(firstIndex + totalYRotationSteps + 1); indices.push(firstIndex + totalYRotationSteps + 1); indices.push(firstIndex + 1); indices.push(firstIndex + totalYRotationSteps + 2); } } } } VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs); const vertexData = new VertexData(); vertexData.indices = indices; vertexData.positions = positions; vertexData.normals = normals; vertexData.uvs = uvs; return vertexData; } __name(CreateSphereVertexData, "CreateSphereVertexData"); function CreateSphere(name260, options = {}, scene = null) { const sphere = new Mesh(name260, scene); options.sideOrientation = Mesh._GetDefaultSideOrientation(options.sideOrientation); sphere._originalBuilderSideOrientation = options.sideOrientation; const vertexData = CreateSphereVertexData(options); vertexData.applyToMesh(sphere, options.updatable); return sphere; } __name(CreateSphere, "CreateSphere"); var SphereBuilder = { // eslint-disable-next-line @typescript-eslint/naming-convention CreateSphere }; VertexData.CreateSphere = CreateSphereVertexData; Mesh.CreateSphere = (name260, segments, diameter, scene, updatable, sideOrientation) => { const options = { segments, diameterX: diameter, diameterY: diameter, diameterZ: diameter, sideOrientation, updatable }; return CreateSphere(name260, options, scene); }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Misc/gradients.js init_math_color(); var ColorGradient = class { static { __name(this, "ColorGradient"); } /** * Creates a new color4 gradient * @param gradient gets or sets the gradient value (between 0 and 1) * @param color1 gets or sets first associated color * @param color2 gets or sets first second color */ constructor(gradient, color1, color2) { this.gradient = gradient; this.color1 = color1; this.color2 = color2; } /** * Will get a color picked randomly between color1 and color2. * If color2 is undefined then color1 will be used * @param result defines the target Color4 to store the result in */ getColorToRef(result) { if (!this.color2) { result.copyFrom(this.color1); return; } Color4.LerpToRef(this.color1, this.color2, Math.random(), result); } }; var Color3Gradient = class { static { __name(this, "Color3Gradient"); } /** * Creates a new color3 gradient * @param gradient gets or sets the gradient value (between 0 and 1) * @param color gets or sets associated color */ constructor(gradient, color) { this.gradient = gradient; this.color = color; } }; var FactorGradient = class { static { __name(this, "FactorGradient"); } /** * Creates a new factor gradient * @param gradient gets or sets the gradient value (between 0 and 1) * @param factor1 gets or sets first associated factor * @param factor2 gets or sets second associated factor */ constructor(gradient, factor1, factor2) { this.gradient = gradient; this.factor1 = factor1; this.factor2 = factor2; } /** * Will get a number picked randomly between factor1 and factor2. * If factor2 is undefined then factor1 will be used * @returns the picked number */ getFactor() { if (this.factor2 === void 0 || this.factor2 === this.factor1) { return this.factor1; } return this.factor1 + (this.factor2 - this.factor1) * Math.random(); } }; var GradientHelper = class { static { __name(this, "GradientHelper"); } /** * Gets the current gradient from an array of IValueGradient * @param ratio defines the current ratio to get * @param gradients defines the array of IValueGradient * @param updateFunc defines the callback function used to get the final value from the selected gradients */ static GetCurrentGradient(ratio, gradients, updateFunc) { if (gradients[0].gradient > ratio) { updateFunc(gradients[0], gradients[0], 1); return; } for (let gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) { const currentGradient = gradients[gradientIndex]; const nextGradient = gradients[gradientIndex + 1]; if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) { const scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient); updateFunc(currentGradient, nextGradient, scale); return; } } const lastIndex = gradients.length - 1; updateFunc(gradients[lastIndex], gradients[lastIndex], 1); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/baseParticleSystem.js init_math_vector(); init_math_color(); init_engine_dynamicBuffer(); init_typeStore(); var BaseParticleSystem = class _BaseParticleSystem { static { __name(this, "BaseParticleSystem"); } /** * The amount of time the particle system is running (depends of the overall update speed). */ get targetStopDuration() { return this._targetStopDuration; } set targetStopDuration(value) { if (this._targetStopDuration === value) { return; } this._targetStopDuration = value; } /** * Returns true if the particle system was generated by a node particle system set */ get isNodeGenerated() { return false; } /** * Gets or sets a texture used to add random noise to particle positions */ get noiseTexture() { return this._noiseTexture; } set noiseTexture(value) { if (this._noiseTexture === value) { return; } this._noiseTexture = value; this._reset(); } /** @internal */ get _isAnimationSheetEnabled() { return this._animationSheetEnabled; } set _isAnimationSheetEnabled(value) { if (this._animationSheetEnabled === value) { return; } this._animationSheetEnabled = value; } /** * Gets or sets whether an animation sprite sheet is enabled or not on the particle system */ get isAnimationSheetEnabled() { return this._isAnimationSheetEnabled; } set isAnimationSheetEnabled(value) { if (this._isAnimationSheetEnabled == value) { return; } this._isAnimationSheetEnabled = value; this._reset(); } /** * Gets or sets a boolean enabling the use of logarithmic depth buffers, which is good for wide depth buffers. */ get useLogarithmicDepth() { return this._useLogarithmicDepth; } set useLogarithmicDepth(value) { this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported; } /** * Get hosting scene * @returns the scene */ getScene() { return this._scene; } _hasTargetStopDurationDependantGradient() { return this._startSizeGradients && this._startSizeGradients.length > 0 || this._emitRateGradients && this._emitRateGradients.length > 0 || this._lifeTimeGradients && this._lifeTimeGradients.length > 0; } _setEngineBasedOnBlendMode(blendMode) { switch (blendMode) { case _BaseParticleSystem.BLENDMODE_MULTIPLYADD: return; case _BaseParticleSystem.BLENDMODE_ADD: blendMode = 1; break; case _BaseParticleSystem.BLENDMODE_ONEONE: blendMode = 6; break; case _BaseParticleSystem.BLENDMODE_STANDARD: blendMode = 2; break; case _BaseParticleSystem.BLENDMODE_MULTIPLY: blendMode = 4; break; case _BaseParticleSystem.BLENDMODE_SUBTRACT: blendMode = 3; break; default: break; } this._engine.setAlphaMode(blendMode); } /** * Gets the current list of drag gradients. * You must use addDragGradient and removeDragGradient to update this list * @returns the list of drag gradients */ getDragGradients() { return this._dragGradients; } /** * Gets the current list of limit velocity gradients. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to update this list * @returns the list of limit velocity gradients */ getLimitVelocityGradients() { return this._limitVelocityGradients; } /** * Gets the current list of color gradients. * You must use addColorGradient and removeColorGradient to update this list * @returns the list of color gradients */ getColorGradients() { return this._colorGradients; } /** * Gets the current list of size gradients. * You must use addSizeGradient and removeSizeGradient to update this list * @returns the list of size gradients */ getSizeGradients() { return this._sizeGradients; } /** * Gets the current list of color remap gradients. * You must use addColorRemapGradient and removeColorRemapGradient to update this list * @returns the list of color remap gradients */ getColorRemapGradients() { return this._colorRemapGradients; } /** * Gets the current list of alpha remap gradients. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to update this list * @returns the list of alpha remap gradients */ getAlphaRemapGradients() { return this._alphaRemapGradients; } /** * Gets the current list of life time gradients. * You must use addLifeTimeGradient and removeLifeTimeGradient to update this list * @returns the list of life time gradients */ getLifeTimeGradients() { return this._lifeTimeGradients; } /** * Gets the current list of angular speed gradients. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to update this list * @returns the list of angular speed gradients */ getAngularSpeedGradients() { return this._angularSpeedGradients; } /** * Gets the current list of velocity gradients. * You must use addVelocityGradient and removeVelocityGradient to update this list * @returns the list of velocity gradients */ getVelocityGradients() { return this._velocityGradients; } /** * Gets the current list of start size gradients. * You must use addStartSizeGradient and removeStartSizeGradient to update this list * @returns the list of start size gradients */ getStartSizeGradients() { return this._startSizeGradients; } /** * Gets the current list of emit rate gradients. * You must use addEmitRateGradient and removeEmitRateGradient to update this list * @returns the list of emit rate gradients */ getEmitRateGradients() { return this._emitRateGradients; } /** * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. * This only works when particleEmitterTyps is a BoxParticleEmitter */ get direction1() { if (this.particleEmitterType.direction1) { return this.particleEmitterType.direction1; } return Vector3.Zero(); } set direction1(value) { if (this.particleEmitterType.direction1) { this.particleEmitterType.direction1 = value; } } /** * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors. * This only works when particleEmitterTyps is a BoxParticleEmitter */ get direction2() { if (this.particleEmitterType.direction2) { return this.particleEmitterType.direction2; } return Vector3.Zero(); } set direction2(value) { if (this.particleEmitterType.direction2) { this.particleEmitterType.direction2 = value; } } /** * Minimum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. * This only works when particleEmitterTyps is a BoxParticleEmitter */ get minEmitBox() { if (this.particleEmitterType.minEmitBox) { return this.particleEmitterType.minEmitBox; } return Vector3.Zero(); } set minEmitBox(value) { if (this.particleEmitterType.minEmitBox) { this.particleEmitterType.minEmitBox = value; } } /** * Maximum box point around our emitter. Our emitter is the center of particles source, but if you want your particles to emit from more than one point, then you can tell it to do so. * This only works when particleEmitterTyps is a BoxParticleEmitter */ get maxEmitBox() { if (this.particleEmitterType.maxEmitBox) { return this.particleEmitterType.maxEmitBox; } return Vector3.Zero(); } set maxEmitBox(value) { if (this.particleEmitterType.maxEmitBox) { this.particleEmitterType.maxEmitBox = value; } } /** * Gets or sets the billboard mode to use when isBillboardBased = true. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED */ get billboardMode() { return this._billboardMode; } set billboardMode(value) { if (this._billboardMode === value) { return; } this._billboardMode = value; this._reset(); } /** * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction */ get isBillboardBased() { return this._isBillboardBased; } set isBillboardBased(value) { if (this._isBillboardBased === value) { return; } this._isBillboardBased = value; this._reset(); } /** * Gets the image processing configuration used either in this material. */ get imageProcessingConfiguration() { 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 imageProcessingConfiguration(value) { this._attachImageProcessingConfiguration(value); } /** * Attaches a new image processing configuration to the Standard Material. * @param configuration */ _attachImageProcessingConfiguration(configuration) { if (configuration === this._imageProcessingConfiguration) { return; } if (!configuration && this._scene) { this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration; } else { this._imageProcessingConfiguration = configuration; } } /** @internal */ _reset() { } /** * @internal */ _removeGradientAndTexture(gradient, gradients, texture) { if (!gradients) { return this; } let index = 0; for (const valueGradient of gradients) { if (valueGradient.gradient === gradient) { gradients.splice(index, 1); break; } index++; } if (texture) { texture.dispose(); } return this; } /** * Instantiates a particle system. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. * @param name The name of the particle system */ constructor(name260) { this.animations = []; this.renderingGroupId = 0; this.emitter = Vector3.Zero(); this.emitRate = 10; this.manualEmitCount = -1; this.updateSpeed = 0.01; this._targetStopDuration = 0; this.disposeOnStop = false; this.minEmitPower = 1; this.maxEmitPower = 1; this.minLifeTime = 1; this.maxLifeTime = 1; this.minSize = 1; this.maxSize = 1; this.minScaleX = 1; this.maxScaleX = 1; this.minScaleY = 1; this.maxScaleY = 1; this.minInitialRotation = 0; this.maxInitialRotation = 0; this.minAngularSpeed = 0; this.maxAngularSpeed = 0; this.layerMask = 268435455; this.customShader = null; this.preventAutoStart = false; this.applyFog = false; this._wasDispatched = false; this._rootUrl = ""; this.noiseStrength = new Vector3(10, 10, 10); this.onAnimationEnd = null; this.blendMode = _BaseParticleSystem.BLENDMODE_ONEONE; this.forceDepthWrite = false; this.preWarmCycles = 0; this.preWarmStepOffset = 1; this.spriteCellChangeSpeed = 1; this.startSpriteCellID = 0; this.endSpriteCellID = 0; this.spriteCellWidth = 0; this.spriteCellHeight = 0; this.spriteCellLoop = true; this.spriteRandomStartCell = false; this.translationPivot = new Vector2(0, 0); this._animationSheetEnabled = false; this.beginAnimationOnStart = false; this.beginAnimationFrom = 0; this.beginAnimationTo = 60; this.beginAnimationLoop = false; this.worldOffset = new Vector3(0, 0, 0); this._useLogarithmicDepth = false; this.gravity = Vector3.Zero(); this._colorGradients = null; this._sizeGradients = null; this._lifeTimeGradients = null; this._angularSpeedGradients = null; this._velocityGradients = null; this._limitVelocityGradients = null; this._dragGradients = null; this._emitRateGradients = null; this._startSizeGradients = null; this._rampGradients = null; this._colorRemapGradients = null; this._alphaRemapGradients = null; this.startDelay = 0; this.limitVelocityDamping = 0.4; this.color1 = new Color4(1, 1, 1, 1); this.color2 = new Color4(1, 1, 1, 1); this.colorDead = new Color4(0, 0, 0, 1); this.textureMask = new Color4(1, 1, 1, 1); this._isSubEmitter = false; this._billboardMode = 7; this._isBillboardBased = true; this._imageProcessingConfigurationDefines = new ImageProcessingConfigurationDefines(); this.id = name260; this.name = name260; } /** * Creates a Point Emitter for the particle system (emits directly from the emitter position) * @param direction1 Particles are emitted between the direction1 and direction2 from within the box * @param direction2 Particles are emitted between the direction1 and direction2 from within the box */ createPointEmitter(direction1, direction2) { throw new Error("Method not implemented."); } /** * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius) * @param radius The radius of the hemisphere to emit from * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius */ createHemisphericEmitter(radius = 1, radiusRange = 1) { throw new Error("Method not implemented."); } /** * Creates a Sphere Emitter for the particle system (emits along the sphere radius) * @param radius The radius of the sphere to emit from * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius */ createSphereEmitter(radius = 1, radiusRange = 1) { throw new Error("Method not implemented."); } /** * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2) * @param radius The radius of the sphere to emit from * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere */ createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { throw new Error("Method not implemented."); } /** * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position) * @param radius The radius of the emission cylinder * @param height The height of the emission cylinder * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius * @param directionRandomizer How much to randomize the particle direction [0-1] */ createCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) { throw new Error("Method not implemented."); } /** * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2) * @param radius The radius of the cylinder to emit from * @param height The height of the emission cylinder * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default) * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder */ createDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { throw new Error("Method not implemented."); } /** * Creates a Cone Emitter for the particle system (emits from the cone to the particle position) * @param radius The radius of the cone to emit from * @param angle The base angle of the cone */ createConeEmitter(radius = 1, angle = Math.PI / 4) { throw new Error("Method not implemented."); } createDirectedConeEmitter(radius = 1, angle = Math.PI / 4, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { throw new Error("Method not implemented."); } /** * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox) * @param direction1 Particles are emitted between the direction1 and direction2 from within the box * @param direction2 Particles are emitted between the direction1 and direction2 from within the box * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox */ createBoxEmitter(direction1, direction2, minEmitBox, maxEmitBox) { throw new Error("Method not implemented."); } }; BaseParticleSystem.BLENDMODE_ONEONE = 0; BaseParticleSystem.BLENDMODE_STANDARD = 1; BaseParticleSystem.BLENDMODE_ADD = 2; BaseParticleSystem.BLENDMODE_MULTIPLY = 3; BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4; BaseParticleSystem.BLENDMODE_SUBTRACT = -1; RegisterClass("BABYLON.BaseParticleSystem", BaseParticleSystem); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/particle.js init_math_vector(); init_math_color(); init_math_scalar_functions(); var Particle = class _Particle { static { __name(this, "Particle"); } /** * Creates a new instance Particle * @param particleSystem the particle system the particle belongs to */ constructor(particleSystem) { this.particleSystem = particleSystem; this.position = Vector3.Zero(); this.direction = Vector3.Zero(); this.color = new Color4(0, 0, 0, 0); this.colorStep = new Color4(0, 0, 0, 0); this.initialColor = new Color4(0, 0, 0, 0); this.colorDead = new Color4(0, 0, 0, 0); this.lifeTime = 1; this.age = 0; this.size = 0; this.scale = new Vector2(1, 1); this.angle = 0; this.angularSpeed = 0; this.cellIndex = 0; this._attachedSubEmitters = null; this._currentColor1 = new Color4(0, 0, 0, 0); this._currentColor2 = new Color4(0, 0, 0, 0); this._currentSize1 = 0; this._currentSize2 = 0; this._currentAngularSpeed1 = 0; this._currentAngularSpeed2 = 0; this._currentVelocity1 = 0; this._currentVelocity2 = 0; this._currentLimitVelocity1 = 0; this._currentLimitVelocity2 = 0; this._currentDrag1 = 0; this._currentDrag2 = 0; this.id = _Particle._Count++; if (!this.particleSystem.isAnimationSheetEnabled) { return; } this._updateCellInfoFromSystem(); } _updateCellInfoFromSystem() { this.cellIndex = this.particleSystem.startSpriteCellID; } /** * Defines how the sprite cell index is updated for the particle */ updateCellIndex() { let offsetAge = this.age; let changeSpeed = this.particleSystem.spriteCellChangeSpeed; if (this.particleSystem.spriteRandomStartCell) { if (this._randomCellOffset === void 0) { this._randomCellOffset = Math.random() * this.lifeTime; } if (changeSpeed === 0) { changeSpeed = 1; offsetAge = this._randomCellOffset; } else { offsetAge += this._randomCellOffset; } } const dist = this._initialEndSpriteCellId - this._initialStartSpriteCellId + 1; let ratio; if (this._initialSpriteCellLoop) { ratio = Clamp(offsetAge * changeSpeed % this.lifeTime / this.lifeTime); } else { ratio = Clamp(offsetAge * changeSpeed / this.lifeTime); } this.cellIndex = this._initialStartSpriteCellId + ratio * dist | 0; } /** * @internal */ _inheritParticleInfoToSubEmitter(subEmitter) { if (subEmitter.particleSystem.emitter.position) { const emitterMesh = subEmitter.particleSystem.emitter; emitterMesh.position.copyFrom(this.position); if (subEmitter.inheritDirection) { const temp = TmpVectors.Vector3[0]; this.direction.normalizeToRef(temp); emitterMesh.setDirection(temp, 0, Math.PI / 2); } } else { const emitterPosition = subEmitter.particleSystem.emitter; emitterPosition.copyFrom(this.position); } this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, TmpVectors.Vector3[0]); subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(TmpVectors.Vector3[0]); } /** @internal */ _inheritParticleInfoToSubEmitters() { if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) { for (const subEmitter of this._attachedSubEmitters) { this._inheritParticleInfoToSubEmitter(subEmitter); } } } /** @internal */ _reset() { this.age = 0; this.id = _Particle._Count++; this._currentColorGradient = null; this._currentSizeGradient = null; this._currentAngularSpeedGradient = null; this._currentVelocityGradient = null; this._currentLimitVelocityGradient = null; this._currentDragGradient = null; this.cellIndex = this.particleSystem.startSpriteCellID; this._randomCellOffset = void 0; } /** * Copy the properties of particle to another one. * @param other the particle to copy the information to. */ copyTo(other) { other.position.copyFrom(this.position); if (this._initialDirection) { if (other._initialDirection) { other._initialDirection.copyFrom(this._initialDirection); } else { other._initialDirection = this._initialDirection.clone(); } } else { other._initialDirection = null; } other.direction.copyFrom(this.direction); if (this._localPosition) { if (other._localPosition) { other._localPosition.copyFrom(this._localPosition); } else { other._localPosition = this._localPosition.clone(); } } other.color.copyFrom(this.color); other.colorStep.copyFrom(this.colorStep); other.initialColor.copyFrom(this.initialColor); other.colorDead.copyFrom(this.colorDead); other.lifeTime = this.lifeTime; other.age = this.age; other._randomCellOffset = this._randomCellOffset; other.size = this.size; other.scale.copyFrom(this.scale); other.angle = this.angle; other.angularSpeed = this.angularSpeed; other.particleSystem = this.particleSystem; other.cellIndex = this.cellIndex; other.id = this.id; other._attachedSubEmitters = this._attachedSubEmitters; if (this._currentColorGradient) { other._currentColorGradient = this._currentColorGradient; other._currentColor1.copyFrom(this._currentColor1); other._currentColor2.copyFrom(this._currentColor2); } if (this._currentSizeGradient) { other._currentSizeGradient = this._currentSizeGradient; other._currentSize1 = this._currentSize1; other._currentSize2 = this._currentSize2; } if (this._currentAngularSpeedGradient) { other._currentAngularSpeedGradient = this._currentAngularSpeedGradient; other._currentAngularSpeed1 = this._currentAngularSpeed1; other._currentAngularSpeed2 = this._currentAngularSpeed2; } if (this._currentVelocityGradient) { other._currentVelocityGradient = this._currentVelocityGradient; other._currentVelocity1 = this._currentVelocity1; other._currentVelocity2 = this._currentVelocity2; } if (this._currentLimitVelocityGradient) { other._currentLimitVelocityGradient = this._currentLimitVelocityGradient; other._currentLimitVelocity1 = this._currentLimitVelocity1; other._currentLimitVelocity2 = this._currentLimitVelocity2; } if (this._currentDragGradient) { other._currentDragGradient = this._currentDragGradient; other._currentDrag1 = this._currentDrag1; other._currentDrag2 = this._currentDrag2; } if (this.particleSystem.isAnimationSheetEnabled) { other._initialStartSpriteCellId = this._initialStartSpriteCellId; other._initialEndSpriteCellId = this._initialEndSpriteCellId; other._initialSpriteCellLoop = this._initialSpriteCellLoop; } if (this.particleSystem.useRampGradients) { if (other.remapData && this.remapData) { other.remapData.copyFrom(this.remapData); } else { other.remapData = new Vector4(0, 0, 0, 0); } } if (this._randomNoiseCoordinates1) { if (other._randomNoiseCoordinates1) { other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1); other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2); } else { other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone(); other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone(); } } } }; Particle._Count = 0; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/EmitterTypes/boxParticleEmitter.js init_math_vector(); init_math_scalar_functions(); init_deepCopier(); var BoxParticleEmitter = class _BoxParticleEmitter { static { __name(this, "BoxParticleEmitter"); } /** * Creates a new instance BoxParticleEmitter */ constructor() { this.direction1 = new Vector3(0, 1, 0); this.direction2 = new Vector3(0, 1, 0); this.minEmitBox = new Vector3(-0.5, -0.5, -0.5); this.maxEmitBox = new Vector3(0.5, 0.5, 0.5); } /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param directionToUpdate is the direction vector to update with the result * @param particle is the particle we are computed the direction for * @param isLocal defines if the direction should be set in local space */ startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { const randX = RandomRange(this.direction1.x, this.direction2.x); const randY = RandomRange(this.direction1.y, this.direction2.y); const randZ = RandomRange(this.direction1.z, this.direction2.z); if (isLocal) { directionToUpdate.x = randX; directionToUpdate.y = randY; directionToUpdate.z = randZ; return; } Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); } /** * Called by the particle System when the position is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param positionToUpdate is the position vector to update with the result * @param particle is the particle we are computed the position for * @param isLocal defines if the position should be set in local space */ startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { const randX = RandomRange(this.minEmitBox.x, this.maxEmitBox.x); const randY = RandomRange(this.minEmitBox.y, this.maxEmitBox.y); const randZ = RandomRange(this.minEmitBox.z, this.maxEmitBox.z); if (isLocal) { positionToUpdate.x = randX; positionToUpdate.y = randY; positionToUpdate.z = randZ; return; } Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate); } /** * Clones the current emitter and returns a copy of it * @returns the new emitter */ clone() { const newOne = new _BoxParticleEmitter(); DeepCopier.DeepCopy(this, newOne); return newOne; } /** * Called by the GPUParticleSystem to setup the update shader * @param uboOrEffect defines the update shader */ applyToShader(uboOrEffect) { uboOrEffect.setVector3("direction1", this.direction1); uboOrEffect.setVector3("direction2", this.direction2); uboOrEffect.setVector3("minEmitBox", this.minEmitBox); uboOrEffect.setVector3("maxEmitBox", this.maxEmitBox); } /** * Creates the structure of the ubo for this particle emitter * @param ubo ubo to create the structure for */ buildUniformLayout(ubo) { ubo.addUniform("direction1", 3); ubo.addUniform("direction2", 3); ubo.addUniform("minEmitBox", 3); ubo.addUniform("maxEmitBox", 3); } /** * Returns a string to use to update the GPU particles update shader * @returns a string containing the defines string */ getEffectDefines() { return "#define BOXEMITTER"; } /** * Returns the string "BoxParticleEmitter" * @returns a string containing the class name */ getClassName() { return "BoxParticleEmitter"; } /** * Serializes the particle system to a JSON object. * @returns the JSON object */ serialize() { const serializationObject = {}; serializationObject.type = this.getClassName(); serializationObject.direction1 = this.direction1.asArray(); serializationObject.direction2 = this.direction2.asArray(); serializationObject.minEmitBox = this.minEmitBox.asArray(); serializationObject.maxEmitBox = this.maxEmitBox.asArray(); return serializationObject; } /** * Parse properties from a JSON object * @param serializationObject defines the JSON object */ parse(serializationObject) { Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1); Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2); Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox); Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/thinParticleSystem.function.js init_math_color(); init_math_scalar_functions(); init_math_vector(); function _CreateColorData(particle, system) { const step = RandomRange(0, 1); Color4.LerpToRef(system.color1, system.color2, step, particle.color); } __name(_CreateColorData, "_CreateColorData"); function _CreateColorDeadData(particle, system) { system.colorDead.subtractToRef(particle.color, system._colorDiff); system._colorDiff.scaleToRef(1 / particle.lifeTime, particle.colorStep); } __name(_CreateColorDeadData, "_CreateColorDeadData"); function _CreateColorGradientsData(particle, system) { particle._currentColorGradient = system._colorGradients[0]; particle._currentColorGradient.getColorToRef(particle.color); particle._currentColor1.copyFrom(particle.color); if (system._colorGradients.length > 1) { system._colorGradients[1].getColorToRef(particle._currentColor2); } else { particle._currentColor2.copyFrom(particle.color); } } __name(_CreateColorGradientsData, "_CreateColorGradientsData"); function _ProcessColorGradients(particle, system) { const colorGradients = system._colorGradients; GradientHelper.GetCurrentGradient(system._ratio, colorGradients, (currentGradient, nextGradient, scale) => { if (currentGradient !== particle._currentColorGradient) { particle._currentColor1.copyFrom(particle._currentColor2); nextGradient.getColorToRef(particle._currentColor2); particle._currentColorGradient = currentGradient; } Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color); }); } __name(_ProcessColorGradients, "_ProcessColorGradients"); function _ProcessColor(particle, system) { particle.colorStep.scaleToRef(system._scaledUpdateSpeed, system._scaledColorStep); particle.color.addInPlace(system._scaledColorStep); if (particle.color.a < 0) { particle.color.a = 0; } } __name(_ProcessColor, "_ProcessColor"); function _ProcessAngularSpeedGradients(particle, system) { GradientHelper.GetCurrentGradient(system._ratio, system._angularSpeedGradients, (currentGradient, nextGradient, scale) => { if (currentGradient !== particle._currentAngularSpeedGradient) { particle._currentAngularSpeed1 = particle._currentAngularSpeed2; particle._currentAngularSpeed2 = nextGradient.getFactor(); particle._currentAngularSpeedGradient = currentGradient; } particle.angularSpeed = Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale); }); } __name(_ProcessAngularSpeedGradients, "_ProcessAngularSpeedGradients"); function _ProcessAngularSpeed(particle, system) { particle.angle += particle.angularSpeed * system._scaledUpdateSpeed; } __name(_ProcessAngularSpeed, "_ProcessAngularSpeed"); function _CreateDirectionData(particle, system) { system.particleEmitterType.startDirectionFunction(system._emitterWorldMatrix, particle.direction, particle, system.isLocal, system._emitterInverseWorldMatrix); } __name(_CreateDirectionData, "_CreateDirectionData"); function _CreateCustomDirectionData(particle, system) { system.startDirectionFunction(system._emitterWorldMatrix, particle.direction, particle, system.isLocal); } __name(_CreateCustomDirectionData, "_CreateCustomDirectionData"); function _CreateVelocityGradients(particle, system) { particle._currentVelocityGradient = system._velocityGradients[0]; particle._currentVelocity1 = particle._currentVelocityGradient.getFactor(); if (system._velocityGradients.length > 1) { particle._currentVelocity2 = system._velocityGradients[1].getFactor(); } else { particle._currentVelocity2 = particle._currentVelocity1; } } __name(_CreateVelocityGradients, "_CreateVelocityGradients"); function _CreateLimitVelocityGradients(particle, system) { particle._currentLimitVelocityGradient = system._limitVelocityGradients[0]; particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor(); if (system._limitVelocityGradients.length > 1) { particle._currentLimitVelocity2 = system._limitVelocityGradients[1].getFactor(); } else { particle._currentLimitVelocity2 = particle._currentLimitVelocity1; } } __name(_CreateLimitVelocityGradients, "_CreateLimitVelocityGradients"); function _ProcessVelocityGradients(particle, system) { GradientHelper.GetCurrentGradient(system._ratio, system._velocityGradients, (currentGradient, nextGradient, scale) => { if (currentGradient !== particle._currentVelocityGradient) { particle._currentVelocity1 = particle._currentVelocity2; particle._currentVelocity2 = nextGradient.getFactor(); particle._currentVelocityGradient = currentGradient; } system._directionScale *= Lerp(particle._currentVelocity1, particle._currentVelocity2, scale); }); } __name(_ProcessVelocityGradients, "_ProcessVelocityGradients"); function _ProcessLimitVelocityGradients(particle, system) { GradientHelper.GetCurrentGradient(system._ratio, system._limitVelocityGradients, (currentGradient, nextGradient, scale) => { if (currentGradient !== particle._currentLimitVelocityGradient) { particle._currentLimitVelocity1 = particle._currentLimitVelocity2; particle._currentLimitVelocity2 = nextGradient.getFactor(); particle._currentLimitVelocityGradient = currentGradient; } const limitVelocity = Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale); const currentVelocity = particle.direction.length(); if (currentVelocity > limitVelocity) { particle.direction.scaleInPlace(system.limitVelocityDamping); } }); } __name(_ProcessLimitVelocityGradients, "_ProcessLimitVelocityGradients"); function _ProcessDirection(particle, system) { particle.direction.scaleToRef(system._directionScale, system._scaledDirection); } __name(_ProcessDirection, "_ProcessDirection"); function _CreatePositionData(particle, system) { system.particleEmitterType.startPositionFunction(system._emitterWorldMatrix, particle.position, particle, system.isLocal); } __name(_CreatePositionData, "_CreatePositionData"); function _CreateCustomPositionData(particle, system) { system.startPositionFunction(system._emitterWorldMatrix, particle.position, particle, system.isLocal); } __name(_CreateCustomPositionData, "_CreateCustomPositionData"); function _CreateIsLocalData(particle, system) { if (!particle._localPosition) { particle._localPosition = particle.position.clone(); } else { particle._localPosition.copyFrom(particle.position); } Vector3.TransformCoordinatesToRef(particle._localPosition, system._emitterWorldMatrix, particle.position); } __name(_CreateIsLocalData, "_CreateIsLocalData"); function _ProcessPosition(particle, system) { if (system.isLocal && particle._localPosition) { particle._localPosition.addInPlace(system._scaledDirection); Vector3.TransformCoordinatesToRef(particle._localPosition, system._emitterWorldMatrix, particle.position); } else { particle.position.addInPlace(system._scaledDirection); } } __name(_ProcessPosition, "_ProcessPosition"); function _CreateDragData(particle, system) { particle._currentDragGradient = system._dragGradients[0]; particle._currentDrag1 = particle._currentDragGradient.getFactor(); if (system._dragGradients.length > 1) { particle._currentDrag2 = system._dragGradients[1].getFactor(); } else { particle._currentDrag2 = particle._currentDrag1; } } __name(_CreateDragData, "_CreateDragData"); function _ProcessDragGradients(particle, system) { GradientHelper.GetCurrentGradient(system._ratio, system._dragGradients, (currentGradient, nextGradient, scale) => { if (currentGradient !== particle._currentDragGradient) { particle._currentDrag1 = particle._currentDrag2; particle._currentDrag2 = nextGradient.getFactor(); particle._currentDragGradient = currentGradient; } const drag = Lerp(particle._currentDrag1, particle._currentDrag2, scale); system._scaledDirection.scaleInPlace(1 - drag); }); } __name(_ProcessDragGradients, "_ProcessDragGradients"); function _CreateNoiseData(particle, system) { if (particle._randomNoiseCoordinates1) { particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random()); particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random()); } else { particle._randomNoiseCoordinates1 = new Vector3(Math.random(), Math.random(), Math.random()); particle._randomNoiseCoordinates2 = new Vector3(Math.random(), Math.random(), Math.random()); } } __name(_CreateNoiseData, "_CreateNoiseData"); function _ProcessNoise(particle, system) { const noiseTextureData = system._noiseTextureData; const noiseTextureSize = system._noiseTextureSize; if (noiseTextureData && noiseTextureSize && particle._randomNoiseCoordinates1) { const fetchedColorR = system._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData); const fetchedColorG = system._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData); const fetchedColorB = system._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData); const force = TmpVectors.Vector3[0]; const scaledForce = TmpVectors.Vector3[1]; force.copyFromFloats((2 * fetchedColorR - 1) * system.noiseStrength.x, (2 * fetchedColorG - 1) * system.noiseStrength.y, (2 * fetchedColorB - 1) * system.noiseStrength.z); force.scaleToRef(system._tempScaledUpdateSpeed, scaledForce); particle.direction.addInPlace(scaledForce); } } __name(_ProcessNoise, "_ProcessNoise"); function _ProcessGravity(particle, system) { system.gravity.scaleToRef(system._tempScaledUpdateSpeed, system._scaledGravity); particle.direction.addInPlace(system._scaledGravity); } __name(_ProcessGravity, "_ProcessGravity"); function _CreateSizeData(particle, system) { particle.size = RandomRange(system.minSize, system.maxSize); particle.scale.copyFromFloats(RandomRange(system.minScaleX, system.maxScaleX), RandomRange(system.minScaleY, system.maxScaleY)); } __name(_CreateSizeData, "_CreateSizeData"); function _CreateSizeGradientsData(particle, system) { particle._currentSizeGradient = system._sizeGradients[0]; particle._currentSize1 = particle._currentSizeGradient.getFactor(); particle.size = particle._currentSize1; if (system._sizeGradients.length > 1) { particle._currentSize2 = system._sizeGradients[1].getFactor(); } else { particle._currentSize2 = particle._currentSize1; } particle.scale.copyFromFloats(RandomRange(system.minScaleX, system.maxScaleX), RandomRange(system.minScaleY, system.maxScaleY)); } __name(_CreateSizeGradientsData, "_CreateSizeGradientsData"); function _CreateStartSizeGradientsData(particle, system) { const ratio = system._actualFrame / system.targetStopDuration; GradientHelper.GetCurrentGradient(ratio, system._startSizeGradients, (currentGradient, nextGradient, scale) => { if (currentGradient !== system._currentStartSizeGradient) { system._currentStartSize1 = system._currentStartSize2; system._currentStartSize2 = nextGradient.getFactor(); system._currentStartSizeGradient = currentGradient; } const value = Lerp(system._currentStartSize1, system._currentStartSize2, scale); particle.scale.scaleInPlace(value); }); } __name(_CreateStartSizeGradientsData, "_CreateStartSizeGradientsData"); function _ProcessSizeGradients(particle, system) { GradientHelper.GetCurrentGradient(system._ratio, system._sizeGradients, (currentGradient, nextGradient, scale) => { if (currentGradient !== particle._currentSizeGradient) { particle._currentSize1 = particle._currentSize2; particle._currentSize2 = nextGradient.getFactor(); particle._currentSizeGradient = currentGradient; } particle.size = Lerp(particle._currentSize1, particle._currentSize2, scale); }); } __name(_ProcessSizeGradients, "_ProcessSizeGradients"); function _CreateRampData(particle, system) { particle.remapData = new Vector4(0, 1, 0, 1); } __name(_CreateRampData, "_CreateRampData"); function _ProcessRemapGradients(particle, system) { if (system._colorRemapGradients && system._colorRemapGradients.length > 0) { GradientHelper.GetCurrentGradient(system._ratio, system._colorRemapGradients, (currentGradient, nextGradient, scale) => { const min = Lerp(currentGradient.factor1, nextGradient.factor1, scale); const max = Lerp(currentGradient.factor2, nextGradient.factor2, scale); particle.remapData.x = min; particle.remapData.y = max - min; }); } if (system._alphaRemapGradients && system._alphaRemapGradients.length > 0) { GradientHelper.GetCurrentGradient(system._ratio, system._alphaRemapGradients, (currentGradient, nextGradient, scale) => { const min = Lerp(currentGradient.factor1, nextGradient.factor1, scale); const max = Lerp(currentGradient.factor2, nextGradient.factor2, scale); particle.remapData.z = min; particle.remapData.w = max - min; }); } } __name(_ProcessRemapGradients, "_ProcessRemapGradients"); function _CreateLifeGradientsData(particle, system) { const ratio = Clamp(system._actualFrame / system.targetStopDuration); GradientHelper.GetCurrentGradient(ratio, system._lifeTimeGradients, (currentGradient, nextGradient) => { const factorGradient1 = currentGradient; const factorGradient2 = nextGradient; const lifeTime1 = factorGradient1.getFactor(); const lifeTime2 = factorGradient2.getFactor(); const gradient = (ratio - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient); particle.lifeTime = Lerp(lifeTime1, lifeTime2, gradient); }); system._emitPower = RandomRange(system.minEmitPower, system.maxEmitPower); } __name(_CreateLifeGradientsData, "_CreateLifeGradientsData"); function _CreateLifetimeData(particle, system) { particle.lifeTime = RandomRange(system.minLifeTime, system.maxLifeTime); system._emitPower = RandomRange(system.minEmitPower, system.maxEmitPower); } __name(_CreateLifetimeData, "_CreateLifetimeData"); function _CreateEmitPowerData(particle, system) { if (system._emitPower === 0) { if (!particle._initialDirection) { particle._initialDirection = particle.direction.clone(); } else { particle._initialDirection.copyFrom(particle.direction); } particle.direction.set(0, 0, 0); } else { particle._initialDirection = null; particle.direction.scaleInPlace(system._emitPower); } particle.direction.addInPlace(system._inheritedVelocityOffset); } __name(_CreateEmitPowerData, "_CreateEmitPowerData"); function _CreateAngleData(particle, system) { particle.angularSpeed = RandomRange(system.minAngularSpeed, system.maxAngularSpeed); particle.angle = RandomRange(system.minInitialRotation, system.maxInitialRotation); } __name(_CreateAngleData, "_CreateAngleData"); function _CreateAngleGradientsData(particle, system) { particle._currentAngularSpeedGradient = system._angularSpeedGradients[0]; particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor(); particle._currentAngularSpeed1 = particle.angularSpeed; if (system._angularSpeedGradients.length > 1) { particle._currentAngularSpeed2 = system._angularSpeedGradients[1].getFactor(); } else { particle._currentAngularSpeed2 = particle._currentAngularSpeed1; } particle.angle = RandomRange(system.minInitialRotation, system.maxInitialRotation); } __name(_CreateAngleGradientsData, "_CreateAngleGradientsData"); function _CreateSheetData(particle, system) { particle._initialStartSpriteCellId = system.startSpriteCellID; particle._initialEndSpriteCellId = system.endSpriteCellID; particle._initialSpriteCellLoop = system.spriteCellLoop; } __name(_CreateSheetData, "_CreateSheetData"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Queue/executionQueue.js function _ConnectBefore(newOne, activeOne) { newOne.previousItem = activeOne.previousItem; newOne.nextItem = activeOne; if (activeOne.previousItem) { activeOne.previousItem.nextItem = newOne; } activeOne.previousItem = newOne; } __name(_ConnectBefore, "_ConnectBefore"); function _ConnectAfter(newOne, activeOne) { newOne.previousItem = activeOne; newOne.nextItem = activeOne.nextItem; if (activeOne.nextItem) { activeOne.nextItem.previousItem = newOne; } activeOne.nextItem = newOne; } __name(_ConnectAfter, "_ConnectAfter"); function _ConnectAtTheEnd(newOne, root) { let activeOne = root; while (activeOne.nextItem) { activeOne = activeOne.nextItem; } newOne.previousItem = activeOne; newOne.nextItem = activeOne.nextItem; activeOne.nextItem = newOne; } __name(_ConnectAtTheEnd, "_ConnectAtTheEnd"); function _RemoveFromQueue(item) { if (item.previousItem) { item.previousItem.nextItem = item.nextItem; } if (item.nextItem) { item.nextItem.previousItem = item.previousItem; } } __name(_RemoveFromQueue, "_RemoveFromQueue"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/thinParticleSystem.js init_observable(); init_math_vector(); init_buffer(); init_engineStore(); init_drawWrapper(); init_math_color(); init_engine_alpha(); init_clipPlaneMaterialHelper(); init_materialHelper_functions(); init_math_scalar_functions(); init_imageProcessingConfiguration_functions(); var ThinParticleSystem = class _ThinParticleSystem extends BaseParticleSystem { static { __name(this, "ThinParticleSystem"); } /** * This function can be defined to specify initial direction for every new particle. * It by default use the emitterType defined function */ get startDirectionFunction() { return this._startDirectionFunction; } set startDirectionFunction(value) { if (this._startDirectionFunction === value) { return; } this._startDirectionFunction = value; if (value) { this._directionProcessing.process = _CreateCustomDirectionData; } else { this._directionProcessing.process = _CreateDirectionData; } } /** * This function can be defined to specify initial position for every new particle. * It by default use the emitterType defined function */ get startPositionFunction() { return this._startPositionFunction; } set startPositionFunction(value) { if (this._startPositionFunction === value) { return; } this._startPositionFunction = value; if (value) { this._positionCreation.process = _CreateCustomPositionData; } else { this._positionCreation.process = _CreatePositionData; } } /** * Sets a callback that will be triggered when the system is disposed */ set onDispose(callback) { if (this._onDisposeObserver) { this.onDisposeObservable.remove(this._onDisposeObserver); } this._onDisposeObserver = this.onDisposeObservable.add(callback); } /** * Gets a boolean indicating that the particle system was disposed */ get isDisposed() { return this._isDisposed; } /** Gets or sets a boolean indicating that ramp gradients must be used * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro#ramp-gradients */ get useRampGradients() { return this._useRampGradients; } set useRampGradients(value) { if (this._useRampGradients === value) { return; } this._useRampGradients = value; this._resetEffect(); if (value) { this._rampCreation = { process: _CreateRampData, previousItem: null, nextItem: null }; _ConnectAfter(this._rampCreation, this._colorDeadCreation); this._remapGradientProcessing = { process: _ProcessRemapGradients, previousItem: null, nextItem: null }; _ConnectAfter(this._remapGradientProcessing, this._gravityProcessing); } else { _RemoveFromQueue(this._rampCreation); _RemoveFromQueue(this._remapGradientProcessing); } } /** * Specifies if the particles are updated in emitter local space or world space */ get isLocal() { return this._isLocal; } set isLocal(value) { if (this._isLocal === value) { return; } this._isLocal = value; if (value) { this._isLocalCreation = { process: _CreateIsLocalData, previousItem: null, nextItem: null }; _ConnectAfter(this._isLocalCreation, this._positionCreation); } else { _RemoveFromQueue(this._isLocalCreation); } } /** * Gets the current list of active particles */ get particles() { return this._particles; } /** * Gets the shader language used in this material. */ get shaderLanguage() { return this._shaderLanguage; } /** @internal */ get _isAnimationSheetEnabled() { return this._animationSheetEnabled; } set _isAnimationSheetEnabled(value) { if (this._animationSheetEnabled === value) { return; } this._animationSheetEnabled = value; if (value) { this._sheetCreation = { process: _CreateSheetData, previousItem: null, nextItem: null }; _ConnectAfter(this._sheetCreation, this._colorDeadCreation); } else { _RemoveFromQueue(this._sheetCreation); } this._reset(); } /** * Gets the number of particles active at the same time. * @returns The number of active particles. */ getActiveCount() { return this._particles.length; } /** * Returns the string "ParticleSystem" * @returns a string containing the class name */ getClassName() { return "ParticleSystem"; } /** * Gets a boolean indicating that the system is stopping * @returns true if the system is currently stopping */ isStopping() { return this._stopped && this.isAlive(); } /** * Gets the custom effect used to render the particles * @param blendMode Blend mode for which the effect should be retrieved * @returns The effect */ getCustomEffect(blendMode = 0) { return this._customWrappers[blendMode]?.effect ?? this._customWrappers[0].effect; } _getCustomDrawWrapper(blendMode = 0) { return this._customWrappers[blendMode] ?? this._customWrappers[0]; } /** * Sets the custom effect used to render the particles * @param effect The effect to set * @param blendMode Blend mode for which the effect should be set */ setCustomEffect(effect, blendMode = 0) { this._customWrappers[blendMode] = new DrawWrapper(this._engine); this._customWrappers[blendMode].effect = effect; if (this._customWrappers[blendMode].drawContext) { this._customWrappers[blendMode].drawContext.useInstancing = this._useInstancing; } } /** * Observable that will be called just before the particles are drawn */ get onBeforeDrawParticlesObservable() { if (!this._onBeforeDrawParticlesObservable) { this._onBeforeDrawParticlesObservable = new Observable(); } return this._onBeforeDrawParticlesObservable; } /** * Gets the name of the particle vertex shader */ get vertexShaderName() { return "particles"; } /** * Gets the vertex buffers used by the particle system */ get vertexBuffers() { return this._vertexBuffers; } /** * Gets the index buffer used by the particle system (or null if no index buffer is used (if _useInstancing=true)) */ get indexBuffer() { return this._indexBuffer; } get noiseTexture() { return this._noiseTexture; } set noiseTexture(value) { if (this.noiseTexture === value) { return; } this._noiseTexture = value; if (!value) { _RemoveFromQueue(this._noiseCreation); _RemoveFromQueue(this._noiseProcessing); return; } this._noiseCreation = { process: _CreateNoiseData, previousItem: null, nextItem: null }; _ConnectAfter(this._noiseCreation, this._colorDeadCreation); this._noiseProcessing = { process: _ProcessNoise, previousItem: null, nextItem: null }; _ConnectAfter(this._noiseProcessing, this._positionProcessing); } /** * Instantiates a particle system. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. * @param name The name of the particle system * @param capacity The max number of particles alive at the same time * @param sceneOrEngine The scene the particle system belongs to or the engine to use if no scene * @param customEffect a custom effect used to change the way particles are rendered by default * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture * @param epsilon Offset used to render the particles * @param noUpdateQueue If true, the particle system will start with an empty update queue */ constructor(name260, capacity, sceneOrEngine, customEffect = null, isAnimationSheetEnabled = false, epsilon = 0.01, noUpdateQueue = false) { super(name260); this._emitterInverseWorldMatrix = Matrix.Identity(); this._startDirectionFunction = null; this._startPositionFunction = null; this._inheritedVelocityOffset = new Vector3(); this.onDisposeObservable = new Observable(); this.onStoppedObservable = new Observable(); this.onStartedObservable = new Observable(); this._noiseTextureSize = null; this._noiseTextureData = null; this._particles = new Array(); this._stockParticles = new Array(); this._newPartsExcess = 0; this._vertexBuffers = {}; this._scaledColorStep = new Color4(0, 0, 0, 0); this._colorDiff = new Color4(0, 0, 0, 0); this._scaledDirection = Vector3.Zero(); this._scaledGravity = Vector3.Zero(); this._currentRenderId = -1; this._useInstancing = false; this._isDisposed = false; this._started = false; this._stopped = false; this._actualFrame = 0; this._currentEmitRate1 = 0; this._currentEmitRate2 = 0; this._currentStartSize1 = 0; this._currentStartSize2 = 0; this.updateInAnimate = true; this._rawTextureWidth = 256; this._useRampGradients = false; this._updateQueueStart = null; this._startSizeCreation = null; this._createQueueStart = null; this._isLocal = false; this.isGPU = false; this._shaderLanguage = 0; this._onBeforeDrawParticlesObservable = null; this._emitFromParticle = (particle) => { }; this.recycleParticle = (particle) => { const lastParticle = this._particles.pop(); if (lastParticle !== particle) { lastParticle.copyTo(particle); } this._stockParticles.push(lastParticle); }; this._createParticle = () => { let particle; if (this._stockParticles.length !== 0) { particle = this._stockParticles.pop(); particle._reset(); } else { particle = new Particle(this); } this._prepareParticle(particle); return particle; }; this.paused = false; this._shadersLoaded = false; this._capacity = capacity; this._epsilon = epsilon; if (!sceneOrEngine || sceneOrEngine.getClassName() === "Scene") { this._scene = sceneOrEngine || EngineStore.LastCreatedScene; this._engine = this._scene.getEngine(); this.uniqueId = this._scene.getUniqueId(); this._scene.particleSystems.push(this); } else { this._engine = sceneOrEngine; this.defaultProjectionMatrix = Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange); } if (this._engine.getCaps().vertexArrayObject) { this._vertexArrayObject = null; } this._initShaderSourceAsync(); this._lifeTimeCreation = { process: _CreateLifetimeData, previousItem: null, nextItem: null }; this._positionCreation = { process: _CreatePositionData, previousItem: null, nextItem: null }; _ConnectAfter(this._positionCreation, this._lifeTimeCreation); this._directionCreation = { process: _CreateDirectionData, previousItem: null, nextItem: null }; _ConnectAfter(this._directionCreation, this._positionCreation); this._emitPowerCreation = { process: _CreateEmitPowerData, previousItem: null, nextItem: null }; _ConnectAfter(this._emitPowerCreation, this._directionCreation); this._sizeCreation = { process: _CreateSizeData, previousItem: null, nextItem: null }; _ConnectAfter(this._sizeCreation, this._emitPowerCreation); this._angleCreation = { process: _CreateAngleData, previousItem: null, nextItem: null }; _ConnectAfter(this._angleCreation, this._sizeCreation); this._colorCreation = { process: _CreateColorData, previousItem: null, nextItem: null }; _ConnectAfter(this._colorCreation, this._angleCreation); this._colorDeadCreation = { process: _CreateColorDeadData, previousItem: null, nextItem: null }; _ConnectAfter(this._colorDeadCreation, this._colorCreation); this._createQueueStart = this._lifeTimeCreation; if (!noUpdateQueue) { this._colorProcessing = { process: _ProcessColor, previousItem: null, nextItem: null }; this._angularSpeedProcessing = { process: _ProcessAngularSpeed, previousItem: null, nextItem: null }; _ConnectAfter(this._angularSpeedProcessing, this._colorProcessing); this._directionProcessing = { process: _ProcessDirection, previousItem: null, nextItem: null }; _ConnectAfter(this._directionProcessing, this._angularSpeedProcessing); this._positionProcessing = { process: _ProcessPosition, previousItem: null, nextItem: null }; _ConnectAfter(this._positionProcessing, this._directionProcessing); this._gravityProcessing = { process: _ProcessGravity, previousItem: null, nextItem: null }; _ConnectAfter(this._gravityProcessing, this._positionProcessing); this._updateQueueStart = this._colorProcessing; } this._isAnimationSheetEnabled = isAnimationSheetEnabled; this._attachImageProcessingConfiguration(null); this._customWrappers = { 0: new DrawWrapper(this._engine) }; this._customWrappers[0].effect = customEffect; this._drawWrappers = []; this._useInstancing = this._engine.getCaps().instancedArrays; this._createIndexBuffer(); this._createVertexBuffers(); this.particleEmitterType = new BoxParticleEmitter(); this.updateFunction = (particles) => { if (this.noiseTexture) { this._noiseTextureSize = this.noiseTexture.getSize(); this.noiseTexture.getContent()?.then((data) => { this._noiseTextureData = data; }); } const sameParticleArray = particles === this._particles; for (let index = 0; index < particles.length; index++) { const particle = particles[index]; this._tempScaledUpdateSpeed = this._scaledUpdateSpeed; const previousAge = particle.age; particle.age += this._tempScaledUpdateSpeed; if (particle.age > particle.lifeTime) { const diff = particle.age - previousAge; const oldDiff = particle.lifeTime - previousAge; this._tempScaledUpdateSpeed = oldDiff * this._tempScaledUpdateSpeed / diff; particle.age = particle.lifeTime; } this._ratio = particle.age / particle.lifeTime; this._directionScale = this._tempScaledUpdateSpeed; let currentQueueItem = this._updateQueueStart; while (currentQueueItem) { currentQueueItem.process(particle, this); currentQueueItem = currentQueueItem.nextItem; } if (this._isAnimationSheetEnabled && !noUpdateQueue) { particle.updateCellIndex(); } particle._inheritParticleInfoToSubEmitters(); if (particle.age >= particle.lifeTime) { this._emitFromParticle(particle); if (particle._attachedSubEmitters) { for (const subEmitter of particle._attachedSubEmitters) { subEmitter.particleSystem.disposeOnStop = true; subEmitter.particleSystem.stop(); } particle._attachedSubEmitters = null; } this.recycleParticle(particle); if (sameParticleArray) { index--; } continue; } } }; } serialize(serializeTexture) { throw new Error("Method not implemented."); } /** * Clones the particle system. * @param name The name of the cloned object * @param newEmitter The new emitter to use * @param cloneTexture Also clone the textures if true */ clone(name260, newEmitter, cloneTexture = false) { throw new Error("Method not implemented."); } _addFactorGradient(factorGradients, gradient, factor, factor2) { const newGradient = new FactorGradient(gradient, factor, factor2); factorGradients.push(newGradient); factorGradients.sort((a, b) => { if (a.gradient < b.gradient) { return -1; } else if (a.gradient > b.gradient) { return 1; } return 0; }); } _removeFactorGradient(factorGradients, gradient) { if (!factorGradients) { return; } let index = 0; for (const factorGradient of factorGradients) { if (factorGradient.gradient === gradient) { factorGradients.splice(index, 1); break; } index++; } } _syncLifeTimeCreation() { if (this.targetStopDuration && this._lifeTimeGradients && this._lifeTimeGradients.length > 0) { this._lifeTimeCreation.process = _CreateLifeGradientsData; return; } this._lifeTimeCreation.process = _CreateLifetimeData; } _syncStartSizeCreation() { if (this._startSizeGradients && this._startSizeGradients[0] && this.targetStopDuration) { if (!this._startSizeCreation) { this._startSizeCreation = { process: _CreateStartSizeGradientsData, previousItem: null, nextItem: null }; _ConnectAfter(this._startSizeCreation, this._sizeCreation); } return; } if (this._startSizeCreation) { _RemoveFromQueue(this._startSizeCreation); this._startSizeCreation = null; } } get targetStopDuration() { return this._targetStopDuration; } set targetStopDuration(value) { if (this.targetStopDuration === value) { return; } this._targetStopDuration = value; this._syncLifeTimeCreation(); this._syncStartSizeCreation(); } /** * Adds a new life time gradient * @param gradient defines the gradient to use (between 0 and 1) * @param factor defines the life time factor to affect to the specified gradient * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from * @returns the current particle system */ addLifeTimeGradient(gradient, factor, factor2) { if (!this._lifeTimeGradients) { this._lifeTimeGradients = []; } this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2); this._syncLifeTimeCreation(); return this; } /** * Remove a specific life time gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeLifeTimeGradient(gradient) { this._removeFactorGradient(this._lifeTimeGradients, gradient); this._syncLifeTimeCreation(); return this; } /** * Adds a new size gradient * @param gradient defines the gradient to use (between 0 and 1) * @param factor defines the size factor to affect to the specified gradient * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from * @returns the current particle system */ addSizeGradient(gradient, factor, factor2) { if (!this._sizeGradients) { this._sizeGradients = []; } if (this._sizeGradients.length === 0) { this._sizeCreation.process = _CreateSizeGradientsData; this._sizeGradientProcessing = { process: _ProcessSizeGradients, previousItem: null, nextItem: null }; _ConnectBefore(this._sizeGradientProcessing, this._gravityProcessing); } this._addFactorGradient(this._sizeGradients, gradient, factor, factor2); return this; } /** * Remove a specific size gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeSizeGradient(gradient) { this._removeFactorGradient(this._sizeGradients, gradient); if (this._sizeGradients?.length === 0) { _RemoveFromQueue(this._sizeGradientProcessing); this._sizeCreation.process = _CreateSizeData; } return this; } /** * Adds a new color remap gradient * @param gradient defines the gradient to use (between 0 and 1) * @param min defines the color remap minimal range * @param max defines the color remap maximal range * @returns the current particle system */ addColorRemapGradient(gradient, min, max) { if (!this._colorRemapGradients) { this._colorRemapGradients = []; } this._addFactorGradient(this._colorRemapGradients, gradient, min, max); return this; } /** * Remove a specific color remap gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeColorRemapGradient(gradient) { this._removeFactorGradient(this._colorRemapGradients, gradient); return this; } /** * Adds a new alpha remap gradient * @param gradient defines the gradient to use (between 0 and 1) * @param min defines the alpha remap minimal range * @param max defines the alpha remap maximal range * @returns the current particle system */ addAlphaRemapGradient(gradient, min, max) { if (!this._alphaRemapGradients) { this._alphaRemapGradients = []; } this._addFactorGradient(this._alphaRemapGradients, gradient, min, max); return this; } /** * Remove a specific alpha remap gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeAlphaRemapGradient(gradient) { this._removeFactorGradient(this._alphaRemapGradients, gradient); return this; } /** * Adds a new angular speed gradient * @param gradient defines the gradient to use (between 0 and 1) * @param factor defines the angular speed to affect to the specified gradient * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from * @returns the current particle system */ addAngularSpeedGradient(gradient, factor, factor2) { if (!this._angularSpeedGradients) { this._angularSpeedGradients = []; } if (this._angularSpeedGradients.length === 0) { this._angleCreation.process = _CreateAngleGradientsData; this._angularSpeedGradientProcessing = { process: _ProcessAngularSpeedGradients, previousItem: null, nextItem: null }; _ConnectBefore(this._angularSpeedGradientProcessing, this._angularSpeedProcessing); } this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2); return this; } /** * Remove a specific angular speed gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeAngularSpeedGradient(gradient) { this._removeFactorGradient(this._angularSpeedGradients, gradient); if (this._angularSpeedGradients?.length === 0) { this._angleCreation.process = _CreateAngleData; _RemoveFromQueue(this._angularSpeedGradientProcessing); } return this; } /** * Adds a new velocity gradient * @param gradient defines the gradient to use (between 0 and 1) * @param factor defines the velocity to affect to the specified gradient * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from * @returns the current particle system */ addVelocityGradient(gradient, factor, factor2) { if (!this._velocityGradients) { this._velocityGradients = []; } if (this._velocityGradients.length === 0) { this._velocityCreation = { process: _CreateVelocityGradients, previousItem: null, nextItem: null }; _ConnectAfter(this._velocityCreation, this._angleCreation); this._velocityGradientProcessing = { process: _ProcessVelocityGradients, previousItem: null, nextItem: null }; _ConnectBefore(this._velocityGradientProcessing, this._directionProcessing); } this._addFactorGradient(this._velocityGradients, gradient, factor, factor2); return this; } /** * Remove a specific velocity gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeVelocityGradient(gradient) { this._removeFactorGradient(this._velocityGradients, gradient); if (this._velocityGradients?.length === 0) { _RemoveFromQueue(this._velocityCreation); _RemoveFromQueue(this._velocityGradientProcessing); } return this; } /** * Adds a new limit velocity gradient * @param gradient defines the gradient to use (between 0 and 1) * @param factor defines the limit velocity value to affect to the specified gradient * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from * @returns the current particle system */ addLimitVelocityGradient(gradient, factor, factor2) { if (!this._limitVelocityGradients) { this._limitVelocityGradients = []; } if (this._limitVelocityGradients.length === 0) { this._limitVelocityCreation = { process: _CreateLimitVelocityGradients, previousItem: null, nextItem: null }; _ConnectAfter(this._limitVelocityCreation, this._angleCreation); this._limitVelocityGradientProcessing = { process: _ProcessLimitVelocityGradients, previousItem: null, nextItem: null }; _ConnectAfter(this._limitVelocityGradientProcessing, this._directionProcessing); } this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2); return this; } /** * Remove a specific limit velocity gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeLimitVelocityGradient(gradient) { this._removeFactorGradient(this._limitVelocityGradients, gradient); if (this._limitVelocityGradients?.length === 0) { _RemoveFromQueue(this._limitVelocityCreation); _RemoveFromQueue(this._limitVelocityGradientProcessing); } return this; } /** * Adds a new drag gradient * @param gradient defines the gradient to use (between 0 and 1) * @param factor defines the drag value to affect to the specified gradient * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from * @returns the current particle system */ addDragGradient(gradient, factor, factor2) { if (!this._dragGradients) { this._dragGradients = []; } if (this._dragGradients.length === 0) { this._dragCreation = { process: _CreateDragData, previousItem: null, nextItem: null }; _ConnectBefore(this._dragCreation, this._colorDeadCreation); this._dragGradientProcessing = { process: _ProcessDragGradients, previousItem: null, nextItem: null }; _ConnectBefore(this._dragGradientProcessing, this._positionProcessing); } this._addFactorGradient(this._dragGradients, gradient, factor, factor2); return this; } /** * Remove a specific drag gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeDragGradient(gradient) { this._removeFactorGradient(this._dragGradients, gradient); if (this._dragGradients?.length === 0) { _RemoveFromQueue(this._dragCreation); _RemoveFromQueue(this._dragGradientProcessing); } return this; } /** * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property) * @param gradient defines the gradient to use (between 0 and 1) * @param factor defines the emit rate value to affect to the specified gradient * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from * @returns the current particle system */ addEmitRateGradient(gradient, factor, factor2) { if (!this._emitRateGradients) { this._emitRateGradients = []; } this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2); return this; } /** * Remove a specific emit rate gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeEmitRateGradient(gradient) { this._removeFactorGradient(this._emitRateGradients, gradient); return this; } /** * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property) * @param gradient defines the gradient to use (between 0 and 1) * @param factor defines the start size value to affect to the specified gradient * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from * @returns the current particle system */ addStartSizeGradient(gradient, factor, factor2) { if (!this._startSizeGradients) { this._startSizeGradients = []; } this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2); this._syncStartSizeCreation(); return this; } /** * Remove a specific start size gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeStartSizeGradient(gradient) { this._removeFactorGradient(this._startSizeGradients, gradient); this._syncStartSizeCreation(); return this; } _createRampGradientTexture() { if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture || !this._scene) { return; } const data = new Uint8Array(this._rawTextureWidth * 4); const tmpColor = TmpColors.Color3[0]; for (let x = 0; x < this._rawTextureWidth; x++) { const ratio = x / this._rawTextureWidth; GradientHelper.GetCurrentGradient(ratio, this._rampGradients, (currentGradient, nextGradient, scale) => { Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor); data[x * 4] = tmpColor.r * 255; data[x * 4 + 1] = tmpColor.g * 255; data[x * 4 + 2] = tmpColor.b * 255; data[x * 4 + 3] = 255; }); } this._rampGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, 1); } /** * Gets the current list of ramp gradients. * You must use addRampGradient and removeRampGradient to update this list * @returns the list of ramp gradients */ getRampGradients() { return this._rampGradients; } /** Force the system to rebuild all gradients that need to be resync */ forceRefreshGradients() { this._syncRampGradientTexture(); } _syncRampGradientTexture() { if (!this._rampGradients) { return; } this._rampGradients.sort((a, b) => { if (a.gradient < b.gradient) { return -1; } else if (a.gradient > b.gradient) { return 1; } return 0; }); if (this._rampGradientsTexture) { this._rampGradientsTexture.dispose(); this._rampGradientsTexture = null; } this._createRampGradientTexture(); } /** * Adds a new ramp gradient used to remap particle colors * @param gradient defines the gradient to use (between 0 and 1) * @param color defines the color to affect to the specified gradient * @returns the current particle system */ addRampGradient(gradient, color) { if (!this._rampGradients) { this._rampGradients = []; } const rampGradient = new Color3Gradient(gradient, color); this._rampGradients.push(rampGradient); this._syncRampGradientTexture(); return this; } /** * Remove a specific ramp gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeRampGradient(gradient) { this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture); this._rampGradientsTexture = null; if (this._rampGradients && this._rampGradients.length > 0) { this._createRampGradientTexture(); } return this; } /** * Adds a new color gradient * @param gradient defines the gradient to use (between 0 and 1) * @param color1 defines the color to affect to the specified gradient * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from * @returns this particle system */ addColorGradient(gradient, color1, color2) { if (!this._colorGradients) { this._colorGradients = []; } if (this._colorGradients.length === 0) { this._colorCreation.process = _CreateColorGradientsData; this._colorProcessing.process = _ProcessColorGradients; } const colorGradient = new ColorGradient(gradient, color1, color2); this._colorGradients.push(colorGradient); this._colorGradients.sort((a, b) => { if (a.gradient < b.gradient) { return -1; } else if (a.gradient > b.gradient) { return 1; } return 0; }); return this; } /** * Remove a specific color gradient * @param gradient defines the gradient to remove * @returns this particle system */ removeColorGradient(gradient) { if (!this._colorGradients) { return this; } let index = 0; for (const colorGradient of this._colorGradients) { if (colorGradient.gradient === gradient) { this._colorGradients.splice(index, 1); break; } index++; } if (this._colorGradients.length === 0) { this._colorCreation.process = _CreateColorData; this._colorProcessing.process = _ProcessColor; } return this; } /** * Resets the draw wrappers cache */ resetDrawCache() { if (!this._drawWrappers) { return; } for (const drawWrappers of this._drawWrappers) { if (drawWrappers) { for (const drawWrapper of drawWrappers) { drawWrapper?.dispose(); } } } this._drawWrappers = []; } /** @internal */ _fetchR(u, v, width, height, pixels) { u = Math.abs(u) * 0.5 + 0.5; v = Math.abs(v) * 0.5 + 0.5; const wrappedU = u * width % width | 0; const wrappedV = v * height % height | 0; const position = (wrappedU + wrappedV * width) * 4; return pixels[position] / 255; } _reset() { this._resetEffect(); } _resetEffect() { if (this._vertexBuffer) { this._vertexBuffer.dispose(); this._vertexBuffer = null; } if (this._spriteBuffer) { this._spriteBuffer.dispose(); this._spriteBuffer = null; } if (this._vertexArrayObject) { this._engine.releaseVertexArrayObject(this._vertexArrayObject); this._vertexArrayObject = null; } this._createVertexBuffers(); } _createVertexBuffers() { this._vertexBufferSize = this._useInstancing ? 10 : 12; if (this._isAnimationSheetEnabled) { this._vertexBufferSize += 1; } if (!this._isBillboardBased || this.billboardMode === 8 || this.billboardMode === 9) { this._vertexBufferSize += 3; } if (this._useRampGradients) { this._vertexBufferSize += 4; } const engine = this._engine; const vertexSize = this._vertexBufferSize * (this._useInstancing ? 1 : 4); this._vertexData = new Float32Array(this._capacity * vertexSize); this._vertexBuffer = new Buffer2(engine, this._vertexData, true, vertexSize); let dataOffset = 0; const positions = this._vertexBuffer.createVertexBuffer(VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing); this._vertexBuffers[VertexBuffer.PositionKind] = positions; dataOffset += 3; const colors = this._vertexBuffer.createVertexBuffer(VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing); this._vertexBuffers[VertexBuffer.ColorKind] = colors; dataOffset += 4; const options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing); this._vertexBuffers["angle"] = options; dataOffset += 1; const size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing); this._vertexBuffers["size"] = size; dataOffset += 2; if (this._isAnimationSheetEnabled) { const cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing); this._vertexBuffers["cellIndex"] = cellIndexBuffer; dataOffset += 1; } if (!this._isBillboardBased || this.billboardMode === 8 || this.billboardMode === 9) { const directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing); this._vertexBuffers["direction"] = directionBuffer; dataOffset += 3; } if (this._useRampGradients) { const rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing); this._vertexBuffers["remapData"] = rampDataBuffer; dataOffset += 4; } let offsets; if (this._useInstancing) { const spriteData = new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]); this._spriteBuffer = new Buffer2(engine, spriteData, false, 2); offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2); } else { offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing); dataOffset += 2; } this._vertexBuffers["offset"] = offsets; this.resetDrawCache(); } _createIndexBuffer() { if (this._useInstancing) { this._linesIndexBufferUseInstancing = this._engine.createIndexBuffer(new Uint32Array([0, 1, 1, 3, 3, 2, 2, 0, 0, 3])); return; } const indices = []; const indicesWireframe = []; let index = 0; for (let count = 0; count < this._capacity; count++) { indices.push(index); indices.push(index + 1); indices.push(index + 2); indices.push(index); indices.push(index + 2); indices.push(index + 3); indicesWireframe.push(index, index + 1, index + 1, index + 2, index + 2, index + 3, index + 3, index, index, index + 3); index += 4; } this._indexBuffer = this._engine.createIndexBuffer(indices); this._linesIndexBuffer = this._engine.createIndexBuffer(indicesWireframe); } /** * Gets the maximum number of particles active at the same time. * @returns The max number of active particles. */ getCapacity() { return this._capacity; } /** * Gets whether there are still active particles in the system. * @returns True if it is alive, otherwise false. */ isAlive() { return this._alive; } /** * Gets if the system has been started. (Note: this will still be true after stop is called) * @returns True if it has been started, otherwise false. */ isStarted() { return this._started; } /** @internal */ _preStart() { } /** * Starts the particle system and begins to emit * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default) */ start(delay = this.startDelay) { if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) { throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set"; } if (delay) { setTimeout(() => { this.start(0); }, delay); return; } this._started = true; this._stopped = false; this._actualFrame = 0; this._preStart(); if (this._emitRateGradients) { if (this._emitRateGradients.length > 0) { this._currentEmitRateGradient = this._emitRateGradients[0]; this._currentEmitRate1 = this._currentEmitRateGradient.getFactor(); this._currentEmitRate2 = this._currentEmitRate1; } if (this._emitRateGradients.length > 1) { this._currentEmitRate2 = this._emitRateGradients[1].getFactor(); } } if (this._startSizeGradients) { if (this._startSizeGradients.length > 0) { this._currentStartSizeGradient = this._startSizeGradients[0]; this._currentStartSize1 = this._currentStartSizeGradient.getFactor(); this._currentStartSize2 = this._currentStartSize1; } if (this._startSizeGradients.length > 1) { this._currentStartSize2 = this._startSizeGradients[1].getFactor(); } } if (this.preWarmCycles) { if (this.emitter?.getClassName().indexOf("Mesh") !== -1) { this.emitter.computeWorldMatrix(true); } const noiseTextureAsProcedural = this.noiseTexture; if (noiseTextureAsProcedural && noiseTextureAsProcedural.onGeneratedObservable) { noiseTextureAsProcedural.onGeneratedObservable.addOnce(() => { setTimeout(() => { for (let index = 0; index < this.preWarmCycles; index++) { this.animate(true); noiseTextureAsProcedural.render(); } }); }); } else { for (let index = 0; index < this.preWarmCycles; index++) { this.animate(true); } } } if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) { this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop); } this.onStartedObservable.notifyObservers(this); } /** * Stops the particle system. * @param stopSubEmitters if true it will stop the current system and all created sub-Systems if false it will stop the current root system only, this param is used by the root particle system only. The default value is true. */ stop(stopSubEmitters = true) { if (this._stopped) { return; } this.onStoppedObservable.notifyObservers(this); this._stopped = true; this._postStop(stopSubEmitters); } /** @internal */ _postStop(_stopSubEmitters) { } // Animation sheet /** * Remove all active particles */ reset() { this._stockParticles.length = 0; this._particles.length = 0; } /** * @internal (for internal use only) */ _appendParticleVertex(index, particle, offsetX, offsetY) { let offset = index * this._vertexBufferSize; const floatingOriginOffset = TmpVectors.Vector3[0].copyFrom(this._scene?.floatingOriginOffset || Vector3.ZeroReadOnly); this._vertexData[offset++] = particle.position.x + this.worldOffset.x - floatingOriginOffset.x; this._vertexData[offset++] = particle.position.y + this.worldOffset.y - floatingOriginOffset.y; this._vertexData[offset++] = particle.position.z + this.worldOffset.z - floatingOriginOffset.z; this._vertexData[offset++] = particle.color.r; this._vertexData[offset++] = particle.color.g; this._vertexData[offset++] = particle.color.b; this._vertexData[offset++] = particle.color.a; this._vertexData[offset++] = particle.angle; this._vertexData[offset++] = particle.scale.x * particle.size; this._vertexData[offset++] = particle.scale.y * particle.size; if (this._isAnimationSheetEnabled) { this._vertexData[offset++] = particle.cellIndex; } if (!this._isBillboardBased) { if (particle._initialDirection) { let initialDirection = particle._initialDirection; if (this.isLocal) { Vector3.TransformNormalToRef(initialDirection, this._emitterWorldMatrix, TmpVectors.Vector3[0]); initialDirection = TmpVectors.Vector3[0]; } if (initialDirection.x === 0 && initialDirection.z === 0) { initialDirection.x = 1e-3; } this._vertexData[offset++] = initialDirection.x; this._vertexData[offset++] = initialDirection.y; this._vertexData[offset++] = initialDirection.z; } else { let direction = particle.direction; if (this.isLocal) { Vector3.TransformNormalToRef(direction, this._emitterWorldMatrix, TmpVectors.Vector3[0]); direction = TmpVectors.Vector3[0]; } if (direction.x === 0 && direction.z === 0) { direction.x = 1e-3; } this._vertexData[offset++] = direction.x; this._vertexData[offset++] = direction.y; this._vertexData[offset++] = direction.z; } } else if (this.billboardMode === 8 || this.billboardMode === 9) { this._vertexData[offset++] = particle.direction.x; this._vertexData[offset++] = particle.direction.y; this._vertexData[offset++] = particle.direction.z; } if (this._useRampGradients && particle.remapData) { this._vertexData[offset++] = particle.remapData.x; this._vertexData[offset++] = particle.remapData.y; this._vertexData[offset++] = particle.remapData.z; this._vertexData[offset++] = particle.remapData.w; } if (!this._useInstancing) { if (this._isAnimationSheetEnabled) { if (offsetX === 0) { offsetX = this._epsilon; } else if (offsetX === 1) { offsetX = 1 - this._epsilon; } if (offsetY === 0) { offsetY = this._epsilon; } else if (offsetY === 1) { offsetY = 1 - this._epsilon; } } this._vertexData[offset++] = offsetX; this._vertexData[offset++] = offsetY; } } /** @internal */ _prepareParticle(_particle) { } _createNewOnes(newParticles) { let particle; for (let index = 0; index < newParticles; index++) { if (this._particles.length === this._capacity) { break; } particle = this._createParticle(); this._particles.push(particle); let currentQueueItem = this._createQueueStart; while (currentQueueItem) { currentQueueItem.process(particle, this); currentQueueItem = currentQueueItem.nextItem; } particle._inheritParticleInfoToSubEmitters(); } } _update(newParticles) { this._alive = this._particles.length > 0; if (this.emitter.position) { const emitterMesh = this.emitter; this._emitterWorldMatrix = emitterMesh.getWorldMatrix(); } else { const emitterPosition = this.emitter; this._emitterWorldMatrix = Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z); } this._emitterWorldMatrix.invertToRef(this._emitterInverseWorldMatrix); this.updateFunction(this._particles); this._createNewOnes(newParticles); } /** * @internal */ static _GetAttributeNamesOrOptions(isAnimationSheetEnabled = false, isBillboardBased = false, useRampGradients = false) { const attributeNamesOrOptions = [VertexBuffer.PositionKind, VertexBuffer.ColorKind, "angle", "offset", "size"]; if (isAnimationSheetEnabled) { attributeNamesOrOptions.push("cellIndex"); } if (!isBillboardBased) { attributeNamesOrOptions.push("direction"); } if (useRampGradients) { attributeNamesOrOptions.push("remapData"); } return attributeNamesOrOptions; } /** * @internal */ static _GetEffectCreationOptions(isAnimationSheetEnabled = false, useLogarithmicDepth = false, applyFog = false) { const effectCreationOption = ["invView", "view", "projection", "textureMask", "translationPivot", "eyePosition"]; AddClipPlaneUniforms(effectCreationOption); if (isAnimationSheetEnabled) { effectCreationOption.push("particlesInfos"); } if (useLogarithmicDepth) { effectCreationOption.push("logarithmicDepthConstant"); } if (applyFog) { effectCreationOption.push("vFogInfos"); effectCreationOption.push("vFogColor"); } return effectCreationOption; } /** * Fill the defines array according to the current settings of the particle system * @param defines Array to be updated * @param blendMode blend mode to take into account when updating the array * @param fillImageProcessing fills the image processing defines */ fillDefines(defines, blendMode, fillImageProcessing = true) { if (this._scene) { PrepareStringDefinesForClipPlanes(this, this._scene, defines); if (this.applyFog && this._scene.fogEnabled && this._scene.fogMode !== 0) { defines.push("#define FOG"); } } if (this._isAnimationSheetEnabled) { defines.push("#define ANIMATESHEET"); } if (this.useLogarithmicDepth) { defines.push("#define LOGARITHMICDEPTH"); } if (blendMode === BaseParticleSystem.BLENDMODE_MULTIPLY) { defines.push("#define BLENDMULTIPLYMODE"); } if (this._useRampGradients) { defines.push("#define RAMPGRADIENT"); } if (this._isBillboardBased) { defines.push("#define BILLBOARD"); switch (this.billboardMode) { case 2: defines.push("#define BILLBOARDY"); break; case 8: case 9: defines.push("#define BILLBOARDSTRETCHED"); if (this.billboardMode === 9) { defines.push("#define BILLBOARDSTRETCHED_LOCAL"); } break; case 7: defines.push("#define BILLBOARDMODE_ALL"); break; default: break; } } if (fillImageProcessing && this._imageProcessingConfiguration) { this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines); defines.push(this._imageProcessingConfigurationDefines.toString()); } } /** * Fill the uniforms, attributes and samplers arrays according to the current settings of the particle system * @param uniforms Uniforms array to fill * @param attributes Attributes array to fill * @param samplers Samplers array to fill */ fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers) { attributes.push(..._ThinParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== 8 && this.billboardMode !== 9, this._useRampGradients)); uniforms.push(..._ThinParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled, this.useLogarithmicDepth, this.applyFog)); samplers.push("diffuseSampler", "rampSampler"); if (this._imageProcessingConfiguration) { PrepareUniformsForImageProcessing(uniforms, this._imageProcessingConfigurationDefines); PrepareSamplersForImageProcessing(samplers, this._imageProcessingConfigurationDefines); } } /** * @internal */ _getWrapper(blendMode) { const customWrapper = this._getCustomDrawWrapper(blendMode); if (customWrapper?.effect) { return customWrapper; } const defines = []; this.fillDefines(defines, blendMode); const currentRenderPassId = this._engine._features.supportRenderPasses ? this._engine.currentRenderPassId : 0; let drawWrappers = this._drawWrappers[currentRenderPassId]; if (!drawWrappers) { drawWrappers = this._drawWrappers[currentRenderPassId] = []; } let drawWrapper = drawWrappers[blendMode]; if (!drawWrapper) { drawWrapper = new DrawWrapper(this._engine); if (drawWrapper.drawContext) { drawWrapper.drawContext.useInstancing = this._useInstancing; } drawWrappers[blendMode] = drawWrapper; } const join = defines.join("\n"); if (drawWrapper.defines !== join) { const attributesNamesOrOptions = []; const effectCreationOption = []; const samplers = []; this.fillUniformsAttributesAndSamplerNames(effectCreationOption, attributesNamesOrOptions, samplers); drawWrapper.setEffect(this._engine.createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join, void 0, void 0, void 0, void 0, this._shaderLanguage), join); } return drawWrapper; } /** * Animates the particle system for the current frame by emitting new particles and or animating the living ones. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false) */ animate(preWarmOnly = false) { if (!this._started || this.paused) { return; } if (!preWarmOnly && this._scene) { if (!this.isReady()) { return; } if (this._currentRenderId === this._scene.getFrameId()) { return; } this._currentRenderId = this._scene.getFrameId(); } this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene?.getAnimationRatio() || 1); let newParticles; if (this.manualEmitCount > -1) { newParticles = this.manualEmitCount; this._newPartsExcess = 0; this.manualEmitCount = 0; } else { let rate = this.emitRate; if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) { const ratio = this._actualFrame / this.targetStopDuration; GradientHelper.GetCurrentGradient(ratio, this._emitRateGradients, (currentGradient, nextGradient, scale) => { if (currentGradient !== this._currentEmitRateGradient) { this._currentEmitRate1 = this._currentEmitRate2; this._currentEmitRate2 = nextGradient.getFactor(); this._currentEmitRateGradient = currentGradient; } rate = Lerp(this._currentEmitRate1, this._currentEmitRate2, scale); }); } newParticles = rate * this._scaledUpdateSpeed >> 0; this._newPartsExcess += rate * this._scaledUpdateSpeed - newParticles; } if (this._newPartsExcess > 1) { newParticles += this._newPartsExcess >> 0; this._newPartsExcess -= this._newPartsExcess >> 0; } this._alive = false; if (!this._stopped) { this._actualFrame += this._scaledUpdateSpeed; if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) { this.stop(); } } else { newParticles = 0; } this._update(newParticles); if (this._stopped) { if (!this._alive) { this._started = false; if (this.onAnimationEnd) { this.onAnimationEnd(); } if (this.disposeOnStop && this._scene) { this._scene._toBeDisposed.push(this); } } } if (!preWarmOnly) { let offset = 0; for (let index = 0; index < this._particles.length; index++) { const particle = this._particles[index]; this._appendParticleVertices(offset, particle); offset += this._useInstancing ? 1 : 4; } if (this._vertexBuffer) { this._vertexBuffer.updateDirectly(this._vertexData, 0, this._particles.length); } } if (this.manualEmitCount === 0 && this.disposeOnStop) { this.stop(); } } _appendParticleVertices(offset, particle) { this._appendParticleVertex(offset++, particle, 0, 0); if (!this._useInstancing) { this._appendParticleVertex(offset++, particle, 1, 0); this._appendParticleVertex(offset++, particle, 1, 1); this._appendParticleVertex(offset++, particle, 0, 1); } } /** * Rebuilds the particle system. */ rebuild() { if (this._engine.getCaps().vertexArrayObject) { this._vertexArrayObject = null; } this._createIndexBuffer(); this._spriteBuffer?._rebuild(); this._createVertexBuffers(); this.resetDrawCache(); } async _initShaderSourceAsync() { const engine = this._engine; if (engine.isWebGPU && !_ThinParticleSystem.ForceGLSL) { this._shaderLanguage = 1; await Promise.all([Promise.resolve().then(() => (init_particles_vertex(), particles_vertex_exports)), Promise.resolve().then(() => (init_particles_fragment(), particles_fragment_exports))]); } else { await Promise.all([Promise.resolve().then(() => (init_particles_vertex2(), particles_vertex_exports2)), Promise.resolve().then(() => (init_particles_fragment2(), particles_fragment_exports2))]); } this._shadersLoaded = true; } /** * Is this system ready to be used/rendered * @returns true if the system is ready */ isReady() { if (!this._shadersLoaded) { return false; } if (!this.emitter || this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) { return false; } if (this.blendMode !== BaseParticleSystem.BLENDMODE_MULTIPLYADD) { if (!this._getWrapper(this.blendMode).effect.isReady()) { return false; } } else { if (!this._getWrapper(BaseParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()) { return false; } if (!this._getWrapper(BaseParticleSystem.BLENDMODE_ADD).effect.isReady()) { return false; } } return true; } _render(blendMode) { const drawWrapper = this._getWrapper(blendMode); const effect = drawWrapper.effect; const engine = this._engine; engine.enableEffect(drawWrapper); const viewMatrix = this.defaultViewMatrix ?? this._scene.getViewMatrix(); effect.setTexture("diffuseSampler", this.particleTexture); effect.setMatrix("view", viewMatrix); effect.setMatrix("projection", this.defaultProjectionMatrix ?? this._scene.getProjectionMatrix()); if (this._isAnimationSheetEnabled && this.particleTexture) { const baseSize = this.particleTexture.getBaseSize(); effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, this.spriteCellWidth / baseSize.width); } effect.setVector2("translationPivot", this.translationPivot); effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a); if (this._isBillboardBased && this._scene) { const camera = this._scene.activeCamera; effect.setVector3("eyePosition", camera.globalPosition); } if (this._rampGradientsTexture) { if (!this._rampGradients || !this._rampGradients.length) { this._rampGradientsTexture.dispose(); this._rampGradientsTexture = null; } effect.setTexture("rampSampler", this._rampGradientsTexture); } const defines = effect.defines; if (this._scene) { BindClipPlane(effect, this, this._scene); if (this.applyFog) { BindFogParameters(this._scene, void 0, effect); } } if (defines.indexOf("#define BILLBOARDMODE_ALL") >= 0) { viewMatrix.invertToRef(TmpVectors.Matrix[0]); effect.setMatrix("invView", TmpVectors.Matrix[0]); } if (this._vertexArrayObject !== void 0) { if (this._scene?.forceWireframe) { engine.bindBuffers(this._vertexBuffers, this._linesIndexBufferUseInstancing, effect); } else { if (!this._vertexArrayObject) { this._vertexArrayObject = this._engine.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, effect); } this._engine.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer); } } else { if (!this._indexBuffer) { engine.bindBuffers(this._vertexBuffers, this._scene?.forceWireframe ? this._linesIndexBufferUseInstancing : null, effect); } else { engine.bindBuffers(this._vertexBuffers, this._scene?.forceWireframe ? this._linesIndexBuffer : this._indexBuffer, effect); } } if (this.useLogarithmicDepth && this._scene) { BindLogDepth(defines, effect, this._scene); } if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) { this._imageProcessingConfiguration.bind(effect); } this._setEngineBasedOnBlendMode(blendMode); if (this._onBeforeDrawParticlesObservable) { this._onBeforeDrawParticlesObservable.notifyObservers(effect); } if (this._useInstancing) { if (this._scene?.forceWireframe) { engine.drawElementsType(6, 0, 10, this._particles.length); } else { engine.drawArraysType(7, 0, 4, this._particles.length); } } else { if (this._scene?.forceWireframe) { engine.drawElementsType(1, 0, this._particles.length * 10); } else { engine.drawElementsType(0, 0, this._particles.length * 6); } } return this._particles.length; } /** * Renders the particle system in its current state. * @returns the current number of particles */ render() { if (!this.isReady() || !this._particles.length) { return 0; } const engine = this._engine; if (engine.setState) { engine.setState(false); if (this.forceDepthWrite) { engine.setDepthWrite(true); } } let outparticles = 0; if (this.blendMode === BaseParticleSystem.BLENDMODE_MULTIPLYADD) { outparticles = this._render(BaseParticleSystem.BLENDMODE_MULTIPLY) + this._render(BaseParticleSystem.BLENDMODE_ADD); } else { outparticles = this._render(this.blendMode); } this._engine.unbindInstanceAttributes(); this._engine.setAlphaMode(0); return outparticles; } /** @internal */ _onDispose(_disposeAttachedSubEmitters = false, _disposeEndSubEmitters = false) { } /** * Disposes the particle system and free the associated resources * @param disposeTexture defines if the particle texture must be disposed as well (true by default) * @param disposeAttachedSubEmitters defines if the attached sub-emitters must be disposed as well (false by default) * @param disposeEndSubEmitters defines if the end type sub-emitters must be disposed as well (false by default) */ dispose(disposeTexture = true, disposeAttachedSubEmitters = false, disposeEndSubEmitters = false) { this.resetDrawCache(); if (this._vertexBuffer) { this._vertexBuffer.dispose(); this._vertexBuffer = null; } if (this._spriteBuffer) { this._spriteBuffer.dispose(); this._spriteBuffer = null; } if (this._indexBuffer) { this._engine._releaseBuffer(this._indexBuffer); this._indexBuffer = null; } if (this._linesIndexBuffer) { this._engine._releaseBuffer(this._linesIndexBuffer); this._linesIndexBuffer = null; } if (this._linesIndexBufferUseInstancing) { this._engine._releaseBuffer(this._linesIndexBufferUseInstancing); this._linesIndexBufferUseInstancing = null; } if (this._vertexArrayObject) { this._engine.releaseVertexArrayObject(this._vertexArrayObject); this._vertexArrayObject = null; } if (disposeTexture && this.particleTexture) { this.particleTexture.dispose(); this.particleTexture = null; } if (disposeTexture && this.noiseTexture) { this.noiseTexture.dispose(); this.noiseTexture = null; } if (this._rampGradientsTexture) { this._rampGradientsTexture.dispose(); this._rampGradientsTexture = null; } this._onDispose(disposeAttachedSubEmitters, disposeEndSubEmitters); if (this._onBeforeDrawParticlesObservable) { this._onBeforeDrawParticlesObservable.clear(); } if (this._scene) { const index = this._scene.particleSystems.indexOf(this); if (index > -1) { this._scene.particleSystems.splice(index, 1); } this._scene._activeParticleSystems.dispose(); } this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); this.onStoppedObservable.clear(); this.onStartedObservable.clear(); this.reset(); this._isDisposed = true; } }; ThinParticleSystem.ForceGLSL = false; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/subEmitter.js init_math_vector(); init_devTools(); init_typeStore(); var SubEmitterType; (function(SubEmitterType2) { SubEmitterType2[SubEmitterType2["ATTACHED"] = 0] = "ATTACHED"; SubEmitterType2[SubEmitterType2["END"] = 1] = "END"; })(SubEmitterType || (SubEmitterType = {})); var SubEmitter = class _SubEmitter { static { __name(this, "SubEmitter"); } /** * Creates a sub emitter * @param particleSystem the particle system to be used by the sub emitter */ constructor(particleSystem) { this.particleSystem = particleSystem; this.type = 1; this.inheritDirection = false; this.inheritedVelocityAmount = 0; if (!particleSystem.emitter || !particleSystem.emitter.dispose) { const internalClass = GetClass("BABYLON.AbstractMesh"); particleSystem.emitter = new internalClass("SubemitterSystemEmitter", particleSystem.getScene()); particleSystem._disposeEmitterOnDispose = true; } } /** * Clones the sub emitter * @returns the cloned sub emitter */ clone() { let emitter = this.particleSystem.emitter; if (!emitter) { emitter = new Vector3(); } else if (emitter instanceof Vector3) { emitter = emitter.clone(); } else if (emitter.getClassName().indexOf("Mesh") !== -1) { const internalClass = GetClass("BABYLON.Mesh"); emitter = new internalClass("", emitter.getScene()); emitter.isVisible = false; } const clone = new _SubEmitter(this.particleSystem.clone(this.particleSystem.name, emitter)); clone.particleSystem.name += "Clone"; clone.type = this.type; clone.inheritDirection = this.inheritDirection; clone.inheritedVelocityAmount = this.inheritedVelocityAmount; clone.particleSystem._disposeEmitterOnDispose = true; clone.particleSystem.disposeOnStop = true; return clone; } /** * Serialize current object to a JSON object * @param serializeTexture defines if the texture must be serialized as well * @returns the serialized object */ serialize(serializeTexture = false) { const serializationObject = {}; serializationObject.type = this.type; serializationObject.inheritDirection = this.inheritDirection; serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount; serializationObject.particleSystem = this.particleSystem.serialize(serializeTexture); return serializationObject; } /** * @internal */ // eslint-disable-next-line @typescript-eslint/no-unused-vars static _ParseParticleSystem(system, sceneOrEngine, rootUrl, doNotStart = false) { throw _WarnImport("ParseParticle"); } /** * Creates a new SubEmitter from a serialized JSON version * @param serializationObject defines the JSON object to read from * @param sceneOrEngine defines the hosting scene or the hosting engine * @param rootUrl defines the rootUrl for data loading * @returns a new SubEmitter */ static Parse(serializationObject, sceneOrEngine, rootUrl) { const system = serializationObject.particleSystem; const subEmitter = new _SubEmitter(_SubEmitter._ParseParticleSystem(system, sceneOrEngine, rootUrl, true)); subEmitter.type = serializationObject.type; subEmitter.inheritDirection = serializationObject.inheritDirection; subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount; subEmitter.particleSystem._isSubEmitter = true; return subEmitter; } /** Release associated resources */ dispose() { this.particleSystem.dispose(); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/EmitterTypes/meshParticleEmitter.js init_deepCopier(); init_math_vector(); init_math_scalar_functions(); init_buffer(); var MeshParticleEmitter = class _MeshParticleEmitter { static { __name(this, "MeshParticleEmitter"); } /** Defines the mesh to use as source */ get mesh() { return this._mesh; } set mesh(value) { if (this._mesh === value) { return; } this._mesh = value; if (value) { this._indices = value.getIndices(); this._positions = value.getVerticesData(VertexBuffer.PositionKind); this._normals = value.getVerticesData(VertexBuffer.NormalKind); } else { this._indices = null; this._positions = null; this._normals = null; } } /** * Creates a new instance MeshParticleEmitter * @param mesh defines the mesh to use as source */ constructor(mesh = null) { this._indices = null; this._positions = null; this._normals = null; this._storedNormal = Vector3.Zero(); this._mesh = null; this.direction1 = new Vector3(0, 1, 0); this.direction2 = new Vector3(0, 1, 0); this.useMeshNormalsForDirection = true; this.mesh = mesh; } /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param directionToUpdate is the direction vector to update with the result * @param particle is the particle we are computed the direction for * @param isLocal defines if the direction should be set in local space */ startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { if (this.useMeshNormalsForDirection && this._normals) { Vector3.TransformNormalToRef(this._storedNormal, worldMatrix, directionToUpdate); return; } const randX = RandomRange(this.direction1.x, this.direction2.x); const randY = RandomRange(this.direction1.y, this.direction2.y); const randZ = RandomRange(this.direction1.z, this.direction2.z); if (isLocal) { directionToUpdate.copyFromFloats(randX, randY, randZ); return; } Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); } /** * Called by the particle System when the position is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param positionToUpdate is the position vector to update with the result * @param particle is the particle we are computed the position for * @param isLocal defines if the position should be set in local space */ startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { if (!this._indices || !this._positions) { return; } const randomFaceIndex = 3 * (Math.random() * (this._indices.length / 3) | 0); const bu = Math.random(); const bv = Math.random() * (1 - bu); const bw = 1 - bu - bv; const faceIndexA = this._indices[randomFaceIndex]; const faceIndexB = this._indices[randomFaceIndex + 1]; const faceIndexC = this._indices[randomFaceIndex + 2]; const vertexA = TmpVectors.Vector3[0]; const vertexB = TmpVectors.Vector3[1]; const vertexC = TmpVectors.Vector3[2]; const randomVertex = TmpVectors.Vector3[3]; Vector3.FromArrayToRef(this._positions, faceIndexA * 3, vertexA); Vector3.FromArrayToRef(this._positions, faceIndexB * 3, vertexB); Vector3.FromArrayToRef(this._positions, faceIndexC * 3, vertexC); randomVertex.x = bu * vertexA.x + bv * vertexB.x + bw * vertexC.x; randomVertex.y = bu * vertexA.y + bv * vertexB.y + bw * vertexC.y; randomVertex.z = bu * vertexA.z + bv * vertexB.z + bw * vertexC.z; if (isLocal) { positionToUpdate.copyFromFloats(randomVertex.x, randomVertex.y, randomVertex.z); } else { Vector3.TransformCoordinatesFromFloatsToRef(randomVertex.x, randomVertex.y, randomVertex.z, worldMatrix, positionToUpdate); } if (this.useMeshNormalsForDirection && this._normals) { Vector3.FromArrayToRef(this._normals, faceIndexA * 3, vertexA); Vector3.FromArrayToRef(this._normals, faceIndexB * 3, vertexB); Vector3.FromArrayToRef(this._normals, faceIndexC * 3, vertexC); this._storedNormal.x = bu * vertexA.x + bv * vertexB.x + bw * vertexC.x; this._storedNormal.y = bu * vertexA.y + bv * vertexB.y + bw * vertexC.y; this._storedNormal.z = bu * vertexA.z + bv * vertexB.z + bw * vertexC.z; } } /** * Clones the current emitter and returns a copy of it * @returns the new emitter */ clone() { const newOne = new _MeshParticleEmitter(this.mesh); DeepCopier.DeepCopy(this, newOne); return newOne; } /** * Called by the GPUParticleSystem to setup the update shader * @param uboOrEffect defines the update shader */ applyToShader(uboOrEffect) { uboOrEffect.setVector3("direction1", this.direction1); uboOrEffect.setVector3("direction2", this.direction2); } /** * Creates the structure of the ubo for this particle emitter * @param ubo ubo to create the structure for */ buildUniformLayout(ubo) { ubo.addUniform("direction1", 3); ubo.addUniform("direction2", 3); } /** * Returns a string to use to update the GPU particles update shader * @returns a string containing the defines string */ getEffectDefines() { return ""; } /** * Returns the string "BoxParticleEmitter" * @returns a string containing the class name */ getClassName() { return "MeshParticleEmitter"; } /** * Serializes the particle system to a JSON object. * @returns the JSON object */ serialize() { const serializationObject = {}; serializationObject.type = this.getClassName(); serializationObject.direction1 = this.direction1.asArray(); serializationObject.direction2 = this.direction2.asArray(); serializationObject.meshId = this.mesh?.id; serializationObject.useMeshNormalsForDirection = this.useMeshNormalsForDirection; return serializationObject; } /** * Parse properties from a JSON object * @param serializationObject defines the JSON object * @param scene defines the hosting scene */ parse(serializationObject, scene) { Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1); Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2); if (serializationObject.meshId && scene) { this.mesh = scene.getLastMeshById(serializationObject.meshId); } this.useMeshNormalsForDirection = serializationObject.useMeshNormalsForDirection; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/EmitterTypes/customParticleEmitter.js init_deepCopier(); init_math_vector(); var CustomParticleEmitter = class _CustomParticleEmitter { static { __name(this, "CustomParticleEmitter"); } /** * Creates a new instance CustomParticleEmitter */ constructor() { this.particlePositionGenerator = () => { }; this.particleDestinationGenerator = () => { }; this.particleDirectionGenerator = () => { }; } /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param directionToUpdate is the direction vector to update with the result * @param particle is the particle we are computed the direction for * @param isLocal defines if the direction should be set in local space */ startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { const tmpVector = TmpVectors.Vector3[0]; if (this.particleDirectionGenerator) { this.particleDirectionGenerator(-1, particle, tmpVector); } else if (this.particleDestinationGenerator) { this.particleDestinationGenerator(-1, particle, tmpVector); const diffVector = TmpVectors.Vector3[1]; tmpVector.subtractToRef(particle.position, diffVector); diffVector.scaleToRef(1 / particle.lifeTime, tmpVector); } else { tmpVector.set(0, 0, 0); } if (isLocal) { directionToUpdate.copyFrom(tmpVector); return; } Vector3.TransformNormalToRef(tmpVector, worldMatrix, directionToUpdate); } /** * Called by the particle System when the position is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param positionToUpdate is the position vector to update with the result * @param particle is the particle we are computed the position for * @param isLocal defines if the position should be set in local space */ startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { const tmpVector = TmpVectors.Vector3[0]; if (this.particlePositionGenerator) { this.particlePositionGenerator(-1, particle, tmpVector); } else { tmpVector.set(0, 0, 0); } if (isLocal) { positionToUpdate.copyFrom(tmpVector); return; } Vector3.TransformCoordinatesToRef(tmpVector, worldMatrix, positionToUpdate); } /** * Clones the current emitter and returns a copy of it * @returns the new emitter */ clone() { const newOne = new _CustomParticleEmitter(); DeepCopier.DeepCopy(this, newOne); return newOne; } /** * Called by the GPUParticleSystem to setup the update shader * @param uboOrEffect defines the update shader */ // eslint-disable-next-line @typescript-eslint/no-unused-vars applyToShader(uboOrEffect) { } /** * Creates the structure of the ubo for this particle emitter * @param ubo ubo to create the structure for */ // eslint-disable-next-line @typescript-eslint/no-unused-vars buildUniformLayout(ubo) { } /** * Returns a string to use to update the GPU particles update shader * @returns a string containing the defines string */ getEffectDefines() { return "#define CUSTOMEMITTER"; } /** * Returns the string "PointParticleEmitter" * @returns a string containing the class name */ getClassName() { return "CustomParticleEmitter"; } /** * Serializes the particle system to a JSON object. * @returns the JSON object */ serialize() { const serializationObject = {}; serializationObject.type = this.getClassName(); serializationObject.particlePositionGenerator = this.particlePositionGenerator; serializationObject.particleDestinationGenerator = this.particleDestinationGenerator; return serializationObject; } /** * Parse properties from a JSON object * @param serializationObject defines the JSON object */ parse(serializationObject) { if (serializationObject.particlePositionGenerator) { this.particlePositionGenerator = serializationObject.particlePositionGenerator; } if (serializationObject.particleDestinationGenerator) { this.particleDestinationGenerator = serializationObject.particleDestinationGenerator; } } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/EmitterTypes/pointParticleEmitter.js init_deepCopier(); init_math_vector(); init_math_scalar_functions(); var PointParticleEmitter = class _PointParticleEmitter { static { __name(this, "PointParticleEmitter"); } /** * Creates a new instance PointParticleEmitter */ constructor() { this.direction1 = new Vector3(0, 1, 0); this.direction2 = new Vector3(0, 1, 0); } /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param directionToUpdate is the direction vector to update with the result * @param particle is the particle we are computed the direction for * @param isLocal defines if the direction should be set in local space */ startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { const randX = RandomRange(this.direction1.x, this.direction2.x); const randY = RandomRange(this.direction1.y, this.direction2.y); const randZ = RandomRange(this.direction1.z, this.direction2.z); if (isLocal) { directionToUpdate.copyFromFloats(randX, randY, randZ); return; } Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); } /** * Called by the particle System when the position is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param positionToUpdate is the position vector to update with the result * @param particle is the particle we are computed the position for * @param isLocal defines if the position should be set in local space */ startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { if (isLocal) { positionToUpdate.copyFromFloats(0, 0, 0); return; } Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate); } /** * Clones the current emitter and returns a copy of it * @returns the new emitter */ clone() { const newOne = new _PointParticleEmitter(); DeepCopier.DeepCopy(this, newOne); return newOne; } /** * Called by the GPUParticleSystem to setup the update shader * @param uboOrEffect defines the update shader */ applyToShader(uboOrEffect) { uboOrEffect.setVector3("direction1", this.direction1); uboOrEffect.setVector3("direction2", this.direction2); } /** * Creates the structure of the ubo for this particle emitter * @param ubo ubo to create the structure for */ buildUniformLayout(ubo) { ubo.addUniform("direction1", 3); ubo.addUniform("direction2", 3); } /** * Returns a string to use to update the GPU particles update shader * @returns a string containing the defines string */ getEffectDefines() { return "#define POINTEMITTER"; } /** * Returns the string "PointParticleEmitter" * @returns a string containing the class name */ getClassName() { return "PointParticleEmitter"; } /** * Serializes the particle system to a JSON object. * @returns the JSON object */ serialize() { const serializationObject = {}; serializationObject.type = this.getClassName(); serializationObject.direction1 = this.direction1.asArray(); serializationObject.direction2 = this.direction2.asArray(); return serializationObject; } /** * Parse properties from a JSON object * @param serializationObject defines the JSON object */ parse(serializationObject) { Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1); Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/EmitterTypes/hemisphericParticleEmitter.js init_deepCopier(); init_math_vector(); init_math_scalar_functions(); var HemisphericParticleEmitter = class _HemisphericParticleEmitter { static { __name(this, "HemisphericParticleEmitter"); } /** * Creates a new instance HemisphericParticleEmitter * @param radius the radius of the emission hemisphere (1 by default) * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default) * @param directionRandomizer defines how much to randomize the particle direction [0-1] */ constructor(radius = 1, radiusRange = 1, directionRandomizer = 0) { this.radius = radius; this.radiusRange = radiusRange; this.directionRandomizer = directionRandomizer; } /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param directionToUpdate is the direction vector to update with the result * @param particle is the particle we are computed the direction for * @param isLocal defines if the direction should be set in local space */ startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { const direction = particle.position.subtract(worldMatrix.getTranslation()).normalize(); const randX = RandomRange(0, this.directionRandomizer); const randY = RandomRange(0, this.directionRandomizer); const randZ = RandomRange(0, this.directionRandomizer); direction.x += randX; direction.y += randY; direction.z += randZ; direction.normalize(); if (isLocal) { directionToUpdate.copyFrom(direction); return; } Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate); } /** * Called by the particle System when the position is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param positionToUpdate is the position vector to update with the result * @param particle is the particle we are computed the position for * @param isLocal defines if the position should be set in local space */ startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { const randRadius = this.radius - RandomRange(0, this.radius * this.radiusRange); const v = RandomRange(0, 1); const phi = RandomRange(0, 2 * Math.PI); const theta = Math.acos(2 * v - 1); const randX = randRadius * Math.cos(phi) * Math.sin(theta); const randY = randRadius * Math.cos(theta); const randZ = randRadius * Math.sin(phi) * Math.sin(theta); if (isLocal) { positionToUpdate.copyFromFloats(randX, Math.abs(randY), randZ); return; } Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate); } /** * Clones the current emitter and returns a copy of it * @returns the new emitter */ clone() { const newOne = new _HemisphericParticleEmitter(this.radius, this.directionRandomizer); DeepCopier.DeepCopy(this, newOne); return newOne; } /** * Called by the GPUParticleSystem to setup the update shader * @param uboOrEffect defines the update shader */ applyToShader(uboOrEffect) { uboOrEffect.setFloat("radius", this.radius); uboOrEffect.setFloat("radiusRange", this.radiusRange); uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer); } /** * Creates the structure of the ubo for this particle emitter * @param ubo ubo to create the structure for */ buildUniformLayout(ubo) { ubo.addUniform("radius", 1); ubo.addUniform("radiusRange", 1); ubo.addUniform("directionRandomizer", 1); } /** * Returns a string to use to update the GPU particles update shader * @returns a string containing the defines string */ getEffectDefines() { return "#define HEMISPHERICEMITTER"; } /** * Returns the string "HemisphericParticleEmitter" * @returns a string containing the class name */ getClassName() { return "HemisphericParticleEmitter"; } /** * Serializes the particle system to a JSON object. * @returns the JSON object */ serialize() { const serializationObject = {}; serializationObject.type = this.getClassName(); serializationObject.radius = this.radius; serializationObject.radiusRange = this.radiusRange; serializationObject.directionRandomizer = this.directionRandomizer; return serializationObject; } /** * Parse properties from a JSON object * @param serializationObject defines the JSON object */ parse(serializationObject) { this.radius = serializationObject.radius; this.radiusRange = serializationObject.radiusRange; this.directionRandomizer = serializationObject.directionRandomizer; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/EmitterTypes/sphereParticleEmitter.js init_math_vector(); init_math_scalar_functions(); init_deepCopier(); var SphereParticleEmitter = class _SphereParticleEmitter { static { __name(this, "SphereParticleEmitter"); } /** * Creates a new instance SphereParticleEmitter * @param radius the radius of the emission sphere (1 by default) * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default) * @param directionRandomizer defines how much to randomize the particle direction [0-1] */ constructor(radius = 1, radiusRange = 1, directionRandomizer = 0) { this.radius = radius; this.radiusRange = radiusRange; this.directionRandomizer = directionRandomizer; } /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param directionToUpdate is the direction vector to update with the result * @param particle is the particle we are computed the direction for * @param isLocal defines if the direction should be set in local space */ startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { const direction = particle.position.subtract(worldMatrix.getTranslation()).normalize(); const randX = RandomRange(0, this.directionRandomizer); const randY = RandomRange(0, this.directionRandomizer); const randZ = RandomRange(0, this.directionRandomizer); direction.x += randX; direction.y += randY; direction.z += randZ; direction.normalize(); if (isLocal) { directionToUpdate.copyFrom(direction); return; } Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate); } /** * Called by the particle System when the position is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param positionToUpdate is the position vector to update with the result * @param particle is the particle we are computed the position for * @param isLocal defines if the position should be set in local space */ startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { const randRadius = this.radius - RandomRange(0, this.radius * this.radiusRange); const v = RandomRange(0, 1); const phi = RandomRange(0, 2 * Math.PI); const theta = Math.acos(2 * v - 1); const randX = randRadius * Math.cos(phi) * Math.sin(theta); const randY = randRadius * Math.cos(theta); const randZ = randRadius * Math.sin(phi) * Math.sin(theta); if (isLocal) { positionToUpdate.copyFromFloats(randX, randY, randZ); return; } Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate); } /** * Clones the current emitter and returns a copy of it * @returns the new emitter */ clone() { const newOne = new _SphereParticleEmitter(this.radius, this.directionRandomizer); DeepCopier.DeepCopy(this, newOne); return newOne; } /** * Called by the GPUParticleSystem to setup the update shader * @param uboOrEffect defines the update shader */ applyToShader(uboOrEffect) { uboOrEffect.setFloat("radius", this.radius); uboOrEffect.setFloat("radiusRange", this.radiusRange); uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer); } /** * Creates the structure of the ubo for this particle emitter * @param ubo ubo to create the structure for */ buildUniformLayout(ubo) { ubo.addUniform("radius", 1); ubo.addUniform("radiusRange", 1); ubo.addUniform("directionRandomizer", 1); } /** * Returns a string to use to update the GPU particles update shader * @returns a string containing the defines string */ getEffectDefines() { return "#define SPHEREEMITTER"; } /** * Returns the string "SphereParticleEmitter" * @returns a string containing the class name */ getClassName() { return "SphereParticleEmitter"; } /** * Serializes the particle system to a JSON object. * @returns the JSON object */ serialize() { const serializationObject = {}; serializationObject.type = this.getClassName(); serializationObject.radius = this.radius; serializationObject.radiusRange = this.radiusRange; serializationObject.directionRandomizer = this.directionRandomizer; return serializationObject; } /** * Parse properties from a JSON object * @param serializationObject defines the JSON object */ parse(serializationObject) { this.radius = serializationObject.radius; this.radiusRange = serializationObject.radiusRange; this.directionRandomizer = serializationObject.directionRandomizer; } }; var SphereDirectedParticleEmitter = class _SphereDirectedParticleEmitter extends SphereParticleEmitter { static { __name(this, "SphereDirectedParticleEmitter"); } /** * Creates a new instance SphereDirectedParticleEmitter * @param radius the radius of the emission sphere (1 by default) * @param direction1 the min limit of the emission direction (up vector by default) * @param direction2 the max limit of the emission direction (up vector by default) */ constructor(radius = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { super(radius); this.direction1 = direction1; this.direction2 = direction2; } /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param directionToUpdate is the direction vector to update with the result */ startDirectionFunction(worldMatrix, directionToUpdate) { const randX = RandomRange(this.direction1.x, this.direction2.x); const randY = RandomRange(this.direction1.y, this.direction2.y); const randZ = RandomRange(this.direction1.z, this.direction2.z); Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); } /** * Clones the current emitter and returns a copy of it * @returns the new emitter */ clone() { const newOne = new _SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2); DeepCopier.DeepCopy(this, newOne); return newOne; } /** * Called by the GPUParticleSystem to setup the update shader * @param uboOrEffect defines the update shader */ applyToShader(uboOrEffect) { uboOrEffect.setFloat("radius", this.radius); uboOrEffect.setFloat("radiusRange", this.radiusRange); uboOrEffect.setVector3("direction1", this.direction1); uboOrEffect.setVector3("direction2", this.direction2); } /** * Creates the structure of the ubo for this particle emitter * @param ubo ubo to create the structure for */ buildUniformLayout(ubo) { ubo.addUniform("radius", 1); ubo.addUniform("radiusRange", 1); ubo.addUniform("direction1", 3); ubo.addUniform("direction2", 3); } /** * Returns a string to use to update the GPU particles update shader * @returns a string containing the defines string */ getEffectDefines() { return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER"; } /** * Returns the string "SphereDirectedParticleEmitter" * @returns a string containing the class name */ getClassName() { return "SphereDirectedParticleEmitter"; } /** * Serializes the particle system to a JSON object. * @returns the JSON object */ serialize() { const serializationObject = super.serialize(); serializationObject.direction1 = this.direction1.asArray(); serializationObject.direction2 = this.direction2.asArray(); return serializationObject; } /** * Parse properties from a JSON object * @param serializationObject defines the JSON object */ parse(serializationObject) { super.parse(serializationObject); this.direction1.copyFrom(serializationObject.direction1); this.direction2.copyFrom(serializationObject.direction2); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/EmitterTypes/cylinderParticleEmitter.js init_math_vector(); init_math_scalar_functions(); init_deepCopier(); var CylinderParticleEmitter = class _CylinderParticleEmitter { static { __name(this, "CylinderParticleEmitter"); } /** * Creates a new instance CylinderParticleEmitter * @param radius the radius of the emission cylinder (1 by default) * @param height the height of the emission cylinder (1 by default) * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default) * @param directionRandomizer defines how much to randomize the particle direction [0-1] */ constructor(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) { this.radius = radius; this.height = height; this.radiusRange = radiusRange; this.directionRandomizer = directionRandomizer; this._tempVector = Vector3.Zero(); } /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param directionToUpdate is the direction vector to update with the result * @param particle is the particle we are computed the direction for * @param isLocal defines if the direction should be set in local space * @param inverseWorldMatrix defines the inverted world matrix to use if isLocal is false */ startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal, inverseWorldMatrix) { particle.position.subtractToRef(worldMatrix.getTranslation(), this._tempVector); this._tempVector.normalize(); Vector3.TransformNormalToRef(this._tempVector, inverseWorldMatrix, this._tempVector); const randY = RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2); let angle = Math.atan2(this._tempVector.x, this._tempVector.z); angle += RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer; this._tempVector.y = randY; this._tempVector.x = Math.sin(angle); this._tempVector.z = Math.cos(angle); this._tempVector.normalize(); if (isLocal) { directionToUpdate.copyFrom(this._tempVector); return; } Vector3.TransformNormalFromFloatsToRef(this._tempVector.x, this._tempVector.y, this._tempVector.z, worldMatrix, directionToUpdate); } /** * Called by the particle System when the position is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param positionToUpdate is the position vector to update with the result * @param particle is the particle we are computed the position for * @param isLocal defines if the position should be set in local space */ startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { const yPos = RandomRange(-this.height / 2, this.height / 2); const angle = RandomRange(0, 2 * Math.PI); const radiusDistribution = RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1); const positionRadius = Math.sqrt(radiusDistribution) * this.radius; const xPos = positionRadius * Math.cos(angle); const zPos = positionRadius * Math.sin(angle); if (isLocal) { positionToUpdate.copyFromFloats(xPos, yPos, zPos); return; } Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate); } /** * Clones the current emitter and returns a copy of it * @returns the new emitter */ clone() { const newOne = new _CylinderParticleEmitter(this.radius, this.directionRandomizer); DeepCopier.DeepCopy(this, newOne); return newOne; } /** * Called by the GPUParticleSystem to setup the update shader * @param uboOrEffect defines the update shader */ applyToShader(uboOrEffect) { uboOrEffect.setFloat("radius", this.radius); uboOrEffect.setFloat("height", this.height); uboOrEffect.setFloat("radiusRange", this.radiusRange); uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer); } /** * Creates the structure of the ubo for this particle emitter * @param ubo ubo to create the structure for */ buildUniformLayout(ubo) { ubo.addUniform("radius", 1); ubo.addUniform("height", 1); ubo.addUniform("radiusRange", 1); ubo.addUniform("directionRandomizer", 1); } /** * Returns a string to use to update the GPU particles update shader * @returns a string containing the defines string */ getEffectDefines() { return "#define CYLINDEREMITTER"; } /** * Returns the string "CylinderParticleEmitter" * @returns a string containing the class name */ getClassName() { return "CylinderParticleEmitter"; } /** * Serializes the particle system to a JSON object. * @returns the JSON object */ serialize() { const serializationObject = {}; serializationObject.type = this.getClassName(); serializationObject.radius = this.radius; serializationObject.height = this.height; serializationObject.radiusRange = this.radiusRange; serializationObject.directionRandomizer = this.directionRandomizer; return serializationObject; } /** * Parse properties from a JSON object * @param serializationObject defines the JSON object */ parse(serializationObject) { this.radius = serializationObject.radius; this.height = serializationObject.height; this.radiusRange = serializationObject.radiusRange; this.directionRandomizer = serializationObject.directionRandomizer; } }; var CylinderDirectedParticleEmitter = class _CylinderDirectedParticleEmitter extends CylinderParticleEmitter { static { __name(this, "CylinderDirectedParticleEmitter"); } /** * Creates a new instance CylinderDirectedParticleEmitter * @param radius the radius of the emission cylinder (1 by default) * @param height the height of the emission cylinder (1 by default) * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default) * @param direction1 the min limit of the emission direction (up vector by default) * @param direction2 the max limit of the emission direction (up vector by default) */ constructor(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { super(radius, height, radiusRange); this.direction1 = direction1; this.direction2 = direction2; } /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param directionToUpdate is the direction vector to update with the result * @param _particle is the particle we are computed the direction for * @param isLocal defines if the direction should be set in local space */ startDirectionFunction(worldMatrix, directionToUpdate, _particle, isLocal) { const randX = RandomRange(this.direction1.x, this.direction2.x); const randY = RandomRange(this.direction1.y, this.direction2.y); const randZ = RandomRange(this.direction1.z, this.direction2.z); if (isLocal) { directionToUpdate.copyFromFloats(randX, randY, randZ); return; } Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); } /** * Clones the current emitter and returns a copy of it * @returns the new emitter */ clone() { const newOne = new _CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2); DeepCopier.DeepCopy(this, newOne); return newOne; } /** * Called by the GPUParticleSystem to setup the update shader * @param uboOrEffect defines the update shader */ applyToShader(uboOrEffect) { uboOrEffect.setFloat("radius", this.radius); uboOrEffect.setFloat("height", this.height); uboOrEffect.setFloat("radiusRange", this.radiusRange); uboOrEffect.setVector3("direction1", this.direction1); uboOrEffect.setVector3("direction2", this.direction2); } /** * Creates the structure of the ubo for this particle emitter * @param ubo ubo to create the structure for */ buildUniformLayout(ubo) { ubo.addUniform("radius", 1); ubo.addUniform("height", 1); ubo.addUniform("radiusRange", 1); ubo.addUniform("direction1", 3); ubo.addUniform("direction2", 3); } /** * Returns a string to use to update the GPU particles update shader * @returns a string containing the defines string */ getEffectDefines() { return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER"; } /** * Returns the string "CylinderDirectedParticleEmitter" * @returns a string containing the class name */ getClassName() { return "CylinderDirectedParticleEmitter"; } /** * Serializes the particle system to a JSON object. * @returns the JSON object */ serialize() { const serializationObject = super.serialize(); serializationObject.direction1 = this.direction1.asArray(); serializationObject.direction2 = this.direction2.asArray(); return serializationObject; } /** * Parse properties from a JSON object * @param serializationObject defines the JSON object */ parse(serializationObject) { super.parse(serializationObject); Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1); Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/EmitterTypes/coneParticleEmitter.js init_deepCopier(); init_math_vector(); init_math_scalar_functions(); var ConeParticleEmitter = class _ConeParticleEmitter { static { __name(this, "ConeParticleEmitter"); } /** * Gets or sets the radius of the emission cone */ get radius() { return this._radius; } set radius(value) { this._radius = value; this._buildHeight(); } /** * Gets or sets the angle of the emission cone */ get angle() { return this._angle; } set angle(value) { this._angle = value; this._buildHeight(); } _buildHeight() { if (this._angle !== 0) { this._height = this._radius / Math.tan(this._angle / 2); } else { this._height = 1; } } /** * Creates a new instance ConeParticleEmitter * @param radius the radius of the emission cone (1 by default) * @param angle the cone base angle (PI by default) * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0) */ constructor(radius = 1, angle = Math.PI, directionRandomizer = 0) { this.directionRandomizer = directionRandomizer; this.radiusRange = 1; this.heightRange = 1; this.emitFromSpawnPointOnly = false; this.angle = angle; this.radius = radius; } /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param directionToUpdate is the direction vector to update with the result * @param particle is the particle we are computed the direction for * @param isLocal defines if the direction should be set in local space */ startDirectionFunction(worldMatrix, directionToUpdate, particle, isLocal) { if (isLocal) { TmpVectors.Vector3[0].copyFrom(particle._localPosition).normalize(); } else { particle.position.subtractToRef(worldMatrix.getTranslation(), TmpVectors.Vector3[0]).normalize(); } const randX = RandomRange(0, this.directionRandomizer); const randY = RandomRange(0, this.directionRandomizer); const randZ = RandomRange(0, this.directionRandomizer); directionToUpdate.x = TmpVectors.Vector3[0].x + randX; directionToUpdate.y = TmpVectors.Vector3[0].y + randY; directionToUpdate.z = TmpVectors.Vector3[0].z + randZ; directionToUpdate.normalize(); } /** * Called by the particle System when the position is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param positionToUpdate is the position vector to update with the result * @param particle is the particle we are computed the position for * @param isLocal defines if the position should be set in local space */ startPositionFunction(worldMatrix, positionToUpdate, particle, isLocal) { const s = RandomRange(0, Math.PI * 2); let h; if (!this.emitFromSpawnPointOnly) { h = RandomRange(0, this.heightRange); h = 1 - h * h; } else { h = 1e-4; } let radius = this._radius - RandomRange(0, this._radius * this.radiusRange); radius = radius * h; const randX = radius * Math.sin(s); const randZ = radius * Math.cos(s); const randY = h * this._height; if (isLocal) { positionToUpdate.x = randX; positionToUpdate.y = randY; positionToUpdate.z = randZ; return; } Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate); } /** * Clones the current emitter and returns a copy of it * @returns the new emitter */ clone() { const newOne = new _ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer); DeepCopier.DeepCopy(this, newOne); return newOne; } /** * Called by the GPUParticleSystem to setup the update shader * @param uboOrEffect defines the update shader */ applyToShader(uboOrEffect) { uboOrEffect.setFloat2("radius", this._radius, this.radiusRange); uboOrEffect.setFloat("coneAngle", this._angle); uboOrEffect.setFloat2("height", this._height, this.heightRange); uboOrEffect.setFloat("directionRandomizer", this.directionRandomizer); } /** * Creates the structure of the ubo for this particle emitter * @param ubo ubo to create the structure for */ buildUniformLayout(ubo) { ubo.addUniform("radius", 2); ubo.addUniform("coneAngle", 1); ubo.addUniform("height", 2); ubo.addUniform("directionRandomizer", 1); } /** * Returns a string to use to update the GPU particles update shader * @returns a string containing the defines string */ getEffectDefines() { let defines = "#define CONEEMITTER"; if (this.emitFromSpawnPointOnly) { defines += "\n#define CONEEMITTERSPAWNPOINT"; } return defines; } /** * Returns the string "ConeParticleEmitter" * @returns a string containing the class name */ getClassName() { return "ConeParticleEmitter"; } /** * Serializes the particle system to a JSON object. * @returns the JSON object */ serialize() { const serializationObject = {}; serializationObject.type = this.getClassName(); serializationObject.radius = this._radius; serializationObject.angle = this._angle; serializationObject.directionRandomizer = this.directionRandomizer; serializationObject.radiusRange = this.radiusRange; serializationObject.heightRange = this.heightRange; serializationObject.emitFromSpawnPointOnly = this.emitFromSpawnPointOnly; return serializationObject; } /** * Parse properties from a JSON object * @param serializationObject defines the JSON object */ parse(serializationObject) { this.radius = serializationObject.radius; this.angle = serializationObject.angle; this.directionRandomizer = serializationObject.directionRandomizer; this.radiusRange = serializationObject.radiusRange !== void 0 ? serializationObject.radiusRange : 1; this.heightRange = serializationObject.radiusRange !== void 0 ? serializationObject.heightRange : 1; this.emitFromSpawnPointOnly = serializationObject.emitFromSpawnPointOnly !== void 0 ? serializationObject.emitFromSpawnPointOnly : false; } }; var ConeDirectedParticleEmitter = class _ConeDirectedParticleEmitter extends ConeParticleEmitter { static { __name(this, "ConeDirectedParticleEmitter"); } constructor(radius = 1, angle = Math.PI, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { super(radius, angle); this.direction1 = direction1; this.direction2 = direction2; } /** * Called by the particle System when the direction is computed for the created particle. * @param worldMatrix is the world matrix of the particle system * @param directionToUpdate is the direction vector to update with the result */ startDirectionFunction(worldMatrix, directionToUpdate) { const randX = RandomRange(this.direction1.x, this.direction2.x); const randY = RandomRange(this.direction1.y, this.direction2.y); const randZ = RandomRange(this.direction1.z, this.direction2.z); Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate); } /** * Clones the current emitter and returns a copy of it * @returns the new emitter */ clone() { const newOne = new _ConeDirectedParticleEmitter(this.radius, this.angle, this.direction1, this.direction2); DeepCopier.DeepCopy(this, newOne); return newOne; } /** * Called by the GPUParticleSystem to setup the update shader * @param uboOrEffect defines the update shader */ applyToShader(uboOrEffect) { uboOrEffect.setFloat("radius", this.radius); uboOrEffect.setFloat("radiusRange", this.radiusRange); uboOrEffect.setVector3("direction1", this.direction1); uboOrEffect.setVector3("direction2", this.direction2); } /** * Creates the structure of the ubo for this particle emitter * @param ubo ubo to create the structure for */ buildUniformLayout(ubo) { ubo.addUniform("radius", 1); ubo.addUniform("radiusRange", 1); ubo.addUniform("direction1", 3); ubo.addUniform("direction2", 3); } /** * Returns a string to use to update the GPU particles update shader * @returns a string containing the defines string */ getEffectDefines() { return "#define CONEEMITTER\n#define DIRECTEDCONEEMITTER"; } /** * Returns the string "ConeDirectedParticleEmitter" * @returns a string containing the class name */ getClassName() { return "ConeDirectedParticleEmitter"; } /** * Serializes the particle system to a JSON object. * @returns the JSON object */ serialize() { const serializationObject = super.serialize(); serializationObject.direction1 = this.direction1.asArray(); serializationObject.direction2 = this.direction2.asArray(); return serializationObject; } /** * Parse properties from a JSON object * @param serializationObject defines the JSON object */ parse(serializationObject) { super.parse(serializationObject); this.direction1.copyFrom(serializationObject.direction1); this.direction2.copyFrom(serializationObject.direction2); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/particleSystem.functions.js init_math_vector(); function CreatePointEmitter(direction1, direction2) { const particleEmitter = new PointParticleEmitter(); particleEmitter.direction1 = direction1; particleEmitter.direction2 = direction2; return particleEmitter; } __name(CreatePointEmitter, "CreatePointEmitter"); function CreateHemisphericEmitter(radius = 1, radiusRange = 1) { return new HemisphericParticleEmitter(radius, radiusRange); } __name(CreateHemisphericEmitter, "CreateHemisphericEmitter"); function CreateSphereEmitter(radius = 1, radiusRange = 1) { return new SphereParticleEmitter(radius, radiusRange); } __name(CreateSphereEmitter, "CreateSphereEmitter"); function CreateDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { return new SphereDirectedParticleEmitter(radius, direction1, direction2); } __name(CreateDirectedSphereEmitter, "CreateDirectedSphereEmitter"); function CreateCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) { return new CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer); } __name(CreateCylinderEmitter, "CreateCylinderEmitter"); function CreateDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { return new CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2); } __name(CreateDirectedCylinderEmitter, "CreateDirectedCylinderEmitter"); function CreateConeEmitter(radius = 1, angle = Math.PI / 4) { return new ConeParticleEmitter(radius, angle); } __name(CreateConeEmitter, "CreateConeEmitter"); function CreateDirectedConeEmitter(radius = 1, angle = Math.PI / 4, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { return new ConeDirectedParticleEmitter(radius, angle, direction1, direction2); } __name(CreateDirectedConeEmitter, "CreateDirectedConeEmitter"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/attractor.js init_math_vector(); var ToAttractor = Vector3.Zero(); var Force = Vector3.Zero(); var ScaledForce = Vector3.Zero(); var Attractor = class { static { __name(this, "Attractor"); } constructor() { this.strength = 0; this.position = Vector3.Zero(); } /** @internal */ _processParticle(particle, system) { this.position.subtractToRef(particle.position, ToAttractor); const distanceSquared = ToAttractor.lengthSquared() + 1; ToAttractor.normalize().scaleToRef(this.strength / distanceSquared, Force); Force.scaleToRef(system._tempScaledUpdateSpeed, ScaledForce); particle.direction.addInPlace(ScaledForce); } /** * Serializes the attractor to a JSON object. * @returns The serialized JSON object. */ serialize() { return { position: this.position.asArray(), strength: this.strength }; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/particleSystem.js init_math_color(); init_math_vector(); init_abstractEngine(); init_typeStore(); init_decorators_serialization(); var ParticleSystem = class _ParticleSystem extends ThinParticleSystem { static { __name(this, "ParticleSystem"); } constructor() { super(...arguments); this._disposeEmitterOnDispose = false; this.canStart = () => { return true; }; this._flowMap = null; this._flowMapUpdate = null; this._source = null; this._blockReference = 0; this.flowMapStrength = 1; this._attractors = []; this._attractorUpdate = null; this.metadata = null; this._emitFromParticle = (particle) => { if (!this._subEmitters || this._subEmitters.length === 0) { return; } const templateIndex = Math.floor(Math.random() * this._subEmitters.length); for (const subEmitter of this._subEmitters[templateIndex]) { if (subEmitter.type === 1) { const subSystem = subEmitter.clone(); particle._inheritParticleInfoToSubEmitter(subSystem); subSystem.particleSystem._rootParticleSystem = this; this.activeSubSystems.push(subSystem.particleSystem); subSystem.particleSystem.start(); } } }; } /** * Creates a Point Emitter for the particle system (emits directly from the emitter position) * @param direction1 Particles are emitted between the direction1 and direction2 from within the box * @param direction2 Particles are emitted between the direction1 and direction2 from within the box * @returns the emitter */ createPointEmitter(direction1, direction2) { const particleEmitter = CreatePointEmitter(direction1, direction2); this.particleEmitterType = particleEmitter; return particleEmitter; } /** * Gets the NodeParticleSystemSet that this particle system belongs to. */ get source() { return this._source; } /** * Returns true if the particle system was generated by a node particle system set */ get isNodeGenerated() { return this._source !== null; } /** Gets or sets the current flow map */ get flowMap() { return this._flowMap; } set flowMap(value) { if (this._flowMap === value) { return; } this._flowMap = value; if (this._flowMapUpdate) { _RemoveFromQueue(this._flowMapUpdate); this._flowMapUpdate = null; } if (value) { this._flowMapUpdate = { process: /* @__PURE__ */ __name((particle) => { const matrix = this.getScene()?.getTransformMatrix(); this._flowMap._processParticle(particle, this.flowMapStrength * this._tempScaledUpdateSpeed, matrix); }, "process"), previousItem: null, nextItem: null }; _ConnectAfter(this._flowMapUpdate, this._directionProcessing); } } /** * The list of attractors used to change the direction of the particles in the system. * Please note that this is a copy of the internal array. If you want to modify it, please use the addAttractor and removeAttractor methods. */ get attractors() { return this._attractors.slice(0); } /** * Add an attractor to the particle system. Attractors are used to change the direction of the particles in the system. * @param attractor The attractor to add to the particle system */ addAttractor(attractor) { this._attractors.push(attractor); if (this._attractors.length === 1) { this._attractorUpdate = { process: /* @__PURE__ */ __name((particle) => { for (const attractor2 of this._attractors) { attractor2._processParticle(particle, this); } }, "process"), previousItem: null, nextItem: null }; _ConnectAfter(this._attractorUpdate, this._directionProcessing); } } /** * Removes an attractor from the particle system. Attractors are used to change the direction of the particles in the system. * @param attractor The attractor to remove from the particle system */ removeAttractor(attractor) { const index = this._attractors.indexOf(attractor); if (index !== -1) { this._attractors.splice(index, 1); } if (this._attractors.length === 0) { _RemoveFromQueue(this._attractorUpdate); } } start(delay = this.startDelay) { if (!this.canStart()) { return; } super.start(delay); } /** * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius) * @param radius The radius of the hemisphere to emit from * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius * @returns the emitter */ createHemisphericEmitter(radius = 1, radiusRange = 1) { const particleEmitter = CreateHemisphericEmitter(radius, radiusRange); this.particleEmitterType = particleEmitter; return particleEmitter; } /** * Creates a Sphere Emitter for the particle system (emits along the sphere radius) * @param radius The radius of the sphere to emit from * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius * @returns the emitter */ createSphereEmitter(radius = 1, radiusRange = 1) { const particleEmitter = CreateSphereEmitter(radius, radiusRange); this.particleEmitterType = particleEmitter; return particleEmitter; } /** * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2) * @param radius The radius of the sphere to emit from * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere * @returns the emitter */ createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { const particleEmitter = CreateDirectedSphereEmitter(radius, direction1, direction2); this.particleEmitterType = particleEmitter; return particleEmitter; } /** * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position) * @param radius The radius of the emission cylinder * @param height The height of the emission cylinder * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius * @param directionRandomizer How much to randomize the particle direction [0-1] * @returns the emitter */ createCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) { const particleEmitter = CreateCylinderEmitter(radius, height, radiusRange, directionRandomizer); this.particleEmitterType = particleEmitter; return particleEmitter; } /** * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2) * @param radius The radius of the cylinder to emit from * @param height The height of the emission cylinder * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default) * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder * @returns the emitter */ createDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { const particleEmitter = CreateDirectedCylinderEmitter(radius, height, radiusRange, direction1, direction2); this.particleEmitterType = particleEmitter; return particleEmitter; } /** * Creates a Cone Emitter for the particle system (emits from the cone to the particle position) * @param radius The radius of the cone to emit from * @param angle The base angle of the cone * @returns the emitter */ createConeEmitter(radius = 1, angle = Math.PI / 4) { const particleEmitter = CreateConeEmitter(radius, angle); this.particleEmitterType = particleEmitter; return particleEmitter; } createDirectedConeEmitter(radius = 1, angle = Math.PI / 4, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { const particleEmitter = CreateDirectedConeEmitter(radius, angle, direction1, direction2); this.particleEmitterType = particleEmitter; return particleEmitter; } /** * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox) * @param direction1 Particles are emitted between the direction1 and direction2 from within the box * @param direction2 Particles are emitted between the direction1 and direction2 from within the box * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox * @returns the emitter */ createBoxEmitter(direction1, direction2, minEmitBox, maxEmitBox) { const particleEmitter = new BoxParticleEmitter(); this.particleEmitterType = particleEmitter; this.direction1 = direction1; this.direction2 = direction2; this.minEmitBox = minEmitBox; this.maxEmitBox = maxEmitBox; return particleEmitter; } _prepareSubEmitterInternalArray() { this._subEmitters = new Array(); if (this.subEmitters) { for (const subEmitter of this.subEmitters) { if (subEmitter instanceof _ParticleSystem) { this._subEmitters.push([new SubEmitter(subEmitter)]); } else if (subEmitter instanceof SubEmitter) { this._subEmitters.push([subEmitter]); } else if (subEmitter instanceof Array) { this._subEmitters.push(subEmitter); } } } } _stopSubEmitters() { if (!this.activeSubSystems) { return; } for (const subSystem of this.activeSubSystems) { subSystem.stop(true); } this.activeSubSystems = []; } _removeFromRoot() { if (!this._rootParticleSystem) { return; } const index = this._rootParticleSystem.activeSubSystems.indexOf(this); if (index !== -1) { this._rootParticleSystem.activeSubSystems.splice(index, 1); } this._rootParticleSystem = null; } /** @internal */ _preStart() { this._prepareSubEmitterInternalArray(); if (this._subEmitters && this._subEmitters.length != 0) { this.activeSubSystems = []; } } /** @internal */ _postStop(stopSubEmitters) { if (stopSubEmitters) { this._stopSubEmitters(); } } /** @internal */ _prepareParticle(particle) { if (this._subEmitters && this._subEmitters.length > 0) { const subEmitters = this._subEmitters[Math.floor(Math.random() * this._subEmitters.length)]; particle._attachedSubEmitters = []; for (const subEmitter of subEmitters) { if (subEmitter.type === 0) { const newEmitter = subEmitter.clone(); particle._attachedSubEmitters.push(newEmitter); newEmitter.particleSystem.start(); } } } } /** @internal */ _onDispose(disposeAttachedSubEmitters = false, disposeEndSubEmitters = false) { this._removeFromRoot(); if (this.subEmitters && !this._subEmitters) { this._prepareSubEmitterInternalArray(); } if (disposeAttachedSubEmitters) { if (this.particles) { for (const particle of this.particles) { if (particle._attachedSubEmitters) { for (let i = particle._attachedSubEmitters.length - 1; i >= 0; i -= 1) { particle._attachedSubEmitters[i].dispose(); } } } } } if (disposeEndSubEmitters) { if (this.activeSubSystems) { for (let i = this.activeSubSystems.length - 1; i >= 0; i -= 1) { this.activeSubSystems[i].dispose(); } } } if (this._subEmitters && this._subEmitters.length) { for (let index = 0; index < this._subEmitters.length; index++) { for (const subEmitter of this._subEmitters[index]) { subEmitter.dispose(); } } this._subEmitters = []; this.subEmitters = []; } if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) { this.emitter.dispose(true); } } /** * @internal */ static _Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl) { let scene; if (sceneOrEngine instanceof AbstractEngine) { scene = null; } else { scene = sceneOrEngine; } const internalClass = GetClass("BABYLON.Texture"); if (internalClass && scene) { if (parsedParticleSystem.texture) { particleSystem.particleTexture = internalClass.Parse(parsedParticleSystem.texture, scene, rootUrl); } else if (parsedParticleSystem.textureName) { particleSystem.particleTexture = new internalClass(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== void 0 ? parsedParticleSystem.invertY : true); particleSystem.particleTexture.name = parsedParticleSystem.textureName; } } if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === void 0) { particleSystem.emitter = Vector3.Zero(); } else if (parsedParticleSystem.emitterId && scene) { particleSystem.emitter = scene.getLastMeshById(parsedParticleSystem.emitterId); } else { particleSystem.emitter = Vector3.FromArray(parsedParticleSystem.emitter); } particleSystem.isLocal = !!parsedParticleSystem.isLocal; if (parsedParticleSystem.renderingGroupId !== void 0) { particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId; } if (parsedParticleSystem.isBillboardBased !== void 0) { particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased; } if (parsedParticleSystem.billboardMode !== void 0) { particleSystem.billboardMode = parsedParticleSystem.billboardMode; } if (parsedParticleSystem.useLogarithmicDepth !== void 0) { particleSystem.useLogarithmicDepth = parsedParticleSystem.useLogarithmicDepth; } if (parsedParticleSystem.animations) { for (let animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) { const parsedAnimation = parsedParticleSystem.animations[animationIndex]; const internalClass2 = GetClass("BABYLON.Animation"); if (internalClass2) { particleSystem.animations.push(internalClass2.Parse(parsedAnimation)); } } particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart; particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom; particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo; particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop; } if (parsedParticleSystem.autoAnimate && scene) { scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1); } particleSystem.startDelay = parsedParticleSystem.startDelay | 0; particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed; particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed; particleSystem.minSize = parsedParticleSystem.minSize; particleSystem.maxSize = parsedParticleSystem.maxSize; if (parsedParticleSystem.minScaleX) { particleSystem.minScaleX = parsedParticleSystem.minScaleX; particleSystem.maxScaleX = parsedParticleSystem.maxScaleX; particleSystem.minScaleY = parsedParticleSystem.minScaleY; particleSystem.maxScaleY = parsedParticleSystem.maxScaleY; } if (parsedParticleSystem.preWarmCycles !== void 0) { particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles; particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset; } if (parsedParticleSystem.minInitialRotation !== void 0) { particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation; particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation; } particleSystem.minLifeTime = parsedParticleSystem.minLifeTime; particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime; particleSystem.minEmitPower = parsedParticleSystem.minEmitPower; particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower; particleSystem.emitRate = parsedParticleSystem.emitRate; particleSystem.gravity = Vector3.FromArray(parsedParticleSystem.gravity); if (parsedParticleSystem.noiseStrength) { particleSystem.noiseStrength = Vector3.FromArray(parsedParticleSystem.noiseStrength); } particleSystem.color1 = Color4.FromArray(parsedParticleSystem.color1); particleSystem.color2 = Color4.FromArray(parsedParticleSystem.color2); particleSystem.colorDead = Color4.FromArray(parsedParticleSystem.colorDead); particleSystem.updateSpeed = parsedParticleSystem.updateSpeed; particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration; particleSystem.blendMode = parsedParticleSystem.blendMode; if (parsedParticleSystem.colorGradients) { for (const colorGradient of parsedParticleSystem.colorGradients) { particleSystem.addColorGradient(colorGradient.gradient, Color4.FromArray(colorGradient.color1), colorGradient.color2 ? Color4.FromArray(colorGradient.color2) : void 0); } } if (parsedParticleSystem.rampGradients) { for (const rampGradient of parsedParticleSystem.rampGradients) { particleSystem.addRampGradient(rampGradient.gradient, Color3.FromArray(rampGradient.color)); } particleSystem.useRampGradients = parsedParticleSystem.useRampGradients; } if (parsedParticleSystem.colorRemapGradients) { for (const colorRemapGradient of parsedParticleSystem.colorRemapGradients) { particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== void 0 ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2); } } if (parsedParticleSystem.alphaRemapGradients) { for (const alphaRemapGradient of parsedParticleSystem.alphaRemapGradients) { particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== void 0 ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2); } } if (parsedParticleSystem.sizeGradients) { for (const sizeGradient of parsedParticleSystem.sizeGradients) { particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== void 0 ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2); } } if (parsedParticleSystem.angularSpeedGradients) { for (const angularSpeedGradient of parsedParticleSystem.angularSpeedGradients) { particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== void 0 ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2); } } if (parsedParticleSystem.velocityGradients) { for (const velocityGradient of parsedParticleSystem.velocityGradients) { particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== void 0 ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2); } } if (parsedParticleSystem.dragGradients) { for (const dragGradient of parsedParticleSystem.dragGradients) { particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== void 0 ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2); } } if (parsedParticleSystem.emitRateGradients) { for (const emitRateGradient of parsedParticleSystem.emitRateGradients) { particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== void 0 ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2); } } if (parsedParticleSystem.startSizeGradients) { for (const startSizeGradient of parsedParticleSystem.startSizeGradients) { particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== void 0 ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2); } } if (parsedParticleSystem.lifeTimeGradients) { for (const lifeTimeGradient of parsedParticleSystem.lifeTimeGradients) { particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== void 0 ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2); } } if (parsedParticleSystem.limitVelocityGradients) { for (const limitVelocityGradient of parsedParticleSystem.limitVelocityGradients) { particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== void 0 ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2); } particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping; } if (parsedParticleSystem.noiseTexture && scene) { const internalClass2 = GetClass("BABYLON.ProceduralTexture"); particleSystem.noiseTexture = internalClass2.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl); } let emitterType; if (parsedParticleSystem.particleEmitterType) { switch (parsedParticleSystem.particleEmitterType.type) { case "SphereParticleEmitter": emitterType = new SphereParticleEmitter(); break; case "SphereDirectedParticleEmitter": emitterType = new SphereDirectedParticleEmitter(); break; case "ConeEmitter": case "ConeParticleEmitter": emitterType = new ConeParticleEmitter(); break; case "ConeDirectedParticleEmitter": emitterType = new ConeDirectedParticleEmitter(); break; case "CylinderParticleEmitter": emitterType = new CylinderParticleEmitter(); break; case "CylinderDirectedParticleEmitter": emitterType = new CylinderDirectedParticleEmitter(); break; case "HemisphericParticleEmitter": emitterType = new HemisphericParticleEmitter(); break; case "PointParticleEmitter": emitterType = new PointParticleEmitter(); break; case "MeshParticleEmitter": emitterType = new MeshParticleEmitter(); break; case "CustomParticleEmitter": emitterType = new CustomParticleEmitter(); break; case "BoxEmitter": case "BoxParticleEmitter": default: emitterType = new BoxParticleEmitter(); break; } emitterType.parse(parsedParticleSystem.particleEmitterType, scene); } else { emitterType = new BoxParticleEmitter(); emitterType.parse(parsedParticleSystem, scene); } particleSystem.particleEmitterType = emitterType; particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID; particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID; particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop ?? true; particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth; particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight; particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed; particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell; particleSystem.disposeOnStop = parsedParticleSystem.disposeOnStop ?? false; particleSystem.manualEmitCount = parsedParticleSystem.manualEmitCount ?? -1; } /** * Parses a JSON object to create a particle system. * @param parsedParticleSystem The JSON object to parse * @param sceneOrEngine The scene or the engine to create the particle system in * @param rootUrl The root url to use to load external dependencies like texture * @param doNotStart Ignore the preventAutoStart attribute and does not start * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used) * @returns the Parsed particle system */ static Parse(parsedParticleSystem, sceneOrEngine, rootUrl, doNotStart = false, capacity) { const name260 = parsedParticleSystem.name; let custom = null; let program = null; let engine; let scene; if (sceneOrEngine instanceof AbstractEngine) { engine = sceneOrEngine; } else { scene = sceneOrEngine; engine = scene.getEngine(); } if (parsedParticleSystem.customShader && engine.createEffectForParticles) { program = parsedParticleSystem.customShader; const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : ""; custom = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines); } const particleSystem = new _ParticleSystem(name260, capacity || parsedParticleSystem.capacity, sceneOrEngine, custom, parsedParticleSystem.isAnimationSheetEnabled); particleSystem.customShader = program; particleSystem._rootUrl = rootUrl; if (parsedParticleSystem.id) { particleSystem.id = parsedParticleSystem.id; } if (parsedParticleSystem.subEmitters) { particleSystem.subEmitters = []; for (const cell of parsedParticleSystem.subEmitters) { const cellArray = []; for (const sub of cell) { cellArray.push(SubEmitter.Parse(sub, sceneOrEngine, rootUrl)); } particleSystem.subEmitters.push(cellArray); } } if (parsedParticleSystem.attractors) { for (const attractor of parsedParticleSystem.attractors) { const newAttractor = new Attractor(); newAttractor.position = Vector3.FromArray(attractor.position); newAttractor.strength = attractor.strength; particleSystem.addAttractor(newAttractor); } } _ParticleSystem._Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl); if (parsedParticleSystem.textureMask) { particleSystem.textureMask = Color4.FromArray(parsedParticleSystem.textureMask); } if (parsedParticleSystem.worldOffset) { particleSystem.worldOffset = Vector3.FromArray(parsedParticleSystem.worldOffset); } if (parsedParticleSystem.preventAutoStart) { particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart; } if (parsedParticleSystem.metadata) { particleSystem.metadata = parsedParticleSystem.metadata; } if (!doNotStart && !particleSystem.preventAutoStart) { particleSystem.start(); } return particleSystem; } /** * Serializes the particle system to a JSON object * @param serializeTexture defines if the texture must be serialized as well * @returns the JSON object */ serialize(serializeTexture = false) { const serializationObject = {}; _ParticleSystem._Serialize(serializationObject, this, serializeTexture); serializationObject.textureMask = this.textureMask.asArray(); serializationObject.customShader = this.customShader; serializationObject.preventAutoStart = this.preventAutoStart; serializationObject.worldOffset = this.worldOffset.asArray(); if (this.metadata) { serializationObject.metadata = this.metadata; } if (this.subEmitters) { serializationObject.subEmitters = []; if (!this._subEmitters) { this._prepareSubEmitterInternalArray(); } for (const subs of this._subEmitters) { const cell = []; for (const sub of subs) { cell.push(sub.serialize(serializeTexture)); } serializationObject.subEmitters.push(cell); } } if (this._attractors && this._attractors.length) { serializationObject.attractors = []; for (const attractor of this._attractors) { serializationObject.attractors.push(attractor.serialize()); } } return serializationObject; } /** * @internal */ static _Serialize(serializationObject, particleSystem, serializeTexture) { serializationObject.name = particleSystem.name; serializationObject.id = particleSystem.id; serializationObject.capacity = particleSystem.getCapacity(); serializationObject.disposeOnStop = particleSystem.disposeOnStop; serializationObject.manualEmitCount = particleSystem.manualEmitCount; if (particleSystem.emitter.position) { const emitterMesh = particleSystem.emitter; serializationObject.emitterId = emitterMesh.id; } else { const emitterPosition = particleSystem.emitter; serializationObject.emitter = emitterPosition.asArray(); } if (particleSystem.particleEmitterType) { serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize(); } if (particleSystem.particleTexture) { if (serializeTexture) { serializationObject.texture = particleSystem.particleTexture.serialize(); } else { serializationObject.textureName = particleSystem.particleTexture.name; serializationObject.invertY = !!particleSystem.particleTexture._invertY; } } serializationObject.isLocal = particleSystem.isLocal; SerializationHelper.AppendSerializedAnimations(particleSystem, serializationObject); serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart; serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom; serializationObject.beginAnimationTo = particleSystem.beginAnimationTo; serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop; serializationObject.startDelay = particleSystem.startDelay; serializationObject.renderingGroupId = particleSystem.renderingGroupId; serializationObject.isBillboardBased = particleSystem.isBillboardBased; serializationObject.billboardMode = particleSystem.billboardMode; serializationObject.minAngularSpeed = particleSystem.minAngularSpeed; serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed; serializationObject.minSize = particleSystem.minSize; serializationObject.maxSize = particleSystem.maxSize; serializationObject.minScaleX = particleSystem.minScaleX; serializationObject.maxScaleX = particleSystem.maxScaleX; serializationObject.minScaleY = particleSystem.minScaleY; serializationObject.maxScaleY = particleSystem.maxScaleY; serializationObject.minEmitPower = particleSystem.minEmitPower; serializationObject.maxEmitPower = particleSystem.maxEmitPower; serializationObject.minLifeTime = particleSystem.minLifeTime; serializationObject.maxLifeTime = particleSystem.maxLifeTime; serializationObject.emitRate = particleSystem.emitRate; serializationObject.gravity = particleSystem.gravity.asArray(); serializationObject.noiseStrength = particleSystem.noiseStrength.asArray(); serializationObject.color1 = particleSystem.color1.asArray(); serializationObject.color2 = particleSystem.color2.asArray(); serializationObject.colorDead = particleSystem.colorDead.asArray(); serializationObject.updateSpeed = particleSystem.updateSpeed; serializationObject.targetStopDuration = particleSystem.targetStopDuration; serializationObject.blendMode = particleSystem.blendMode; serializationObject.preWarmCycles = particleSystem.preWarmCycles; serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset; serializationObject.minInitialRotation = particleSystem.minInitialRotation; serializationObject.maxInitialRotation = particleSystem.maxInitialRotation; serializationObject.startSpriteCellID = particleSystem.startSpriteCellID; serializationObject.spriteCellLoop = particleSystem.spriteCellLoop; serializationObject.endSpriteCellID = particleSystem.endSpriteCellID; serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed; serializationObject.spriteCellWidth = particleSystem.spriteCellWidth; serializationObject.spriteCellHeight = particleSystem.spriteCellHeight; serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell; serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled; serializationObject.useLogarithmicDepth = particleSystem.useLogarithmicDepth; const colorGradients = particleSystem.getColorGradients(); if (colorGradients) { serializationObject.colorGradients = []; for (const colorGradient of colorGradients) { const serializedGradient = { gradient: colorGradient.gradient, color1: colorGradient.color1.asArray() }; if (colorGradient.color2) { serializedGradient.color2 = colorGradient.color2.asArray(); } else { serializedGradient.color2 = colorGradient.color1.asArray(); } serializationObject.colorGradients.push(serializedGradient); } } const rampGradients = particleSystem.getRampGradients(); if (rampGradients) { serializationObject.rampGradients = []; for (const rampGradient of rampGradients) { const serializedGradient = { gradient: rampGradient.gradient, color: rampGradient.color.asArray() }; serializationObject.rampGradients.push(serializedGradient); } serializationObject.useRampGradients = particleSystem.useRampGradients; } const colorRemapGradients = particleSystem.getColorRemapGradients(); if (colorRemapGradients) { serializationObject.colorRemapGradients = []; for (const colorRemapGradient of colorRemapGradients) { const serializedGradient = { gradient: colorRemapGradient.gradient, factor1: colorRemapGradient.factor1 }; if (colorRemapGradient.factor2 !== void 0) { serializedGradient.factor2 = colorRemapGradient.factor2; } else { serializedGradient.factor2 = colorRemapGradient.factor1; } serializationObject.colorRemapGradients.push(serializedGradient); } } const alphaRemapGradients = particleSystem.getAlphaRemapGradients(); if (alphaRemapGradients) { serializationObject.alphaRemapGradients = []; for (const alphaRemapGradient of alphaRemapGradients) { const serializedGradient = { gradient: alphaRemapGradient.gradient, factor1: alphaRemapGradient.factor1 }; if (alphaRemapGradient.factor2 !== void 0) { serializedGradient.factor2 = alphaRemapGradient.factor2; } else { serializedGradient.factor2 = alphaRemapGradient.factor1; } serializationObject.alphaRemapGradients.push(serializedGradient); } } const sizeGradients = particleSystem.getSizeGradients(); if (sizeGradients) { serializationObject.sizeGradients = []; for (const sizeGradient of sizeGradients) { const serializedGradient = { gradient: sizeGradient.gradient, factor1: sizeGradient.factor1 }; if (sizeGradient.factor2 !== void 0) { serializedGradient.factor2 = sizeGradient.factor2; } else { serializedGradient.factor2 = sizeGradient.factor1; } serializationObject.sizeGradients.push(serializedGradient); } } const angularSpeedGradients = particleSystem.getAngularSpeedGradients(); if (angularSpeedGradients) { serializationObject.angularSpeedGradients = []; for (const angularSpeedGradient of angularSpeedGradients) { const serializedGradient = { gradient: angularSpeedGradient.gradient, factor1: angularSpeedGradient.factor1 }; if (angularSpeedGradient.factor2 !== void 0) { serializedGradient.factor2 = angularSpeedGradient.factor2; } else { serializedGradient.factor2 = angularSpeedGradient.factor1; } serializationObject.angularSpeedGradients.push(serializedGradient); } } const velocityGradients = particleSystem.getVelocityGradients(); if (velocityGradients) { serializationObject.velocityGradients = []; for (const velocityGradient of velocityGradients) { const serializedGradient = { gradient: velocityGradient.gradient, factor1: velocityGradient.factor1 }; if (velocityGradient.factor2 !== void 0) { serializedGradient.factor2 = velocityGradient.factor2; } else { serializedGradient.factor2 = velocityGradient.factor1; } serializationObject.velocityGradients.push(serializedGradient); } } const dragGradients = particleSystem.getDragGradients(); if (dragGradients) { serializationObject.dragGradients = []; for (const dragGradient of dragGradients) { const serializedGradient = { gradient: dragGradient.gradient, factor1: dragGradient.factor1 }; if (dragGradient.factor2 !== void 0) { serializedGradient.factor2 = dragGradient.factor2; } else { serializedGradient.factor2 = dragGradient.factor1; } serializationObject.dragGradients.push(serializedGradient); } } const emitRateGradients = particleSystem.getEmitRateGradients(); if (emitRateGradients) { serializationObject.emitRateGradients = []; for (const emitRateGradient of emitRateGradients) { const serializedGradient = { gradient: emitRateGradient.gradient, factor1: emitRateGradient.factor1 }; if (emitRateGradient.factor2 !== void 0) { serializedGradient.factor2 = emitRateGradient.factor2; } else { serializedGradient.factor2 = emitRateGradient.factor1; } serializationObject.emitRateGradients.push(serializedGradient); } } const startSizeGradients = particleSystem.getStartSizeGradients(); if (startSizeGradients) { serializationObject.startSizeGradients = []; for (const startSizeGradient of startSizeGradients) { const serializedGradient = { gradient: startSizeGradient.gradient, factor1: startSizeGradient.factor1 }; if (startSizeGradient.factor2 !== void 0) { serializedGradient.factor2 = startSizeGradient.factor2; } else { serializedGradient.factor2 = startSizeGradient.factor1; } serializationObject.startSizeGradients.push(serializedGradient); } } const lifeTimeGradients = particleSystem.getLifeTimeGradients(); if (lifeTimeGradients) { serializationObject.lifeTimeGradients = []; for (const lifeTimeGradient of lifeTimeGradients) { const serializedGradient = { gradient: lifeTimeGradient.gradient, factor1: lifeTimeGradient.factor1 }; if (lifeTimeGradient.factor2 !== void 0) { serializedGradient.factor2 = lifeTimeGradient.factor2; } else { serializedGradient.factor2 = lifeTimeGradient.factor1; } serializationObject.lifeTimeGradients.push(serializedGradient); } } const limitVelocityGradients = particleSystem.getLimitVelocityGradients(); if (limitVelocityGradients) { serializationObject.limitVelocityGradients = []; for (const limitVelocityGradient of limitVelocityGradients) { const serializedGradient = { gradient: limitVelocityGradient.gradient, factor1: limitVelocityGradient.factor1 }; if (limitVelocityGradient.factor2 !== void 0) { serializedGradient.factor2 = limitVelocityGradient.factor2; } else { serializedGradient.factor2 = limitVelocityGradient.factor1; } serializationObject.limitVelocityGradients.push(serializedGradient); } serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping; } if (particleSystem.noiseTexture) { serializationObject.noiseTexture = particleSystem.noiseTexture.serialize(); } } // Clone /** * Clones the particle system. * @param name The name of the cloned object * @param newEmitter The new emitter to use * @param cloneTexture Also clone the textures if true * @returns the cloned particle system */ clone(name260, newEmitter, cloneTexture = false) { const custom = { ...this._customWrappers }; let program = null; const engine = this._engine; if (engine.createEffectForParticles) { if (this.customShader != null) { program = this.customShader; const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : ""; const effect = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines); if (!custom[0]) { this.setCustomEffect(effect, 0); } else { custom[0].effect = effect; } } } const serialization = this.serialize(cloneTexture); const result = _ParticleSystem.Parse(serialization, this._scene || this._engine, this._rootUrl); result.name = name260; result.customShader = program; result._customWrappers = custom; if (newEmitter === void 0) { newEmitter = this.emitter; } if (this.noiseTexture) { result.noiseTexture = this.noiseTexture.clone(); } result.emitter = newEmitter; if (!this.preventAutoStart) { result.start(); } return result; } }; ParticleSystem.BILLBOARDMODE_Y = 2; ParticleSystem.BILLBOARDMODE_ALL = 7; ParticleSystem.BILLBOARDMODE_STRETCHED = 8; ParticleSystem.BILLBOARDMODE_STRETCHED_LOCAL = 9; SubEmitter._ParseParticleSystem = ParticleSystem.Parse; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.transformFeedback.js init_engine(); var _forceTransformFeedbackToBundle = true; Engine.prototype.createTransformFeedback = function() { const transformFeedback = this._gl.createTransformFeedback(); if (!transformFeedback) { throw new Error("Unable to create Transform Feedback"); } return transformFeedback; }; Engine.prototype.deleteTransformFeedback = function(value) { this._gl.deleteTransformFeedback(value); }; Engine.prototype.bindTransformFeedback = function(value) { this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value); }; Engine.prototype.beginTransformFeedback = function(usePoints = true) { this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES); }; Engine.prototype.endTransformFeedback = function() { this._gl.endTransformFeedback(); }; Engine.prototype.setTranformFeedbackVaryings = function(program, value) { this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS); }; Engine.prototype.bindTransformFeedbackBuffer = function(value) { this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value ? value.underlyingResource : null); }; Engine.prototype.readTransformFeedbackBuffer = function(target) { this._gl.getBufferSubData(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, target); }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneFragmentDeclaration2.js init_shaderStore(); var name244 = "clipPlaneFragmentDeclaration2"; var shader244 = `#ifdef CLIPPLANE in float fClipDistance; #endif #ifdef CLIPPLANE2 in float fClipDistance2; #endif #ifdef CLIPPLANE3 in float fClipDistance3; #endif #ifdef CLIPPLANE4 in float fClipDistance4; #endif #ifdef CLIPPLANE5 in float fClipDistance5; #endif #ifdef CLIPPLANE6 in float fClipDistance6; #endif `; if (!ShaderStore.IncludesShadersStore[name244]) { ShaderStore.IncludesShadersStore[name244] = shader244; } var clipPlaneFragmentDeclaration2 = { name: name244, shader: shader244 }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/gpuRenderParticles.fragment.js init_shaderStore(); init_imageProcessingDeclaration2(); init_logDepthDeclaration2(); init_helperFunctions2(); init_imageProcessingFunctions2(); init_fogFragmentDeclaration2(); init_clipPlaneFragment2(); init_logDepthFragment2(); init_fogFragment2(); var name245 = "gpuRenderParticlesPixelShader"; var shader245 = `precision highp float; #ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif uniform sampler2D diffuseSampler;varying vec2 vUV;varying vec4 vColor; #include #include #include #include #include #include void main() { #include vec4 textureColor=texture2D(diffuseSampler,vUV);gl_FragColor=textureColor*vColor; #ifdef BLENDMULTIPLYMODE float alpha=vColor.a*textureColor.a;gl_FragColor.rgb=gl_FragColor.rgb*alpha+vec3(1.0)*(1.0-alpha); #endif #include #include(color,gl_FragColor) #ifdef IMAGEPROCESSINGPOSTPROCESS gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb); #else #ifdef IMAGEPROCESSING gl_FragColor.rgb=toLinearSpace(gl_FragColor.rgb);gl_FragColor=applyImageProcessing(gl_FragColor); #endif #endif } `; if (!ShaderStore.ShadersStore[name245]) { ShaderStore.ShadersStore[name245] = shader245; } var gpuRenderParticlesPixelShader = { name: name245, shader: shader245 }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/ShadersInclude/clipPlaneVertexDeclaration2.js init_shaderStore(); var name246 = "clipPlaneVertexDeclaration2"; var shader246 = `#ifdef CLIPPLANE uniform vec4 vClipPlane;out float fClipDistance; #endif #ifdef CLIPPLANE2 uniform vec4 vClipPlane2;out float fClipDistance2; #endif #ifdef CLIPPLANE3 uniform vec4 vClipPlane3;out float fClipDistance3; #endif #ifdef CLIPPLANE4 uniform vec4 vClipPlane4;out float fClipDistance4; #endif #ifdef CLIPPLANE5 uniform vec4 vClipPlane5;out float fClipDistance5; #endif #ifdef CLIPPLANE6 uniform vec4 vClipPlane6;out float fClipDistance6; #endif `; if (!ShaderStore.IncludesShadersStore[name246]) { ShaderStore.IncludesShadersStore[name246] = shader246; } var clipPlaneVertexDeclaration2 = { name: name246, shader: shader246 }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/gpuRenderParticles.vertex.js init_shaderStore(); init_fogVertexDeclaration2(); init_logDepthDeclaration2(); init_clipPlaneVertex2(); init_fogVertex2(); init_logDepthVertex2(); var name247 = "gpuRenderParticlesVertexShader"; var shader247 = `precision highp float;uniform mat4 view;uniform mat4 projection;uniform vec2 translationPivot;uniform vec3 worldOffset; #ifdef LOCAL uniform mat4 emitterWM; #endif attribute vec3 position;attribute float age;attribute float life;attribute vec3 size; #ifndef BILLBOARD attribute vec3 initialDirection; #endif #ifdef BILLBOARDSTRETCHED attribute vec3 direction; #endif attribute float angle; #ifdef ANIMATESHEET attribute float cellIndex; #endif attribute vec2 offset;attribute vec2 uv;varying vec2 vUV;varying vec4 vColor;varying vec3 vPositionW; #if defined(BILLBOARD) && !defined(BILLBOARDY) && !defined(BILLBOARDSTRETCHED) uniform mat4 invView; #endif #include #include #include #ifdef COLORGRADIENTS uniform sampler2D colorGradientSampler; #else uniform vec4 colorDead;attribute vec4 color; #endif #ifdef ANIMATESHEET uniform vec3 sheetInfos; #endif #ifdef BILLBOARD uniform vec3 eyePosition; #endif vec3 rotate(vec3 yaxis,vec3 rotatedCorner) {vec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));vec3 zaxis=normalize(cross(yaxis,xaxis));vec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);vec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);vec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; #ifdef LOCAL return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; #else return (position+worldOffset)+alignedCorner; #endif } #ifdef BILLBOARDSTRETCHED vec3 rotateAlign(vec3 toCamera,vec3 rotatedCorner) {vec3 normalizedToCamera=normalize(toCamera);vec3 normalizedCrossDirToCamera=normalize(cross(normalize(direction),normalizedToCamera));vec3 crossProduct=normalize(cross(normalizedToCamera,normalizedCrossDirToCamera));vec3 row0=vec3(normalizedCrossDirToCamera.x,normalizedCrossDirToCamera.y,normalizedCrossDirToCamera.z);vec3 row1=vec3(crossProduct.x,crossProduct.y,crossProduct.z);vec3 row2=vec3(normalizedToCamera.x,normalizedToCamera.y,normalizedToCamera.z);mat3 rotMatrix= mat3(row0,row1,row2);vec3 alignedCorner=rotMatrix*rotatedCorner; #ifdef LOCAL return ((emitterWM*vec4(position,1.0)).xyz+worldOffset)+alignedCorner; #else return (position+worldOffset)+alignedCorner; #endif } #endif void main() { #ifdef ANIMATESHEET float rowOffset=floor(cellIndex/sheetInfos.z);float columnOffset=cellIndex-rowOffset*sheetInfos.z;vec2 uvScale=sheetInfos.xy;vec2 uvOffset=vec2(uv.x ,1.0-uv.y);vUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale; #else vUV=uv; #endif float ratio=min(1.0,age/life); #ifdef COLORGRADIENTS vColor=texture2D(colorGradientSampler,vec2(ratio,0)); #else vColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio); #endif vec2 cornerPos=(offset-translationPivot)*size.yz*size.x; #ifdef BILLBOARD vec4 rotatedCorner;rotatedCorner.w=0.; #ifdef BILLBOARDY rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.y=0.;rotatedCorner.xz+=translationPivot;vec3 yaxis=(position+worldOffset)-eyePosition;yaxis.y=0.;vPositionW=rotate(normalize(yaxis),rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); #elif defined(BILLBOARDSTRETCHED) rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot;vec3 toCamera=(position+worldOffset)-eyePosition;vPositionW=rotateAlign(toCamera,rotatedCorner.xyz);vec4 viewPosition=(view*vec4(vPositionW,1.0)); #else rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.z=0.;rotatedCorner.xy+=translationPivot; #ifdef LOCAL vec4 viewPosition=view*vec4(((emitterWM*vec4(position,1.0)).xyz+worldOffset),1.0)+rotatedCorner; #else vec4 viewPosition=view*vec4((position+worldOffset),1.0)+rotatedCorner; #endif vPositionW=(invView*viewPosition).xyz; #endif #else vec3 rotatedCorner;rotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);rotatedCorner.y=0.;rotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);rotatedCorner.xz+=translationPivot;vec3 yaxis=normalize(initialDirection);vPositionW=rotate(yaxis,rotatedCorner);vec4 viewPosition=view*vec4(vPositionW,1.0); #endif gl_Position=projection*viewPosition; #if defined(CLIPPLANE) || defined(CLIPPLANE2) || defined(CLIPPLANE3) || defined(CLIPPLANE4) || defined(CLIPPLANE5) || defined(CLIPPLANE6) || defined(FOG) vec4 worldPos=vec4(vPositionW,1.0); #endif #include #include #include }`; if (!ShaderStore.ShadersStore[name247]) { ShaderStore.ShadersStore[name247] = shader247; } var gpuRenderParticlesVertexShader = { name: name247, shader: shader247 }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/gpuParticleSystem.js init_observable(); init_math_vector(); init_math_color(); init_math_scalar_functions(); init_buffer(); init_imageProcessingConfiguration(); init_engineStore(); init_abstractEngine(); init_drawWrapper(); init_typeStore(); init_clipPlaneMaterialHelper(); init_scene(); init_materialHelper_functions(); var GPUParticleSystem = class _GPUParticleSystem extends BaseParticleSystem { static { __name(this, "GPUParticleSystem"); } /** * Gets a boolean indicating if the GPU particles can be rendered on current browser */ static get IsSupported() { if (!EngineStore.LastCreatedEngine) { return false; } const caps = EngineStore.LastCreatedEngine.getCaps(); return caps.supportTransformFeedbacks || caps.supportComputeShaders; } _createIndexBuffer() { this._linesIndexBufferUseInstancing = this._engine.createIndexBuffer(new Uint32Array([0, 1, 1, 3, 3, 2, 2, 0, 0, 3]), void 0, "GPUParticleSystemLinesIndexBuffer"); } /** * Gets the maximum number of particles active at the same time. * @returns The max number of active particles. */ getCapacity() { return this._capacity; } /** * Gets or set the number of active particles * The value cannot be greater than "capacity" (if it is, it will be limited to "capacity"). */ get maxActiveParticleCount() { return this._maxActiveParticleCount; } set maxActiveParticleCount(value) { this._maxActiveParticleCount = Math.min(value, this._capacity); } /** * Gets or set the number of active particles * @deprecated Please use maxActiveParticleCount instead. */ get activeParticleCount() { return this.maxActiveParticleCount; } set activeParticleCount(value) { this.maxActiveParticleCount = value; } /** * Creates a Point Emitter for the particle system (emits directly from the emitter position) * @param direction1 Particles are emitted between the direction1 and direction2 from within the box * @param direction2 Particles are emitted between the direction1 and direction2 from within the box * @returns the emitter */ createPointEmitter(direction1, direction2) { const particleEmitter = CreatePointEmitter(direction1, direction2); this.particleEmitterType = particleEmitter; return particleEmitter; } /** * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius) * @param radius The radius of the hemisphere to emit from * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius * @returns the emitter */ createHemisphericEmitter(radius = 1, radiusRange = 1) { const particleEmitter = CreateHemisphericEmitter(radius, radiusRange); this.particleEmitterType = particleEmitter; return particleEmitter; } /** * Creates a Sphere Emitter for the particle system (emits along the sphere radius) * @param radius The radius of the sphere to emit from * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius * @returns the emitter */ createSphereEmitter(radius = 1, radiusRange = 1) { const particleEmitter = CreateSphereEmitter(radius, radiusRange); this.particleEmitterType = particleEmitter; return particleEmitter; } /** * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2) * @param radius The radius of the sphere to emit from * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere * @returns the emitter */ createDirectedSphereEmitter(radius = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { const particleEmitter = CreateDirectedSphereEmitter(radius, direction1, direction2); this.particleEmitterType = particleEmitter; return particleEmitter; } /** * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position) * @param radius The radius of the emission cylinder * @param height The height of the emission cylinder * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius * @param directionRandomizer How much to randomize the particle direction [0-1] * @returns the emitter */ createCylinderEmitter(radius = 1, height = 1, radiusRange = 1, directionRandomizer = 0) { const particleEmitter = CreateCylinderEmitter(radius, height, radiusRange, directionRandomizer); this.particleEmitterType = particleEmitter; return particleEmitter; } /** * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2) * @param radius The radius of the cylinder to emit from * @param height The height of the emission cylinder * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default) * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder * @returns the emitter */ createDirectedCylinderEmitter(radius = 1, height = 1, radiusRange = 1, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { const particleEmitter = CreateDirectedCylinderEmitter(radius, height, radiusRange, direction1, direction2); this.particleEmitterType = particleEmitter; return particleEmitter; } /** * Creates a Cone Emitter for the particle system (emits from the cone to the particle position) * @param radius The radius of the cone to emit from * @param angle The base angle of the cone * @returns the emitter */ createConeEmitter(radius = 1, angle = Math.PI / 4) { const particleEmitter = CreateConeEmitter(radius, angle); this.particleEmitterType = particleEmitter; return particleEmitter; } createDirectedConeEmitter(radius = 1, angle = Math.PI / 4, direction1 = new Vector3(0, 1, 0), direction2 = new Vector3(0, 1, 0)) { const particleEmitter = CreateDirectedConeEmitter(radius, angle, direction1, direction2); this.particleEmitterType = particleEmitter; return particleEmitter; } /** * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox) * @param direction1 Particles are emitted between the direction1 and direction2 from within the box * @param direction2 Particles are emitted between the direction1 and direction2 from within the box * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox * @returns the emitter */ createBoxEmitter(direction1, direction2, minEmitBox, maxEmitBox) { const particleEmitter = new BoxParticleEmitter(); this.particleEmitterType = particleEmitter; this.direction1 = direction1; this.direction2 = direction2; this.minEmitBox = minEmitBox; this.maxEmitBox = maxEmitBox; return particleEmitter; } /** Gets or sets the current flow map */ get flowMap() { return this._flowMap; } set flowMap(value) { if (this._flowMap === value) { return; } this._flowMap = value; } /** * Is this system ready to be used/rendered * @returns true if the system is ready */ isReady() { if (!this.emitter || this._imageProcessingConfiguration && !this._imageProcessingConfiguration.isReady() || this._flowMap && !this._flowMap.isReady() || !this.particleTexture || !this.particleTexture.isReady() || this._rebuildingAfterContextLost) { return false; } if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) { if (!this._getWrapper(this.blendMode).effect.isReady()) { return false; } } else { if (!this._getWrapper(ParticleSystem.BLENDMODE_MULTIPLY).effect.isReady()) { return false; } if (!this._getWrapper(ParticleSystem.BLENDMODE_ADD).effect.isReady()) { return false; } } if (!this._platform.isUpdateBufferCreated()) { this._recreateUpdateEffect(); return false; } return this._platform.isUpdateBufferReady(); } /** * Gets if the system has been started. (Note: this will still be true after stop is called) * @returns True if it has been started, otherwise false. */ isStarted() { return this._started; } /** * Gets if the system has been stopped. (Note: rendering is still happening but the system is frozen) * @returns True if it has been stopped, otherwise false. */ isStopped() { return this._stopped; } /** * Gets a boolean indicating that the system is stopping * @returns true if the system is currently stopping */ isStopping() { return false; } /** * Gets the number of particles active at the same time. * @returns The number of active particles. */ getActiveCount() { return this._currentActiveCount; } /** * Starts the particle system and begins to emit * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default) */ start(delay = this.startDelay) { if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) { throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set"; } if (delay) { setTimeout(() => { this.start(0); }, delay); return; } this._started = true; this._stopped = false; this._actualFrame = 0; this._preWarmDone = false; if (this.beginAnimationOnStart && this.animations && this.animations.length > 0 && this._scene) { this._scene.beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop); } } /** * Stops the particle system. */ stop() { if (this._stopped) { return; } this.onStoppedObservable.notifyObservers(this); this._stopped = true; } /** * Remove all active particles */ reset() { this._releaseBuffers(); this._platform.releaseVertexBuffers(); this._currentActiveCount = 0; this._targetIndex = 0; } /** * Returns the string "GPUParticleSystem" * @returns a string containing the class name */ getClassName() { return "GPUParticleSystem"; } /** * Gets the custom effect used to render the particles * @param blendMode Blend mode for which the effect should be retrieved * @returns The effect */ getCustomEffect(blendMode = 0) { return this._customWrappers[blendMode]?.effect ?? this._customWrappers[0].effect; } _getCustomDrawWrapper(blendMode = 0) { return this._customWrappers[blendMode] ?? this._customWrappers[0]; } /** * Sets the custom effect used to render the particles * @param effect The effect to set * @param blendMode Blend mode for which the effect should be set */ setCustomEffect(effect, blendMode = 0) { this._customWrappers[blendMode] = new DrawWrapper(this._engine); this._customWrappers[blendMode].effect = effect; } /** * Observable that will be called just before the particles are drawn */ get onBeforeDrawParticlesObservable() { if (!this._onBeforeDrawParticlesObservable) { this._onBeforeDrawParticlesObservable = new Observable(); } return this._onBeforeDrawParticlesObservable; } /** * Gets the name of the particle vertex shader */ get vertexShaderName() { return "gpuRenderParticles"; } /** * Gets the vertex buffers used by the particle system * Should be called after render() has been called for the current frame so that the buffers returned are the ones that have been updated * in the current frame (there's a ping-pong between two sets of buffers - for a given frame, one set is used as the source and the other as the destination) */ get vertexBuffers() { return this._renderVertexBuffers[this._targetIndex ^ 1]; } /** * Gets the index buffer used by the particle system (null for GPU particle systems) */ get indexBuffer() { return null; } _removeGradientAndTexture(gradient, gradients, texture) { super._removeGradientAndTexture(gradient, gradients, texture); this._releaseBuffers(); return this; } /** * Adds a new color gradient * @param gradient defines the gradient to use (between 0 and 1) * @param color1 defines the color to affect to the specified gradient * @returns the current particle system */ addColorGradient(gradient, color1) { if (!this._colorGradients) { this._colorGradients = []; } const colorGradient = new ColorGradient(gradient, color1); this._colorGradients.push(colorGradient); this._refreshColorGradient(true); this._releaseBuffers(); return this; } _refreshColorGradient(reorder = false) { if (this._colorGradients) { if (reorder) { this._colorGradients.sort((a, b) => { if (a.gradient < b.gradient) { return -1; } else if (a.gradient > b.gradient) { return 1; } return 0; }); } if (this._colorGradientsTexture) { this._colorGradientsTexture.dispose(); this._colorGradientsTexture = null; } } } /** Force the system to rebuild all gradients that need to be resync */ forceRefreshGradients() { this._refreshColorGradient(); this._refreshFactorGradient(this._sizeGradients, "_sizeGradientsTexture"); this._refreshFactorGradient(this._angularSpeedGradients, "_angularSpeedGradientsTexture"); this._refreshFactorGradient(this._velocityGradients, "_velocityGradientsTexture"); this._refreshFactorGradient(this._limitVelocityGradients, "_limitVelocityGradientsTexture"); this._refreshFactorGradient(this._dragGradients, "_dragGradientsTexture"); this.reset(); } /** * Remove a specific color gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeColorGradient(gradient) { this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture); this._colorGradientsTexture = null; return this; } /** * Resets the draw wrappers cache */ resetDrawCache() { for (const blendMode in this._drawWrappers) { const drawWrapper = this._drawWrappers[blendMode]; drawWrapper.drawContext?.reset(); } } _addFactorGradient(factorGradients, gradient, factor) { const valueGradient = new FactorGradient(gradient, factor); factorGradients.push(valueGradient); this._releaseBuffers(); } /** * Adds a new size gradient * @param gradient defines the gradient to use (between 0 and 1) * @param factor defines the size factor to affect to the specified gradient * @returns the current particle system */ addSizeGradient(gradient, factor) { if (!this._sizeGradients) { this._sizeGradients = []; } this._addFactorGradient(this._sizeGradients, gradient, factor); this._refreshFactorGradient(this._sizeGradients, "_sizeGradientsTexture", true); this._releaseBuffers(); return this; } /** * Remove a specific size gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeSizeGradient(gradient) { this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture); this._sizeGradientsTexture = null; return this; } _refreshFactorGradient(factorGradients, textureName, reorder = false) { if (!factorGradients) { return; } if (reorder) { factorGradients.sort((a, b) => { if (a.gradient < b.gradient) { return -1; } else if (a.gradient > b.gradient) { return 1; } return 0; }); } const that = this; if (that[textureName]) { that[textureName].dispose(); that[textureName] = null; } } /** * Adds a new angular speed gradient * @param gradient defines the gradient to use (between 0 and 1) * @param factor defines the angular speed to affect to the specified gradient * @returns the current particle system */ addAngularSpeedGradient(gradient, factor) { if (!this._angularSpeedGradients) { this._angularSpeedGradients = []; } this._addFactorGradient(this._angularSpeedGradients, gradient, factor); this._refreshFactorGradient(this._angularSpeedGradients, "_angularSpeedGradientsTexture", true); this._releaseBuffers(); return this; } /** * Remove a specific angular speed gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeAngularSpeedGradient(gradient) { this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture); this._angularSpeedGradientsTexture = null; return this; } /** * Adds a new velocity gradient * @param gradient defines the gradient to use (between 0 and 1) * @param factor defines the velocity to affect to the specified gradient * @returns the current particle system */ addVelocityGradient(gradient, factor) { if (!this._velocityGradients) { this._velocityGradients = []; } this._addFactorGradient(this._velocityGradients, gradient, factor); this._refreshFactorGradient(this._velocityGradients, "_velocityGradientsTexture", true); this._releaseBuffers(); return this; } /** * Remove a specific velocity gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeVelocityGradient(gradient) { this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture); this._velocityGradientsTexture = null; return this; } /** * Adds a new limit velocity gradient * @param gradient defines the gradient to use (between 0 and 1) * @param factor defines the limit velocity value to affect to the specified gradient * @returns the current particle system */ addLimitVelocityGradient(gradient, factor) { if (!this._limitVelocityGradients) { this._limitVelocityGradients = []; } this._addFactorGradient(this._limitVelocityGradients, gradient, factor); this._refreshFactorGradient(this._limitVelocityGradients, "_limitVelocityGradientsTexture", true); this._releaseBuffers(); return this; } /** * Remove a specific limit velocity gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeLimitVelocityGradient(gradient) { this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture); this._limitVelocityGradientsTexture = null; return this; } /** * Adds a new drag gradient * @param gradient defines the gradient to use (between 0 and 1) * @param factor defines the drag value to affect to the specified gradient * @returns the current particle system */ addDragGradient(gradient, factor) { if (!this._dragGradients) { this._dragGradients = []; } this._addFactorGradient(this._dragGradients, gradient, factor); this._refreshFactorGradient(this._dragGradients, "_dragGradientsTexture", true); this._releaseBuffers(); return this; } /** * Remove a specific drag gradient * @param gradient defines the gradient to remove * @returns the current particle system */ removeDragGradient(gradient) { this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture); this._dragGradientsTexture = null; return this; } /** * Not supported by GPUParticleSystem * @returns the current particle system */ addEmitRateGradient() { return this; } /** * Not supported by GPUParticleSystem * @returns the current particle system */ removeEmitRateGradient() { return this; } /** * Not supported by GPUParticleSystem * @returns the current particle system */ addStartSizeGradient() { return this; } /** * Not supported by GPUParticleSystem * @returns the current particle system */ removeStartSizeGradient() { return this; } /** * Not supported by GPUParticleSystem * @returns the current particle system */ addColorRemapGradient() { return this; } /** * Not supported by GPUParticleSystem * @returns the current particle system */ removeColorRemapGradient() { return this; } /** * Not supported by GPUParticleSystem * @returns the current particle system */ addAlphaRemapGradient() { return this; } /** * Not supported by GPUParticleSystem * @returns the current particle system */ removeAlphaRemapGradient() { return this; } /** * Not supported by GPUParticleSystem * @returns the current particle system */ addRampGradient() { return this; } /** * Not supported by GPUParticleSystem * @returns the current particle system */ removeRampGradient() { return this; } /** * Not supported by GPUParticleSystem * @returns the list of ramp gradients */ getRampGradients() { return null; } /** * Not supported by GPUParticleSystem * Gets or sets a boolean indicating that ramp gradients must be used * @see https://doc.babylonjs.com/features/featuresDeepDive/particles/particle_system/particle_system_intro#ramp-gradients */ get useRampGradients() { return false; } set useRampGradients(value) { } /** * Not supported by GPUParticleSystem * @returns the current particle system */ addLifeTimeGradient() { return this; } /** * Not supported by GPUParticleSystem * @returns the current particle system */ removeLifeTimeGradient() { return this; } /** * Instantiates a GPU particle system. * Particles are often small sprites used to simulate hard-to-reproduce phenomena like fire, smoke, water, or abstract visual effects like magic glitter and faery dust. * @param name The name of the particle system * @param options The options used to create the system * @param sceneOrEngine The scene the particle system belongs to or the engine to use if no scene * @param customEffect a custom effect used to change the way particles are rendered by default * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture */ constructor(name260, options, sceneOrEngine, customEffect = null, isAnimationSheetEnabled = false) { super(name260); this.layerMask = 268435455; this._accumulatedCount = 0; this._renderVertexBuffers = []; this._targetIndex = 0; this._currentRenderId = -1; this._currentRenderingCameraUniqueId = -1; this._started = false; this._stopped = false; this._timeDelta = 0; this.updateInAnimate = false; this._actualFrame = 0; this._rawTextureWidth = 256; this._rebuildingAfterContextLost = false; this.onDisposeObservable = new Observable(); this.onStoppedObservable = new Observable(); this.onStartedObservable = new Observable(); this.forceDepthWrite = false; this._preWarmDone = false; this.isLocal = false; this.isGPU = true; this.metadata = null; this._flowMap = null; this.flowMapStrength = 1; this._onBeforeDrawParticlesObservable = null; if (!sceneOrEngine || sceneOrEngine.getClassName() === "Scene") { this._scene = sceneOrEngine || EngineStore.LastCreatedScene; this._engine = this._scene.getEngine(); this.uniqueId = this._scene.getUniqueId(); this._scene.particleSystems.push(this); } else { this._engine = sceneOrEngine; this.defaultProjectionMatrix = Matrix.PerspectiveFovLH(0.8, 1, 0.1, 100, this._engine.isNDCHalfZRange); } if (this._engine.getCaps().supportComputeShaders) { if (!GetClass("BABYLON.ComputeShaderParticleSystem")) { throw new Error("The ComputeShaderParticleSystem class is not available! Make sure you have imported it."); } this._platform = new (GetClass("BABYLON.ComputeShaderParticleSystem"))(this, this._engine); } else { if (!GetClass("BABYLON.WebGL2ParticleSystem")) { throw new Error("The WebGL2ParticleSystem class is not available! Make sure you have imported it."); } this._platform = new (GetClass("BABYLON.WebGL2ParticleSystem"))(this, this._engine); } this._customWrappers = { 0: new DrawWrapper(this._engine) }; this._customWrappers[0].effect = customEffect; this._drawWrappers = { 0: new DrawWrapper(this._engine) }; if (this._drawWrappers[0].drawContext) { this._drawWrappers[0].drawContext.useInstancing = true; } this._createIndexBuffer(); this._attachImageProcessingConfiguration(null); options = options ?? {}; if (!options.randomTextureSize) { delete options.randomTextureSize; } const fullOptions = { capacity: 5e4, randomTextureSize: this._engine.getCaps().maxTextureSize, ...options }; const optionsAsNumber = options; if (isFinite(optionsAsNumber)) { fullOptions.capacity = optionsAsNumber; } this._capacity = fullOptions.capacity; this._maxActiveParticleCount = fullOptions.capacity; this._currentActiveCount = 0; this._isAnimationSheetEnabled = isAnimationSheetEnabled; this.particleEmitterType = new BoxParticleEmitter(); const maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize); let d = []; for (let i = 0; i < maxTextureSize; ++i) { d.push(Math.random()); d.push(Math.random()); d.push(Math.random()); d.push(Math.random()); } this._randomTexture = new RawTexture(new Float32Array(d), maxTextureSize, 1, 5, sceneOrEngine, false, false, 1, 1); this._randomTexture.name = "GPUParticleSystem_random1"; this._randomTexture.wrapU = 1; this._randomTexture.wrapV = 1; d = []; for (let i = 0; i < maxTextureSize; ++i) { d.push(Math.random()); d.push(Math.random()); d.push(Math.random()); d.push(Math.random()); } this._randomTexture2 = new RawTexture(new Float32Array(d), maxTextureSize, 1, 5, sceneOrEngine, false, false, 1, 1); this._randomTexture2.name = "GPUParticleSystem_random2"; this._randomTexture2.wrapU = 1; this._randomTexture2.wrapV = 1; this._randomTextureSize = maxTextureSize; } _reset() { this._releaseBuffers(); } _createVertexBuffers(updateBuffer, renderBuffer, spriteSource) { const renderVertexBuffers = {}; renderVertexBuffers["position"] = renderBuffer.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true); let offset = 3; renderVertexBuffers["age"] = renderBuffer.createVertexBuffer("age", offset, 1, this._attributesStrideSize, true); offset += 1; renderVertexBuffers["size"] = renderBuffer.createVertexBuffer("size", offset, 3, this._attributesStrideSize, true); offset += 3; renderVertexBuffers["life"] = renderBuffer.createVertexBuffer("life", offset, 1, this._attributesStrideSize, true); offset += 1; offset += 4; if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) { renderVertexBuffers["direction"] = renderBuffer.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true); } offset += 3; if (this._platform.alignDataInBuffer) { offset += 1; } if (this.particleEmitterType instanceof CustomParticleEmitter) { offset += 3; if (this._platform.alignDataInBuffer) { offset += 1; } } if (!this._colorGradientsTexture) { renderVertexBuffers["color"] = renderBuffer.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true); offset += 4; } if (!this._isBillboardBased) { renderVertexBuffers["initialDirection"] = renderBuffer.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true); offset += 3; if (this._platform.alignDataInBuffer) { offset += 1; } } if (this.noiseTexture) { renderVertexBuffers["noiseCoordinates1"] = renderBuffer.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true); offset += 3; if (this._platform.alignDataInBuffer) { offset += 1; } renderVertexBuffers["noiseCoordinates2"] = renderBuffer.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true); offset += 3; if (this._platform.alignDataInBuffer) { offset += 1; } } renderVertexBuffers["angle"] = renderBuffer.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true); if (this._angularSpeedGradientsTexture) { offset++; } else { offset += 2; } if (this._isAnimationSheetEnabled) { renderVertexBuffers["cellIndex"] = renderBuffer.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true); offset += 1; if (this.spriteRandomStartCell) { renderVertexBuffers["cellStartOffset"] = renderBuffer.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true); offset += 1; } } renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2); renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2); this._renderVertexBuffers.push(renderVertexBuffers); this._platform.createVertexBuffers(updateBuffer, renderVertexBuffers); this.resetDrawCache(); } _initialize(force = false) { if (this._buffer0 && !force) { return; } const engine = this._engine; const data = []; this._attributesStrideSize = 21; this._targetIndex = 0; if (this._platform.alignDataInBuffer) { this._attributesStrideSize += 1; } if (this.particleEmitterType instanceof CustomParticleEmitter) { this._attributesStrideSize += 3; if (this._platform.alignDataInBuffer) { this._attributesStrideSize += 1; } } if (!this.isBillboardBased) { this._attributesStrideSize += 3; if (this._platform.alignDataInBuffer) { this._attributesStrideSize += 1; } } if (this._colorGradientsTexture) { this._attributesStrideSize -= 4; } if (this._angularSpeedGradientsTexture) { this._attributesStrideSize -= 1; } if (this._isAnimationSheetEnabled) { this._attributesStrideSize += 1; if (this.spriteRandomStartCell) { this._attributesStrideSize += 1; } } if (this.noiseTexture) { this._attributesStrideSize += 6; if (this._platform.alignDataInBuffer) { this._attributesStrideSize += 2; } } if (this._platform.alignDataInBuffer) { this._attributesStrideSize += 3 - (this._attributesStrideSize + 3 & 3); } const usingCustomEmitter = this.particleEmitterType instanceof CustomParticleEmitter; const tmpVector = TmpVectors.Vector3[0]; let offset = 0; for (let particleIndex = 0; particleIndex < this._capacity; particleIndex++) { data.push(0); data.push(0); data.push(0); data.push(0); data.push(0); data.push(0); data.push(0); data.push(0); data.push(Math.random()); data.push(Math.random()); data.push(Math.random()); data.push(Math.random()); if (usingCustomEmitter) { this.particleEmitterType.particleDestinationGenerator(particleIndex, null, tmpVector); data.push(tmpVector.x); data.push(tmpVector.y); data.push(tmpVector.z); } else { data.push(0); data.push(0); data.push(0); } if (this._platform.alignDataInBuffer) { data.push(0); } offset += 16; if (usingCustomEmitter) { this.particleEmitterType.particlePositionGenerator(particleIndex, null, tmpVector); data.push(tmpVector.x); data.push(tmpVector.y); data.push(tmpVector.z); if (this._platform.alignDataInBuffer) { data.push(0); } offset += 4; } if (!this._colorGradientsTexture) { data.push(0); data.push(0); data.push(0); data.push(0); offset += 4; } if (!this.isBillboardBased) { data.push(0); data.push(0); data.push(0); if (this._platform.alignDataInBuffer) { data.push(0); } offset += 4; } if (this.noiseTexture) { data.push(Math.random()); data.push(Math.random()); data.push(Math.random()); if (this._platform.alignDataInBuffer) { data.push(0); } data.push(Math.random()); data.push(Math.random()); data.push(Math.random()); if (this._platform.alignDataInBuffer) { data.push(0); } offset += 8; } data.push(0); offset += 1; if (!this._angularSpeedGradientsTexture) { data.push(0); offset += 1; } if (this._isAnimationSheetEnabled) { data.push(0); offset += 1; if (this.spriteRandomStartCell) { data.push(0); offset += 1; } } if (this._platform.alignDataInBuffer) { let numDummies = 3 - (offset + 3 & 3); offset += numDummies; while (numDummies-- > 0) { data.push(0); } } } const spriteData = new Float32Array([0.5, 0.5, 1, 1, -0.5, 0.5, 0, 1, 0.5, -0.5, 1, 0, -0.5, -0.5, 0, 0]); const bufferData1 = this._platform.createParticleBuffer(data); const bufferData2 = this._platform.createParticleBuffer(data); this._buffer0 = new Buffer2(engine, bufferData1, false, this._attributesStrideSize); this._buffer1 = new Buffer2(engine, bufferData2, false, this._attributesStrideSize); this._spriteBuffer = new Buffer2(engine, spriteData, false, 4); this._renderVertexBuffers = []; this._createVertexBuffers(this._buffer0, this._buffer1, this._spriteBuffer); this._createVertexBuffers(this._buffer1, this._buffer0, this._spriteBuffer); this._sourceBuffer = this._buffer0; this._targetBuffer = this._buffer1; } /** @internal */ _recreateUpdateEffect() { this._createColorGradientTexture(); this._createSizeGradientTexture(); this._createAngularSpeedGradientTexture(); this._createVelocityGradientTexture(); this._createLimitVelocityGradientTexture(); this._createDragGradientTexture(); let defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : ""; if (this._isBillboardBased) { defines += "\n#define BILLBOARD"; } if (this._colorGradientsTexture) { defines += "\n#define COLORGRADIENTS"; } if (this._sizeGradientsTexture) { defines += "\n#define SIZEGRADIENTS"; } if (this._angularSpeedGradientsTexture) { defines += "\n#define ANGULARSPEEDGRADIENTS"; } if (this._velocityGradientsTexture) { defines += "\n#define VELOCITYGRADIENTS"; } if (this._limitVelocityGradientsTexture) { defines += "\n#define LIMITVELOCITYGRADIENTS"; } if (this._dragGradientsTexture) { defines += "\n#define DRAGGRADIENTS"; } if (this._flowMap) { defines += "\n#define FLOWMAP"; } if (this.isAnimationSheetEnabled) { defines += "\n#define ANIMATESHEET"; if (this.spriteRandomStartCell) { defines += "\n#define ANIMATESHEETRANDOMSTART"; } } if (this.noiseTexture) { defines += "\n#define NOISE"; } if (this.isLocal) { defines += "\n#define LOCAL"; } if (this._platform.isUpdateBufferCreated() && this._cachedUpdateDefines === defines) { return this._platform.isUpdateBufferReady(); } this._cachedUpdateDefines = defines; this._updateBuffer = this._platform.createUpdateBuffer(defines); return this._platform.isUpdateBufferReady(); } /** * @internal */ _getWrapper(blendMode) { const customWrapper = this._getCustomDrawWrapper(blendMode); if (customWrapper?.effect) { return customWrapper; } const defines = []; this.fillDefines(defines, blendMode); let drawWrapper = this._drawWrappers[blendMode]; if (!drawWrapper) { drawWrapper = new DrawWrapper(this._engine); if (drawWrapper.drawContext) { drawWrapper.drawContext.useInstancing = true; } this._drawWrappers[blendMode] = drawWrapper; } const join = defines.join("\n"); if (drawWrapper.defines !== join) { const attributes = []; const uniforms = []; const samplers = []; this.fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers); drawWrapper.setEffect(this._engine.createEffect("gpuRenderParticles", attributes, uniforms, samplers, join), join); } return drawWrapper; } /** * @internal */ static _GetAttributeNamesOrOptions(hasColorGradients = false, isAnimationSheetEnabled = false, isBillboardBased = false, isBillboardStretched = false) { const attributeNamesOrOptions = [VertexBuffer.PositionKind, "age", "life", "size", "angle"]; if (!hasColorGradients) { attributeNamesOrOptions.push(VertexBuffer.ColorKind); } if (isAnimationSheetEnabled) { attributeNamesOrOptions.push("cellIndex"); } if (!isBillboardBased) { attributeNamesOrOptions.push("initialDirection"); } if (isBillboardStretched) { attributeNamesOrOptions.push("direction"); } attributeNamesOrOptions.push("offset", VertexBuffer.UVKind); return attributeNamesOrOptions; } /** * @internal */ static _GetEffectCreationOptions(isAnimationSheetEnabled = false, useLogarithmicDepth = false, applyFog = false) { const effectCreationOption = ["emitterWM", "worldOffset", "view", "projection", "colorDead", "invView", "translationPivot", "eyePosition"]; AddClipPlaneUniforms(effectCreationOption); if (isAnimationSheetEnabled) { effectCreationOption.push("sheetInfos"); } if (useLogarithmicDepth) { effectCreationOption.push("logarithmicDepthConstant"); } if (applyFog) { effectCreationOption.push("vFogInfos"); effectCreationOption.push("vFogColor"); } return effectCreationOption; } /** * Fill the defines array according to the current settings of the particle system * @param defines Array to be updated * @param blendMode blend mode to take into account when updating the array * @param fillImageProcessing fills the image processing defines */ fillDefines(defines, blendMode = 0, fillImageProcessing = true) { if (this._scene) { PrepareStringDefinesForClipPlanes(this, this._scene, defines); if (this.applyFog && this._scene.fogEnabled && this._scene.fogMode !== Scene.FOGMODE_NONE) { defines.push("#define FOG"); } } if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) { defines.push("#define BLENDMULTIPLYMODE"); } if (this.isLocal) { defines.push("#define LOCAL"); } if (this.useLogarithmicDepth) { defines.push("#define LOGARITHMICDEPTH"); } if (this._isBillboardBased) { defines.push("#define BILLBOARD"); switch (this.billboardMode) { case ParticleSystem.BILLBOARDMODE_Y: defines.push("#define BILLBOARDY"); break; case ParticleSystem.BILLBOARDMODE_STRETCHED: defines.push("#define BILLBOARDSTRETCHED"); break; case ParticleSystem.BILLBOARDMODE_ALL: defines.push("#define BILLBOARDMODE_ALL"); break; default: break; } } if (this._colorGradientsTexture) { defines.push("#define COLORGRADIENTS"); } if (this.isAnimationSheetEnabled) { defines.push("#define ANIMATESHEET"); } if (fillImageProcessing && this._imageProcessingConfiguration) { this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines); defines.push("" + this._imageProcessingConfigurationDefines.toString()); } } /** * Fill the uniforms, attributes and samplers arrays according to the current settings of the particle system * @param uniforms Uniforms array to fill * @param attributes Attributes array to fill * @param samplers Samplers array to fill */ fillUniformsAttributesAndSamplerNames(uniforms, attributes, samplers) { attributes.push(..._GPUParticleSystem._GetAttributeNamesOrOptions(!!this._colorGradientsTexture, this._isAnimationSheetEnabled, this._isBillboardBased, this._isBillboardBased && this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED)); uniforms.push(..._GPUParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled, this.useLogarithmicDepth, this.applyFog)); samplers.push("diffuseSampler", "colorGradientSampler"); if (this._imageProcessingConfiguration) { ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines); ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines); } } /** * Animates the particle system for the current frame by emitting new particles and or animating the living ones. * @param preWarm defines if we are in the pre-warmimg phase */ animate(preWarm = false) { this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene?.getAnimationRatio() || 1); this._actualFrame += this._timeDelta; if (!this._stopped) { if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) { this.stop(); } } if (this.updateInAnimate) { this._update(); } } _createFactorGradientTexture(factorGradients, textureName) { const texture = this[textureName]; if (!factorGradients || !factorGradients.length || texture) { return; } const data = new Float32Array(this._rawTextureWidth); for (let x = 0; x < this._rawTextureWidth; x++) { const ratio = x / this._rawTextureWidth; GradientHelper.GetCurrentGradient(ratio, factorGradients, (currentGradient, nextGradient, scale) => { data[x] = Lerp(currentGradient.factor1, nextGradient.factor1, scale); }); } this[textureName] = RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene || this._engine, false, false, 1); this[textureName].name = textureName.substring(1); } _createSizeGradientTexture() { this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture"); } _createAngularSpeedGradientTexture() { this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture"); } _createVelocityGradientTexture() { this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture"); } _createLimitVelocityGradientTexture() { this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture"); } _createDragGradientTexture() { this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture"); } _createColorGradientTexture() { if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) { return; } const data = new Uint8Array(this._rawTextureWidth * 4); const tmpColor = TmpColors.Color4[0]; for (let x = 0; x < this._rawTextureWidth; x++) { const ratio = x / this._rawTextureWidth; GradientHelper.GetCurrentGradient(ratio, this._colorGradients, (currentGradient, nextGradient, scale) => { Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor); data[x * 4] = tmpColor.r * 255; data[x * 4 + 1] = tmpColor.g * 255; data[x * 4 + 2] = tmpColor.b * 255; data[x * 4 + 3] = tmpColor.a * 255; }); } this._colorGradientsTexture = RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, 1); this._colorGradientsTexture.name = "colorGradients"; } _render(blendMode, emitterWM) { const drawWrapper = this._getWrapper(blendMode); const effect = drawWrapper.effect; this._engine.enableEffect(drawWrapper); const viewMatrix = this._scene?.getViewMatrix() || Matrix.IdentityReadOnly; effect.setMatrix("view", viewMatrix); effect.setMatrix("projection", this.defaultProjectionMatrix ?? this._scene.getProjectionMatrix()); effect.setTexture("diffuseSampler", this.particleTexture); effect.setVector2("translationPivot", this.translationPivot); const worldOffset = this.worldOffset.subtractToRef(this._scene?.floatingOriginOffset || Vector3.ZeroReadOnly, TmpVectors.Vector3[0]); effect.setVector3("worldOffset", worldOffset); if (this.isLocal) { effect.setMatrix("emitterWM", emitterWM); } if (this._colorGradientsTexture) { effect.setTexture("colorGradientSampler", this._colorGradientsTexture); } else { effect.setDirectColor4("colorDead", this.colorDead); } if (this._isAnimationSheetEnabled && this.particleTexture) { const baseSize = this.particleTexture.getBaseSize(); effect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth); } if (this._isBillboardBased && this._scene) { const camera = this._scene.activeCamera; effect.setVector3("eyePosition", camera.globalPosition); } const defines = effect.defines; if (this._scene) { BindClipPlane(effect, this, this._scene); if (this.applyFog) { BindFogParameters(this._scene, void 0, effect); } } if (defines.indexOf("#define BILLBOARDMODE_ALL") >= 0) { const invView = viewMatrix.clone(); invView.invert(); effect.setMatrix("invView", invView); } if (this.useLogarithmicDepth && this._scene) { BindLogDepth(defines, effect, this._scene); } if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) { this._imageProcessingConfiguration.bind(effect); } this._setEngineBasedOnBlendMode(blendMode); this._platform.bindDrawBuffers(this._targetIndex, effect, this._scene?.forceWireframe ? this._linesIndexBufferUseInstancing : null); if (this._onBeforeDrawParticlesObservable) { this._onBeforeDrawParticlesObservable.notifyObservers(effect); } if (this._scene?.forceWireframe) { this._engine.drawElementsType(6, 0, 10, this._currentActiveCount); } else { this._engine.drawArraysType(7, 0, 4, this._currentActiveCount); } this._engine.setAlphaMode(0); if (this._scene?.forceWireframe) { this._engine.unbindInstanceAttributes(); } return this._currentActiveCount; } /** @internal */ _update(emitterWM) { if (!this.emitter || !this._targetBuffer) { return; } if (!this._recreateUpdateEffect() || this._rebuildingAfterContextLost) { return; } if (!emitterWM) { if (this.emitter.position) { const emitterMesh = this.emitter; emitterWM = emitterMesh.getWorldMatrix(); } else { const emitterPosition = this.emitter; emitterWM = TmpVectors.Matrix[0]; Matrix.TranslationToRef(emitterPosition.x, emitterPosition.y, emitterPosition.z, emitterWM); } } const engine = this._engine; const depthWriteState = engine.getDepthWrite(); engine.setDepthWrite(false); this._platform.preUpdateParticleBuffer(); this._updateBuffer.setFloat("currentCount", this._currentActiveCount); this._updateBuffer.setFloat("timeDelta", this._timeDelta); this._updateBuffer.setFloat("stopFactor", this._stopped ? 0 : 1); this._updateBuffer.setInt("randomTextureSize", this._randomTextureSize); this._updateBuffer.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime); this._updateBuffer.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower); if (!this._colorGradientsTexture) { this._updateBuffer.setDirectColor4("color1", this.color1); this._updateBuffer.setDirectColor4("color2", this.color2); } this._updateBuffer.setFloat2("sizeRange", this.minSize, this.maxSize); this._updateBuffer.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY); this._updateBuffer.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation); this._updateBuffer.setVector3("gravity", this.gravity); if (this._limitVelocityGradientsTexture) { this._updateBuffer.setFloat("limitVelocityDamping", this.limitVelocityDamping); } if (this.particleEmitterType) { this.particleEmitterType.applyToShader(this._updateBuffer); } if (this._isAnimationSheetEnabled) { this._updateBuffer.setFloat4("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed, this.spriteCellLoop ? 1 : 0); } if (this.noiseTexture) { this._updateBuffer.setVector3("noiseStrength", this.noiseStrength); } if (this._flowMap) { const scene = this.getScene(); this._updateBuffer.setFloat("flowMapStrength", this.flowMapStrength); this._updateBuffer.setMatrix("flowMapProjection", scene.getTransformMatrix()); } if (!this.isLocal) { this._updateBuffer.setMatrix("emitterWM", emitterWM); } this._platform.updateParticleBuffer(this._targetIndex, this._targetBuffer, this._currentActiveCount); this._targetIndex++; if (this._targetIndex === 2) { this._targetIndex = 0; } const tmpBuffer = this._sourceBuffer; this._sourceBuffer = this._targetBuffer; this._targetBuffer = tmpBuffer; engine.setDepthWrite(depthWriteState); } /** * Renders the particle system in its current state * @param preWarm defines if the system should only update the particles but not render them * @param forceUpdateOnly if true, force to only update the particles and never display them (meaning, even if preWarm=false, when forceUpdateOnly=true the particles won't be displayed) * @returns the current number of particles */ render(preWarm = false, forceUpdateOnly = false) { if (!this._started) { return 0; } if (!this.isReady()) { return 0; } if (!preWarm && this._scene) { if (!this._preWarmDone && this.preWarmCycles) { for (let index = 0; index < this.preWarmCycles; index++) { this.animate(true); this.render(true, true); } this._preWarmDone = true; } if (this._currentRenderId === this._scene.getRenderId() && (!this._scene.activeCamera || this._scene.activeCamera && this._currentRenderingCameraUniqueId === this._scene.activeCamera.uniqueId)) { return 0; } this._currentRenderId = this._scene.getRenderId(); if (this._scene.activeCamera) { this._currentRenderingCameraUniqueId = this._scene.activeCamera.uniqueId; } } this._initialize(); if (this.manualEmitCount > -1) { this._accumulatedCount += this.manualEmitCount; this.manualEmitCount = 0; } else { this._accumulatedCount += this.emitRate * this._timeDelta; } if (this._accumulatedCount >= 1) { const intPart = this._accumulatedCount | 0; this._accumulatedCount -= intPart; this._currentActiveCount += intPart; } this._currentActiveCount = Math.min(this._maxActiveParticleCount, this._currentActiveCount); if (!this._currentActiveCount) { return 0; } let emitterWM; if (this.emitter.position) { const emitterMesh = this.emitter; emitterWM = emitterMesh.getWorldMatrix(); } else { const emitterPosition = this.emitter; emitterWM = TmpVectors.Matrix[0]; Matrix.TranslationToRef(emitterPosition.x, emitterPosition.y, emitterPosition.z, emitterWM); } const engine = this._engine; if (!this.updateInAnimate) { this._update(emitterWM); } let outparticles = 0; if (!preWarm && !forceUpdateOnly) { engine.setState(false); if (this.forceDepthWrite) { engine.setDepthWrite(true); } if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) { outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY, emitterWM) + this._render(ParticleSystem.BLENDMODE_ADD, emitterWM); } else { outparticles = this._render(this.blendMode, emitterWM); } this._engine.setAlphaMode(0); } return outparticles; } /** * Rebuilds the particle system */ rebuild() { const checkUpdateEffect = /* @__PURE__ */ __name(() => { if (!this._recreateUpdateEffect() || !this._platform.isUpdateBufferReady()) { setTimeout(checkUpdateEffect, 10); } else { this._initialize(true); this._rebuildingAfterContextLost = false; } }, "checkUpdateEffect"); this._createIndexBuffer(); this._cachedUpdateDefines = ""; this._platform.contextLost(); this._rebuildingAfterContextLost = true; checkUpdateEffect(); } _releaseBuffers() { if (this._buffer0) { this._buffer0.dispose(); this._buffer0 = null; } if (this._buffer1) { this._buffer1.dispose(); this._buffer1 = null; } if (this._spriteBuffer) { this._spriteBuffer.dispose(); this._spriteBuffer = null; } this._platform.releaseBuffers(); } /** * Disposes the particle system and free the associated resources * @param disposeTexture defines if the particule texture must be disposed as well (true by default) */ dispose(disposeTexture = true) { for (const blendMode in this._drawWrappers) { const drawWrapper = this._drawWrappers[blendMode]; drawWrapper.dispose(); } this._drawWrappers = {}; if (this._scene) { const index = this._scene.particleSystems.indexOf(this); if (index > -1) { this._scene.particleSystems.splice(index, 1); } } this._releaseBuffers(); this._platform.releaseVertexBuffers(); for (let i = 0; i < this._renderVertexBuffers.length; ++i) { const rvb = this._renderVertexBuffers[i]; for (const key in rvb) { rvb[key].dispose(); } } this._renderVertexBuffers = []; if (this._colorGradientsTexture) { this._colorGradientsTexture.dispose(); this._colorGradientsTexture = null; } if (this._sizeGradientsTexture) { this._sizeGradientsTexture.dispose(); this._sizeGradientsTexture = null; } if (this._angularSpeedGradientsTexture) { this._angularSpeedGradientsTexture.dispose(); this._angularSpeedGradientsTexture = null; } if (this._velocityGradientsTexture) { this._velocityGradientsTexture.dispose(); this._velocityGradientsTexture = null; } if (this._limitVelocityGradientsTexture) { this._limitVelocityGradientsTexture.dispose(); this._limitVelocityGradientsTexture = null; } if (this._dragGradientsTexture) { this._dragGradientsTexture.dispose(); this._dragGradientsTexture = null; } if (this._randomTexture) { this._randomTexture.dispose(); this._randomTexture = null; } if (this._randomTexture2) { this._randomTexture2.dispose(); this._randomTexture2 = null; } if (disposeTexture && this.particleTexture) { this.particleTexture.dispose(); this.particleTexture = null; } if (disposeTexture && this.noiseTexture) { this.noiseTexture.dispose(); this.noiseTexture = null; } this.onStoppedObservable.clear(); this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); } /** * Clones the particle system. * @param name The name of the cloned object * @param newEmitter The new emitter to use * @param cloneTexture Also clone the textures if true * @returns the cloned particle system */ clone(name260, newEmitter, cloneTexture = false) { const custom = { ...this._customWrappers }; let program = null; const engine = this._engine; if (engine.createEffectForParticles) { if (this.customShader != null) { program = this.customShader; const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : ""; custom[0] = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines, void 0, void 0, void 0, this); } } const serialization = this.serialize(cloneTexture); const result = _GPUParticleSystem.Parse(serialization, this._scene || this._engine, this._rootUrl); result.name = name260; result.customShader = program; result._customWrappers = custom; if (newEmitter === void 0) { newEmitter = this.emitter; } if (this.noiseTexture) { result.noiseTexture = this.noiseTexture.clone(); } result.emitter = newEmitter; return result; } /** * Serializes the particle system to a JSON object * @param serializeTexture defines if the texture must be serialized as well * @returns the JSON object */ serialize(serializeTexture = false) { const serializationObject = {}; ParticleSystem._Serialize(serializationObject, this, serializeTexture); serializationObject.activeParticleCount = this.activeParticleCount; serializationObject.randomTextureSize = this._randomTextureSize; serializationObject.customShader = this.customShader; serializationObject.preventAutoStart = this.preventAutoStart; serializationObject.worldOffset = this.worldOffset.asArray(); if (this.metadata) { serializationObject.metadata = this.metadata; } return serializationObject; } /** * Parses a JSON object to create a GPU particle system. * @param parsedParticleSystem The JSON object to parse * @param sceneOrEngine The scene or the engine to create the particle system in * @param rootUrl The root url to use to load external dependencies like texture * @param doNotStart Ignore the preventAutoStart attribute and does not start * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used) * @returns the parsed GPU particle system */ static Parse(parsedParticleSystem, sceneOrEngine, rootUrl, doNotStart = false, capacity) { const name260 = parsedParticleSystem.name; let engine; let scene; if (sceneOrEngine instanceof AbstractEngine) { engine = sceneOrEngine; } else { scene = sceneOrEngine; engine = scene.getEngine(); } const particleSystem = new _GPUParticleSystem(name260, { capacity: capacity || parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, sceneOrEngine, null, parsedParticleSystem.isAnimationSheetEnabled); particleSystem._rootUrl = rootUrl; if (parsedParticleSystem.customShader && engine.createEffectForParticles) { const program = parsedParticleSystem.customShader; const defines = program.shaderOptions.defines.length > 0 ? program.shaderOptions.defines.join("\n") : ""; const custom = engine.createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines, void 0, void 0, void 0, particleSystem); particleSystem.setCustomEffect(custom, 0); particleSystem.customShader = program; } if (parsedParticleSystem.id) { particleSystem.id = parsedParticleSystem.id; } if (parsedParticleSystem.activeParticleCount) { particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount; } ParticleSystem._Parse(parsedParticleSystem, particleSystem, sceneOrEngine, rootUrl); if (parsedParticleSystem.worldOffset) { particleSystem.worldOffset = Vector3.FromArray(parsedParticleSystem.worldOffset); } if (parsedParticleSystem.preventAutoStart) { particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart; } if (parsedParticleSystem.metadata) { particleSystem.metadata = parsedParticleSystem.metadata; } if (!doNotStart && !particleSystem.preventAutoStart) { particleSystem.start(); } return particleSystem; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/particleSystemSet.js init_math_color(); init_engineStore(); var ParticleSystemSetEmitterCreationOptions = class { static { __name(this, "ParticleSystemSetEmitterCreationOptions"); } }; var ParticleSystemSet = class _ParticleSystemSet { static { __name(this, "ParticleSystemSet"); } constructor() { this._emitterNodeIsOwned = true; this.systems = []; } /** * Gets or sets the emitter node used with this set */ get emitterNode() { return this._emitterNode; } set emitterNode(value) { if (this._emitterNodeIsOwned && this._emitterNode) { if (this._emitterNode.dispose) { this._emitterNode.dispose(); } this._emitterNodeIsOwned = false; } for (const system of this.systems) { system.emitter = value; } this._emitterNode = value; } /** * Creates a new emitter mesh as a sphere * @param options defines the options used to create the sphere * @param options.diameter * @param options.segments * @param options.color * @param renderingGroupId defines the renderingGroupId to use for the sphere * @param scene defines the hosting scene */ setEmitterAsSphere(options, renderingGroupId, scene) { if (this._emitterNodeIsOwned && this._emitterNode) { if (this._emitterNode.dispose) { this._emitterNode.dispose(); } } this._emitterNodeIsOwned = true; this._emitterCreationOptions = { kind: "Sphere", options, renderingGroupId }; const emitterMesh = CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene); emitterMesh.renderingGroupId = renderingGroupId; const material = new StandardMaterial("emitterSphereMaterial", scene); material.emissiveColor = options.color; emitterMesh.material = material; for (const system of this.systems) { system.emitter = emitterMesh; } this._emitterNode = emitterMesh; } /** * Starts all particle systems of the set * @param emitter defines an optional mesh to use as emitter for the particle systems */ start(emitter) { for (const system of this.systems) { if (emitter) { system.emitter = emitter; } system.start(); } } /** * Release all associated resources */ dispose() { for (const system of this.systems) { system.dispose(); } this.systems.length = 0; if (this._emitterNode) { if (this._emitterNode.dispose) { this._emitterNode.dispose(); } this._emitterNode = null; } } /** * Serialize the set into a JSON compatible object * @param serializeTexture defines if the texture must be serialized as well * @returns a JSON compatible representation of the set */ serialize(serializeTexture = false) { const result = {}; result.systems = []; for (const system of this.systems) { result.systems.push(system.serialize(serializeTexture)); } if (this._emitterNode) { result.emitter = this._emitterCreationOptions; } return result; } /** * Parse a new ParticleSystemSet from a serialized source * @param data defines a JSON compatible representation of the set * @param scene defines the hosting scene * @param gpu defines if we want GPU particles or CPU particles * @param capacity defines the system capacity (if null or undefined the sotred capacity will be used) * @returns a new ParticleSystemSet */ static Parse(data, scene, gpu = false, capacity) { const result = new _ParticleSystemSet(); const rootUrl = this.BaseAssetsUrl + "/textures/"; scene = scene || EngineStore.LastCreatedScene; for (const system of data.systems) { result.systems.push(gpu ? GPUParticleSystem.Parse(system, scene, rootUrl, true, capacity) : ParticleSystem.Parse(system, scene, rootUrl, true, capacity)); } if (data.emitter) { const options = data.emitter.options; switch (data.emitter.kind) { case "Sphere": result.setEmitterAsSphere({ diameter: options.diameter, segments: options.segments, color: Color3.FromArray(options.color) }, data.emitter.renderingGroupId, scene); break; } } return result; } }; ParticleSystemSet.BaseAssetsUrl = "https://assets.babylonjs.com/particles"; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/Enums/nodeParticleBlockConnectionPointTypes.js var NodeParticleBlockConnectionPointTypes; (function(NodeParticleBlockConnectionPointTypes2) { NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["Int"] = 1] = "Int"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["Float"] = 2] = "Float"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["Vector2"] = 4] = "Vector2"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["Vector3"] = 8] = "Vector3"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["Matrix"] = 16] = "Matrix"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["Particle"] = 32] = "Particle"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["Texture"] = 64] = "Texture"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["Color4"] = 128] = "Color4"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["FloatGradient"] = 256] = "FloatGradient"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["Vector2Gradient"] = 512] = "Vector2Gradient"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["Vector3Gradient"] = 1024] = "Vector3Gradient"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["Color4Gradient"] = 2048] = "Color4Gradient"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["System"] = 4096] = "System"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["AutoDetect"] = 8192] = "AutoDetect"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["BasedOnInput"] = 16384] = "BasedOnInput"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["Undefined"] = 32768] = "Undefined"; NodeParticleBlockConnectionPointTypes2[NodeParticleBlockConnectionPointTypes2["All"] = 65535] = "All"; })(NodeParticleBlockConnectionPointTypes || (NodeParticleBlockConnectionPointTypes = {})); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/nodeParticleBlockConnectionPoint.js init_observable(); var NodeParticleConnectionPointCompatibilityStates; (function(NodeParticleConnectionPointCompatibilityStates2) { NodeParticleConnectionPointCompatibilityStates2[NodeParticleConnectionPointCompatibilityStates2["Compatible"] = 0] = "Compatible"; NodeParticleConnectionPointCompatibilityStates2[NodeParticleConnectionPointCompatibilityStates2["TypeIncompatible"] = 1] = "TypeIncompatible"; NodeParticleConnectionPointCompatibilityStates2[NodeParticleConnectionPointCompatibilityStates2["HierarchyIssue"] = 2] = "HierarchyIssue"; })(NodeParticleConnectionPointCompatibilityStates || (NodeParticleConnectionPointCompatibilityStates = {})); var NodeParticleConnectionPointDirection; (function(NodeParticleConnectionPointDirection2) { NodeParticleConnectionPointDirection2[NodeParticleConnectionPointDirection2["Input"] = 0] = "Input"; NodeParticleConnectionPointDirection2[NodeParticleConnectionPointDirection2["Output"] = 1] = "Output"; })(NodeParticleConnectionPointDirection || (NodeParticleConnectionPointDirection = {})); var NodeParticleConnectionPoint = class { static { __name(this, "NodeParticleConnectionPoint"); } /** Gets the direction of the point */ get direction() { return this._direction; } /** * Gets or sets the connection point type (default is float) */ get type() { if (this._type === NodeParticleBlockConnectionPointTypes.AutoDetect) { if (this._ownerBlock.isInput) { return this._ownerBlock.type; } if (this._connectedPoint) { return this._connectedPoint.type; } if (this._linkedConnectionSource) { if (this._linkedConnectionSource.isConnected) { return this._linkedConnectionSource.type; } if (this._linkedConnectionSource._defaultConnectionPointType) { return this._linkedConnectionSource._defaultConnectionPointType; } } if (this._defaultConnectionPointType) { return this._defaultConnectionPointType; } } if (this._type === NodeParticleBlockConnectionPointTypes.BasedOnInput) { if (this._typeConnectionSource) { if (!this._typeConnectionSource.isConnected && this._defaultConnectionPointType) { return this._defaultConnectionPointType; } if (this._typeConnectionSourceTranslation) { return this._typeConnectionSourceTranslation(this._typeConnectionSource.type); } return this._typeConnectionSource.type; } else if (this._defaultConnectionPointType) { return this._defaultConnectionPointType; } } return this._type; } set type(value) { this._type = value; } /** * Gets a boolean indicating that the current point is connected to another NodeMaterialBlock */ get isConnected() { return this.connectedPoint !== null || this.hasEndpoints; } /** Get the other side of the connection (if any) */ get connectedPoint() { return this._connectedPoint; } /** Get the block that owns this connection point */ get ownerBlock() { return this._ownerBlock; } /** Get the block connected on the other side of this connection (if any) */ get sourceBlock() { if (!this._connectedPoint) { return null; } return this._connectedPoint.ownerBlock; } /** Get the block connected on the endpoints of this connection (if any) */ get connectedBlocks() { if (this._endpoints.length === 0) { return []; } return this._endpoints.map((e) => e.ownerBlock); } /** Gets the list of connected endpoints */ get endpoints() { return this._endpoints; } /** Gets a boolean indicating if that output point is connected to at least one input */ get hasEndpoints() { return this._endpoints && this._endpoints.length > 0; } /** Get the inner type (ie AutoDetect for instance instead of the inferred one) */ get innerType() { if (this._linkedConnectionSource && !this._isMainLinkSource && this._linkedConnectionSource.isConnected) { return this.type; } return this._type; } /** * 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 */ constructor(name260, ownerBlock, direction) { this._connectedPoint = null; this._storedValue = null; this._storedFunction = null; this._acceptedConnectionPointType = null; this._endpoints = new Array(); this._type = NodeParticleBlockConnectionPointTypes.Particle; this._linkedConnectionSource = null; this._typeConnectionSource = null; this._typeConnectionSourceTranslation = null; this._defaultConnectionPointType = null; this._isMainLinkSource = false; this.acceptedConnectionPointTypes = []; this.excludedConnectionPointTypes = []; this.onConnectionObservable = new Observable(); this.onDisconnectionObservable = new Observable(); this.isExposedOnFrame = false; this.exposedPortPosition = -1; this.defaultValue = null; this.value = null; this.valueMin = null; this.valueMax = null; this._ownerBlock = ownerBlock; this.name = name260; this._direction = direction; } /** * Gets the current class name e.g. "NodeMaterialConnectionPoint" * @returns the class name */ getClassName() { return "NodeParticleConnectionPoint"; } /** * Gets the value represented by this connection point * @param state current evaluation state * @returns the connected value or the value if nothing is connected */ getConnectedValue(state) { if (this.isConnected) { if (this._connectedPoint?._storedFunction) { return this._connectedPoint._storedFunction(state); } return this._connectedPoint._storedValue; } return this.value; } /** * Gets a boolean indicating if the current point can be connected to another point * @param connectionPoint defines the other connection point * @returns a boolean */ canConnectTo(connectionPoint) { return this.checkCompatibilityState(connectionPoint) === 0; } /** * 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 */ checkCompatibilityState(connectionPoint) { const ownerBlock = this._ownerBlock; const otherBlock = connectionPoint.ownerBlock; if (this.type !== connectionPoint.type && connectionPoint.innerType !== NodeParticleBlockConnectionPointTypes.AutoDetect) { if (connectionPoint.acceptedConnectionPointTypes && connectionPoint.acceptedConnectionPointTypes.indexOf(this.type) !== -1) { return 0; } else { return 1; } } if (connectionPoint.excludedConnectionPointTypes && connectionPoint.excludedConnectionPointTypes.indexOf(this.type) !== -1) { return 1; } let targetBlock = otherBlock; let sourceBlock = ownerBlock; if (this.direction === 0) { targetBlock = ownerBlock; sourceBlock = otherBlock; } if (targetBlock.isAnAncestorOf(sourceBlock)) { return 2; } return 0; } /** * 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 */ connectTo(connectionPoint, ignoreConstraints = false) { if (!ignoreConstraints && !this.canConnectTo(connectionPoint)) { throw `Cannot connect these two connectors. source: "${this.ownerBlock.name}".${this.name}, target: "${connectionPoint.ownerBlock.name}".${connectionPoint.name}`; } this._endpoints.push(connectionPoint); connectionPoint._connectedPoint = this; 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 */ disconnectFrom(endpoint) { const index = this._endpoints.indexOf(endpoint); if (index === -1) { return this; } this._endpoints.splice(index, 1); endpoint._connectedPoint = null; this.onDisconnectionObservable.notifyObservers(endpoint); endpoint.onDisconnectionObservable.notifyObservers(this); return this; } /** * Fill the list of excluded connection point types with all types other than those passed in the parameter * @param mask Types (ORed values of NodeMaterialBlockConnectionPointTypes) that are allowed, and thus will not be pushed to the excluded list */ addExcludedConnectionPointFromAllowedTypes(mask) { let bitmask = 1; while (bitmask < NodeParticleBlockConnectionPointTypes.All) { if (!(mask & bitmask)) { this.excludedConnectionPointTypes.push(bitmask); } bitmask = bitmask << 1; } } /** * 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 */ serialize(isInput = true) { const serializationObject = {}; serializationObject.name = this.name; serializationObject.displayName = this.displayName; if (this.value !== void 0 && this.value !== null) { if (this.value.asArray) { serializationObject.valueType = "BABYLON." + this.value.getClassName(); serializationObject.value = this.value.asArray(); } else { serializationObject.valueType = "number"; serializationObject.value = this.value; } } if (isInput && this.connectedPoint) { serializationObject.inputName = this.name; serializationObject.targetBlockId = this.connectedPoint.ownerBlock.uniqueId; serializationObject.targetConnectionName = this.connectedPoint.name; serializationObject.isExposedOnFrame = true; serializationObject.exposedPortPosition = this.exposedPortPosition; } if (this.isExposedOnFrame || this.exposedPortPosition >= 0) { serializationObject.isExposedOnFrame = true; serializationObject.exposedPortPosition = this.exposedPortPosition; } return serializationObject; } /** * Release resources */ dispose() { this.onConnectionObservable.clear(); this.onDisconnectionObservable.clear(); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/nodeParticleBlock.js init_tslib_es6(); init_decorators(); init_uniqueIdGenerator(); init_logger(); init_observable(); init_typeStore(); var NodeParticleBlock = class { static { __name(this, "NodeParticleBlock"); } /** * Gets a boolean indicating if this block is a teleport out */ get isTeleportOut() { return this._isTeleportOut; } /** * Gets a boolean indicating if this block is a teleport in */ get isTeleportIn() { return this._isTeleportIn; } /** * Gets a boolean indicating that this block is a system block */ get isSystem() { return this._isSystem; } /** * Gets a boolean indicating that this block is an input block */ get isInput() { return this._isInput; } /** * Gets a boolean indicating if this block is a debug block */ get isDebug() { return this._isDebug; } /** * Gets or set the name of the block */ get name() { return this._name; } set name(value) { this._name = value; } /** * Gets the current class name e.g. "NodeParticleBlock" * @returns the class name */ getClassName() { return "NodeParticleBlock"; } /** * Gets the list of input points */ get inputs() { return this._inputs; } /** Gets the list of output points */ get outputs() { return this._outputs; } /** * Creates a new NodeParticleBlock * @param name defines the block name */ constructor(name260) { this._name = ""; this._isInput = false; this._isSystem = false; this._isDebug = false; this._isTeleportOut = false; this._isTeleportIn = false; this._inputs = new Array(); this._outputs = new Array(); this.onBuildObservable = new Observable(); this.onDisposeObservable = new Observable(); this.onInputChangedObservable = new Observable(); this.visibleOnFrame = false; this._name = name260; this.uniqueId = UniqueIdGenerator.UniqueId; } _inputRename(name260) { return name260; } _outputRename(name260) { return name260; } /** * Checks if the current block is an ancestor of a given block * @param block defines the potential descendant block to check * @returns true if block is a descendant */ isAnAncestorOf(block) { for (const output of this._outputs) { if (!output.hasEndpoints) { continue; } for (const endpoint of output.endpoints) { if (endpoint.ownerBlock === block) { return true; } if (endpoint.ownerBlock.isAnAncestorOf(block)) { return true; } } } return false; } /** * Checks if the current block is an ancestor of a given type * @param type defines the potential type to check * @returns true if block is a descendant */ isAnAncestorOfType(type) { if (this.getClassName() === type) { return true; } for (const output of this._outputs) { if (!output.hasEndpoints) { continue; } for (const endpoint of output.endpoints) { if (endpoint.ownerBlock.isAnAncestorOfType(type)) { return true; } } } return false; } /** * 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 */ getInputByName(name260) { const filter = this._inputs.filter((e) => e.name === name260); if (filter.length) { return filter[0]; } return null; } _linkConnectionTypes(inputIndex0, inputIndex1, looseCoupling = false) { if (looseCoupling) { this._inputs[inputIndex1]._acceptedConnectionPointType = this._inputs[inputIndex0]; } else { this._inputs[inputIndex0]._linkedConnectionSource = this._inputs[inputIndex1]; this._inputs[inputIndex0]._isMainLinkSource = true; } this._inputs[inputIndex1]._linkedConnectionSource = this._inputs[inputIndex0]; } /** * 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 value value to return if there is no connection * @param valueMin min value accepted for value * @param valueMax max value accepted for value * @returns the current block */ registerInput(name260, type, isOptional = false, value, valueMin, valueMax) { const point = new NodeParticleConnectionPoint( name260, this, 0 /* NodeParticleConnectionPointDirection.Input */ ); point.type = type; point.isOptional = isOptional; point.defaultValue = value; point.value = value; point.valueMin = valueMin; point.valueMax = valueMax; this._inputs.push(point); this.onInputChangedObservable.notifyObservers(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 point an already created connection point. If not provided, create a new one * @returns the current block */ registerOutput(name260, type, point) { point = point ?? new NodeParticleConnectionPoint( name260, this, 1 /* NodeParticleConnectionPointDirection.Output */ ); point.type = type; this._outputs.push(point); return this; } /** * Builds the block. Must be implemented by derived classes. * @param _state defines the current build state */ _build(_state) { } _customBuildStep(_state) { } /** * Builds the block * @param state defines the current build state * @returns the built block */ build(state) { if (this._buildId === state.buildId) { return true; } if (this._outputs.length > 0) { if (!this._outputs.some((o) => o.hasEndpoints) && !this.isDebug && !this.isSystem) { return false; } } this._buildId = state.buildId; for (const input of this._inputs) { if (!input.connectedPoint) { if (!input.isOptional) { state.notConnectedNonOptionalInputs.push(input); } continue; } const block = input.connectedPoint.ownerBlock; if (block && block !== this && !block.isSystem) { block.build(state); } } this._customBuildStep(state); if (state.verbose) { Logger.Log(`Building ${this.name} [${this.getClassName()}]`); } this._build(state); this.onBuildObservable.notifyObservers(this); return false; } /** * Serializes this block in a JSON representation * @returns the serialized block object */ serialize() { const serializationObject = {}; serializationObject.customType = "BABYLON." + this.getClassName(); serializationObject.id = this.uniqueId; serializationObject.name = this.name; serializationObject.visibleOnFrame = this.visibleOnFrame; serializationObject.comments = this.comments; serializationObject.inputs = []; serializationObject.outputs = []; for (const input of this.inputs) { serializationObject.inputs.push(input.serialize()); } for (const output of this.outputs) { serializationObject.outputs.push(output.serialize(false)); } return serializationObject; } /** * @internal */ _deserialize(serializationObject) { this._name = serializationObject.name; this.comments = serializationObject.comments; this.visibleOnFrame = !!serializationObject.visibleOnFrame; this._deserializePortDisplayNamesAndExposedOnFrame(serializationObject); } _deserializePortDisplayNamesAndExposedOnFrame(serializationObject) { const serializedInputs = serializationObject.inputs; const serializedOutputs = serializationObject.outputs; if (serializedInputs) { for (const port of serializedInputs) { const input = this.inputs.find((i) => i.name === port.name); if (!input) { return; } if (port.displayName) { input.displayName = port.displayName; } if (port.isExposedOnFrame) { input.isExposedOnFrame = port.isExposedOnFrame; input.exposedPortPosition = port.exposedPortPosition; } if (port.value !== void 0 && port.value !== null) { if (port.valueType === "number") { input.value = port.value; } else { const valueType = GetClass(port.valueType); if (valueType) { input.value = valueType.FromArray(port.value); } } } } } if (serializedOutputs) { for (let i = 0; i < serializedOutputs.length; i++) { const port = serializedOutputs[i]; if (port.displayName) { this.outputs[i].displayName = port.displayName; } if (port.isExposedOnFrame) { this.outputs[i].isExposedOnFrame = port.isExposedOnFrame; this.outputs[i].exposedPortPosition = port.exposedPortPosition; } } } } /** * Clone the current block to a new identical block * @returns a copy of the current block */ clone() { const serializationObject = this.serialize(); const blockType = GetClass(serializationObject.customType); if (blockType) { const block = new blockType(); block._deserialize(serializationObject); return block; } return null; } /** * Release resources */ dispose() { this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); for (const input of this.inputs) { input.dispose(); } for (const output of this.outputs) { output.dispose(); } this.onBuildObservable.clear(); this.onInputChangedObservable.clear(); } }; __decorate([ serialize("comment") ], NodeParticleBlock.prototype, "comments", void 0); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Decorators/nodeDecorator.js var PropertyTypeForEdition; (function(PropertyTypeForEdition2) { PropertyTypeForEdition2[PropertyTypeForEdition2["Boolean"] = 0] = "Boolean"; PropertyTypeForEdition2[PropertyTypeForEdition2["Float"] = 1] = "Float"; PropertyTypeForEdition2[PropertyTypeForEdition2["Int"] = 2] = "Int"; PropertyTypeForEdition2[PropertyTypeForEdition2["Vector2"] = 3] = "Vector2"; PropertyTypeForEdition2[PropertyTypeForEdition2["Vector3"] = 4] = "Vector3"; PropertyTypeForEdition2[PropertyTypeForEdition2["List"] = 5] = "List"; PropertyTypeForEdition2[PropertyTypeForEdition2["Color4"] = 6] = "Color4"; PropertyTypeForEdition2[PropertyTypeForEdition2["SamplingMode"] = 7] = "SamplingMode"; PropertyTypeForEdition2[PropertyTypeForEdition2["TextureFormat"] = 8] = "TextureFormat"; PropertyTypeForEdition2[PropertyTypeForEdition2["TextureType"] = 9] = "TextureType"; PropertyTypeForEdition2[PropertyTypeForEdition2["String"] = 10] = "String"; PropertyTypeForEdition2[PropertyTypeForEdition2["Matrix"] = 11] = "Matrix"; })(PropertyTypeForEdition || (PropertyTypeForEdition = {})); function editableInPropertyPage(displayName, propertyType = 0, groupName = "PROPERTIES", options) { return (target, propertyKey) => { let propStore = target._propStore; if (!propStore) { propStore = []; target._propStore = propStore; } propStore.push({ propertyName: propertyKey, displayName, type: propertyType, groupName, options: options ?? {}, className: target.getClassName() }); }; } __name(editableInPropertyPage, "editableInPropertyPage"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/Enums/nodeParticleContextualSources.js var NodeParticleContextualSources; (function(NodeParticleContextualSources2) { NodeParticleContextualSources2[NodeParticleContextualSources2["None"] = 0] = "None"; NodeParticleContextualSources2[NodeParticleContextualSources2["Position"] = 1] = "Position"; NodeParticleContextualSources2[NodeParticleContextualSources2["Direction"] = 2] = "Direction"; NodeParticleContextualSources2[NodeParticleContextualSources2["Age"] = 3] = "Age"; NodeParticleContextualSources2[NodeParticleContextualSources2["Lifetime"] = 4] = "Lifetime"; NodeParticleContextualSources2[NodeParticleContextualSources2["Color"] = 5] = "Color"; NodeParticleContextualSources2[NodeParticleContextualSources2["ScaledDirection"] = 6] = "ScaledDirection"; NodeParticleContextualSources2[NodeParticleContextualSources2["Scale"] = 7] = "Scale"; NodeParticleContextualSources2[NodeParticleContextualSources2["AgeGradient"] = 8] = "AgeGradient"; NodeParticleContextualSources2[NodeParticleContextualSources2["Angle"] = 9] = "Angle"; NodeParticleContextualSources2[NodeParticleContextualSources2["SpriteCellIndex"] = 16] = "SpriteCellIndex"; NodeParticleContextualSources2[NodeParticleContextualSources2["SpriteCellStart"] = 17] = "SpriteCellStart"; NodeParticleContextualSources2[NodeParticleContextualSources2["SpriteCellEnd"] = 18] = "SpriteCellEnd"; NodeParticleContextualSources2[NodeParticleContextualSources2["InitialColor"] = 19] = "InitialColor"; NodeParticleContextualSources2[NodeParticleContextualSources2["ColorDead"] = 20] = "ColorDead"; NodeParticleContextualSources2[NodeParticleContextualSources2["InitialDirection"] = 21] = "InitialDirection"; })(NodeParticleContextualSources || (NodeParticleContextualSources = {})); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/Enums/nodeParticleSystemSources.js var NodeParticleSystemSources; (function(NodeParticleSystemSources2) { NodeParticleSystemSources2[NodeParticleSystemSources2["None"] = 0] = "None"; NodeParticleSystemSources2[NodeParticleSystemSources2["Time"] = 1] = "Time"; NodeParticleSystemSources2[NodeParticleSystemSources2["Delta"] = 2] = "Delta"; NodeParticleSystemSources2[NodeParticleSystemSources2["Emitter"] = 3] = "Emitter"; NodeParticleSystemSources2[NodeParticleSystemSources2["CameraPosition"] = 4] = "CameraPosition"; })(NodeParticleSystemSources || (NodeParticleSystemSources = {})); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/nodeParticleBuildState.js init_math_vector(); init_math_color(); var NodeParticleBuildState = class { static { __name(this, "NodeParticleBuildState"); } constructor() { this.notConnectedNonOptionalInputs = []; this.particleContext = null; this.systemContext = null; this.gradientIndex = 0; this.nextGradientIndex = 0; } /** * Emits errors if any */ emitErrors() { let errorMessage = ""; for (const notConnectedInput of this.notConnectedNonOptionalInputs) { errorMessage += `input ${notConnectedInput.name} from block ${notConnectedInput.ownerBlock.name}[${notConnectedInput.ownerBlock.getClassName()}] is not connected and is not optional. `; } if (errorMessage) { throw "Build of Node Particle System Set failed:\n" + errorMessage; } } /** * Adapt a value to a target type * @param source defines the value to adapt * @param targetType defines the target type * @returns the adapted value */ adapt(source, targetType) { const value = source.getConnectedValue(this) || 0; if (source.type === targetType) { return value; } switch (targetType) { case NodeParticleBlockConnectionPointTypes.Vector2: return new Vector2(value, value); case NodeParticleBlockConnectionPointTypes.Vector3: return new Vector3(value, value, value); case NodeParticleBlockConnectionPointTypes.Color4: return new Color4(value, value, value, value); } return null; } /** * Gets the value associated with a contextual source * @param source Source of the contextual value * @returns the value associated with the source */ getContextualValue(source) { if (!this.particleContext || !this.systemContext) { return null; } switch (source) { case NodeParticleContextualSources.Position: return this.particleContext.position; case NodeParticleContextualSources.Direction: return this.particleContext.direction; case NodeParticleContextualSources.ScaledDirection: this.particleContext.direction.scaleToRef(this.systemContext._directionScale, this.systemContext._scaledDirection); return this.systemContext._scaledDirection; case NodeParticleContextualSources.Color: return this.particleContext.color; case NodeParticleContextualSources.InitialColor: return this.particleContext.initialColor; case NodeParticleContextualSources.ColorDead: return this.particleContext.colorDead; case NodeParticleContextualSources.Age: return this.particleContext.age; case NodeParticleContextualSources.Lifetime: return this.particleContext.lifeTime; case NodeParticleContextualSources.Angle: return this.particleContext.angle; case NodeParticleContextualSources.Scale: return this.particleContext.scale; case NodeParticleContextualSources.AgeGradient: return this.particleContext.age / this.particleContext.lifeTime; case NodeParticleContextualSources.SpriteCellEnd: return this.systemContext.endSpriteCellID; case NodeParticleContextualSources.SpriteCellIndex: return this.particleContext.cellIndex; case NodeParticleContextualSources.SpriteCellStart: return this.systemContext.startSpriteCellID; case NodeParticleContextualSources.InitialDirection: return this.particleContext._initialDirection; } return null; } /** * Gets a boolean indicating if the emitter is a transform node (or a simple vector3) */ get isEmitterTransformNode() { if (!this.systemContext) { return false; } if (this.systemContext.emitter.position) { return true; } return false; } /** * Gets the emitter world matrix */ get emitterWorldMatrix() { if (!this.systemContext) { return null; } return this.systemContext._emitterWorldMatrix; } /** * Gets the emitter inverse world matrix */ get emitterInverseWorldMatrix() { if (!this.systemContext) { return null; } return this.systemContext._emitterInverseWorldMatrix; } /** * Gets the emitter position */ get emitterPosition() { if (!this.systemContext) { return null; } if (this.isEmitterTransformNode) { return this.systemContext.emitter.absolutePosition; } return this.systemContext.emitter; } /** * Gets the value associated with a system source * @param source Source of the system value * @returns the value associated with the source */ getSystemValue(source) { if (!this.particleContext || !this.systemContext) { return null; } switch (source) { case NodeParticleSystemSources.Time: return this.systemContext._actualFrame; case NodeParticleSystemSources.Delta: return this.systemContext._scaledUpdateSpeed; case NodeParticleSystemSources.Emitter: if (this.isEmitterTransformNode) { const emitterMesh = this.systemContext.emitter; return emitterMesh.absolutePosition; } else { return this.systemContext.emitter; } case NodeParticleSystemSources.CameraPosition: return this.scene.activeCamera?.globalPosition || Vector3.Zero(); } return null; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/Blocks/Triggers/triggerTools.js function _TriggerSubEmitter(template, scene, location2) { const newState = new NodeParticleBuildState(); newState.scene = scene; const clone = template.createSystem(newState); clone.canStart = () => true; clone.emitter = location2.clone(); clone.disposeOnStop = true; clone.start(); return clone; } __name(_TriggerSubEmitter, "_TriggerSubEmitter"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/Blocks/systemBlock.js init_tslib_es6(); init_typeStore(); var SystemBlock = class _SystemBlock extends NodeParticleBlock { static { __name(this, "SystemBlock"); } /** * Create a new SystemBlock * @param name defines the block name */ constructor(name260) { super(name260); this.blendMode = BaseParticleSystem.BLENDMODE_ONEONE; this.capacity = 1e3; this.emitRate = 10; this.targetStopDuration = 0; this.startDelay = 0; this.doNoStart = false; this._internalId = _SystemBlock._IdCounter++; this._isSystem = true; this.registerInput("particle", NodeParticleBlockConnectionPointTypes.Particle); this.registerInput("texture", NodeParticleBlockConnectionPointTypes.Texture); this.registerInput("onStart", NodeParticleBlockConnectionPointTypes.System, true); this.registerInput("onEnd", NodeParticleBlockConnectionPointTypes.System, true); this.registerOutput("system", NodeParticleBlockConnectionPointTypes.System); } /** * Gets the current class name * @returns the class name */ getClassName() { return "SystemBlock"; } /** * Gets the particle input component */ get particle() { return this._inputs[0]; } /** * Gets the texture input component */ get texture() { return this._inputs[1]; } /** * Gets the onStart input component */ get onStart() { return this._inputs[2]; } /** * Gets the onEnd input component */ get onEnd() { return this._inputs[3]; } /** * Gets the system output component */ get system() { return this._outputs[0]; } /** * Builds the block and return a functional particle system * @param state defines the building state * @returns the built particle system */ createSystem(state) { state.capacity = this.capacity; state.buildId = this._buildId++; this.build(state); const particleSystem = this.particle.getConnectedValue(state); particleSystem.particleTexture = this.texture.getConnectedValue(state); particleSystem.emitRate = this.emitRate; particleSystem.blendMode = this.blendMode; particleSystem.name = this.name; particleSystem._targetStopDuration = this.targetStopDuration; particleSystem.startDelay = this.startDelay; this.system._storedValue = this; particleSystem.canStart = () => { return !this.doNoStart; }; particleSystem.onStartedObservable.add((system) => { const onStartSystem = this.onStart.getConnectedValue(state); if (onStartSystem) { system.onStartedObservable.addOnce(() => { state.systemContext = particleSystem; const clone = _TriggerSubEmitter(onStartSystem, state.scene, state.emitterPosition); this.onDisposeObservable.addOnce(() => { clone.dispose(); }); }); } const onEndSystem = this.onEnd.getConnectedValue(state); if (onEndSystem) { system.onStoppedObservable.addOnce(() => { state.systemContext = particleSystem; const clone = _TriggerSubEmitter(onEndSystem, state.scene, state.emitterPosition); this.onDisposeObservable.addOnce(() => { clone.dispose(); }); }); } }); this.onDisposeObservable.addOnce(() => { particleSystem.dispose(); }); return particleSystem; } serialize() { const serializationObject = super.serialize(); serializationObject.capacity = this.capacity; serializationObject.emitRate = this.emitRate; serializationObject.blendMode = this.blendMode; serializationObject.doNoStart = this.doNoStart; serializationObject.targetStopDuration = this.targetStopDuration; serializationObject.startDelay = this.startDelay; return serializationObject; } _deserialize(serializationObject) { super._deserialize(serializationObject); this.capacity = serializationObject.capacity; this.emitRate = serializationObject.emitRate; this.doNoStart = !!serializationObject.doNoStart; if (serializationObject.blendMode !== void 0) { this.blendMode = serializationObject.blendMode; } if (serializationObject.targetStopDuration !== void 0) { this.targetStopDuration = serializationObject.targetStopDuration; } if (serializationObject.startDelay !== void 0) { this.startDelay = serializationObject.startDelay; } } }; SystemBlock._IdCounter = 0; __decorate([ editableInPropertyPage("Blend mode", 5, "ADVANCED", { notifiers: { rebuild: true }, embedded: true, options: [ { label: "OneOne", value: BaseParticleSystem.BLENDMODE_ONEONE }, { label: "Standard", value: BaseParticleSystem.BLENDMODE_STANDARD }, { label: "Add", value: BaseParticleSystem.BLENDMODE_ADD }, { label: "Multiply", value: BaseParticleSystem.BLENDMODE_MULTIPLY }, { label: "MultiplyAdd", value: BaseParticleSystem.BLENDMODE_MULTIPLYADD } ] }) ], SystemBlock.prototype, "blendMode", void 0); __decorate([ editableInPropertyPage("Capacity", 2, "ADVANCED", { embedded: true, notifiers: { rebuild: true }, min: 0, max: 1e4 }) ], SystemBlock.prototype, "capacity", void 0); __decorate([ editableInPropertyPage("Emit rate", 2, "ADVANCED", { embedded: true, notifiers: { rebuild: true }, min: 0 }) ], SystemBlock.prototype, "emitRate", void 0); __decorate([ editableInPropertyPage("Target duration", 1, "ADVANCED", { embedded: true, notifiers: { rebuild: true }, min: 0 }) ], SystemBlock.prototype, "targetStopDuration", void 0); __decorate([ editableInPropertyPage("Delay start(ms)", 1, "ADVANCED", { embedded: true, notifiers: { rebuild: true }, min: 0 }) ], SystemBlock.prototype, "startDelay", void 0); __decorate([ editableInPropertyPage("Do no start", 0, "ADVANCED", { embedded: true, notifiers: { rebuild: true } }) ], SystemBlock.prototype, "doNoStart", void 0); RegisterClass("BABYLON.SystemBlock", SystemBlock); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/Blocks/particleInputBlock.js init_observable(); init_typeStore(); init_math_vector(); init_math_color(); var ParticleInputBlock = class extends NodeParticleBlock { static { __name(this, "ParticleInputBlock"); } /** * Gets or sets the connection point type (default is float) */ get type() { if (this._type === NodeParticleBlockConnectionPointTypes.AutoDetect) { if (this.value != null) { if (!isNaN(this.value)) { this._type = NodeParticleBlockConnectionPointTypes.Float; return this._type; } switch (this.value.getClassName()) { case "Vector2": this._type = NodeParticleBlockConnectionPointTypes.Vector2; return this._type; case "Vector3": this._type = NodeParticleBlockConnectionPointTypes.Vector3; return this._type; case "Color4": this._type = NodeParticleBlockConnectionPointTypes.Color4; return this._type; case "Matrix": this._type = NodeParticleBlockConnectionPointTypes.Matrix; return this._type; } } } return this._type; } /** * Gets a boolean indicating that the current connection point is a system source */ get isSystemSource() { return this._contextualSource === NodeParticleContextualSources.None && this._systemSource !== NodeParticleSystemSources.None; } /** * Gets or sets the system source used by this input block */ get systemSource() { return this._systemSource; } set systemSource(value) { this._systemSource = value; if (value !== NodeParticleSystemSources.None) { this._contextualSource = NodeParticleContextualSources.None; this._type = NodeParticleBlockConnectionPointTypes.Float; switch (value) { case NodeParticleSystemSources.Time: case NodeParticleSystemSources.Delta: this._type = NodeParticleBlockConnectionPointTypes.Float; break; case NodeParticleSystemSources.Emitter: case NodeParticleSystemSources.CameraPosition: this._type = NodeParticleBlockConnectionPointTypes.Vector3; break; } if (this.output) { this.output.type = this._type; } } } /** * Gets a boolean indicating that the current connection point is a contextual value */ get isContextual() { return this._contextualSource !== NodeParticleContextualSources.None; } /** * Gets or sets the current contextual value */ get contextualValue() { return this._contextualSource; } set contextualValue(value) { this._contextualSource = value; if (value !== NodeParticleContextualSources.None) { this._systemSource = NodeParticleSystemSources.None; switch (value) { case NodeParticleContextualSources.Scale: this._type = NodeParticleBlockConnectionPointTypes.Vector2; break; case NodeParticleContextualSources.Position: case NodeParticleContextualSources.Direction: case NodeParticleContextualSources.ScaledDirection: case NodeParticleContextualSources.InitialDirection: this._type = NodeParticleBlockConnectionPointTypes.Vector3; break; case NodeParticleContextualSources.Color: case NodeParticleContextualSources.InitialColor: case NodeParticleContextualSources.ColorDead: this._type = NodeParticleBlockConnectionPointTypes.Color4; break; case NodeParticleContextualSources.Age: case NodeParticleContextualSources.Lifetime: case NodeParticleContextualSources.Angle: case NodeParticleContextualSources.AgeGradient: this._type = NodeParticleBlockConnectionPointTypes.Float; break; case NodeParticleContextualSources.SpriteCellEnd: case NodeParticleContextualSources.SpriteCellStart: case NodeParticleContextualSources.SpriteCellIndex: this._type = NodeParticleBlockConnectionPointTypes.Int; break; } if (this.output) { this.output.type = this._type; } } } /** * Creates a new InputBlock * @param name defines the block name * @param type defines the type of the input (can be set to NodeParticleBlockConnectionPointTypes.AutoDetect) */ constructor(name260, type = NodeParticleBlockConnectionPointTypes.AutoDetect) { super(name260); this._type = NodeParticleBlockConnectionPointTypes.Undefined; this.min = 0; this.max = 0; this.groupInInspector = ""; this.displayInInspector = true; this.onValueChangedObservable = new Observable(); this._systemSource = NodeParticleSystemSources.None; this._contextualSource = NodeParticleContextualSources.None; this._type = type; this._isInput = true; this._storedValue = null; this.setDefaultValue(); this.registerOutput("output", type); } /** * Gets or sets the value of that point. * Please note that this value will be ignored if valueCallback is defined */ get value() { return this._storedValue; } set value(value) { if (this.type === NodeParticleBlockConnectionPointTypes.Float) { if (this.min !== this.max) { value = Math.max(this.min, value); value = Math.min(this.max, value); } } this._storedValue = value; this.onValueChangedObservable.notifyObservers(this); } /** * 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 valueCallback() { return this._valueCallback; } set valueCallback(value) { this._valueCallback = value; } /** * Gets the current class name * @returns the class name */ getClassName() { return "ParticleInputBlock"; } /** * Gets the output component */ get output() { return this._outputs[0]; } /** * Set the input block to its default value (based on its type) */ setDefaultValue() { switch (this.type) { case NodeParticleBlockConnectionPointTypes.Int: case NodeParticleBlockConnectionPointTypes.Float: this.value = 0; break; case NodeParticleBlockConnectionPointTypes.Vector2: this.value = Vector2.Zero(); break; case NodeParticleBlockConnectionPointTypes.Vector3: this.value = Vector3.Zero(); break; case NodeParticleBlockConnectionPointTypes.Color4: this.value = new Color4(1, 1, 1, 1); break; case NodeParticleBlockConnectionPointTypes.Matrix: this.value = Matrix.Identity(); break; } } _build(state) { super._build(state); if (this.isSystemSource) { this.output._storedValue = null; this.output._storedFunction = (state2) => { return state2.getSystemValue(this._systemSource); }; } else if (this.isContextual) { this.output._storedValue = null; this.output._storedFunction = (state2) => { return state2.getContextualValue(this._contextualSource); }; } else { this.output._storedValue = this.value; this.output._storedFunction = () => { return this.value; }; } } dispose() { this.onValueChangedObservable.clear(); super.dispose(); } serialize() { const serializationObject = super.serialize(); serializationObject.type = this.type; serializationObject.contextualValue = this.contextualValue; serializationObject.systemSource = this.systemSource; serializationObject.min = this.min; serializationObject.max = this.max; serializationObject.groupInInspector = this.groupInInspector; serializationObject.displayInInspector = this.displayInInspector; if (this._storedValue !== null && !this.isContextual && !this.isSystemSource) { 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; } _deserialize(serializationObject) { super._deserialize(serializationObject); this._type = serializationObject.type; this.contextualValue = serializationObject.contextualValue; this.systemSource = serializationObject.systemSource || NodeParticleSystemSources.None; this.min = serializationObject.min || 0; this.max = serializationObject.max || 0; this.groupInInspector = serializationObject.groupInInspector || ""; if (serializationObject.displayInInspector !== void 0) { this.displayInInspector = serializationObject.displayInInspector; } if (!serializationObject.valueType) { return; } if (serializationObject.valueType === "number") { this._storedValue = serializationObject.value; } else { const valueType = GetClass(serializationObject.valueType); if (valueType) { this._storedValue = valueType.FromArray(serializationObject.value); } } } }; RegisterClass("BABYLON.ParticleInputBlock", ParticleInputBlock); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/Blocks/particleSourceTextureBlock.js init_texture(); init_typeStore(); init_textureTools(); var ParticleTextureSourceBlock = class extends NodeParticleBlock { static { __name(this, "ParticleTextureSourceBlock"); } /** * Gets or sets the URL of the texture to be used by this block. */ get url() { return this._url; } set url(value) { if (this._url === value) { return; } this._cachedData = null; this._url = value; this._textureDataUrl = ""; this._sourceTexture = null; } /** * Gets or sets the data URL of the texture to be used by this block. * This is a base64 encoded string representing the texture data. */ get textureDataUrl() { return this._textureDataUrl; } set textureDataUrl(value) { if (this._textureDataUrl === value) { return; } this._cachedData = null; this._textureDataUrl = value; this._url = ""; this._sourceTexture = null; } /** * Directly sets the texture to be used by this block. * This value will not be serialized. */ set sourceTexture(value) { if (this._sourceTexture === value) { return; } this._cachedData = null; this._sourceTexture = value; this._url = value.url || ""; this._textureDataUrl = ""; } /** * Create a new ParticleTextureSourceBlock * @param name defines the block name */ constructor(name260) { super(name260); this._url = ""; this._textureDataUrl = ""; this._sourceTexture = null; this._cachedData = null; this.serializedCachedData = false; this.registerOutput("texture", NodeParticleBlockConnectionPointTypes.Texture); } /** * Gets the current class name * @returns the class name */ getClassName() { return "ParticleTextureSourceBlock"; } /** * Gets the texture output component */ get texture() { return this._outputs[0]; } /** * Gets the texture content as a promise * @returns a promise that resolves to the texture content, including width, height, and pixel data */ async extractTextureContentAsync() { if (!this.texture._storedValue && !this._sourceTexture) { return null; } if (this._cachedData) { return this._cachedData; } const texture = this.texture._storedValue || this._sourceTexture; return await new Promise((resolve, reject) => { if (!texture.isReady()) { texture.onLoadObservable.addOnce(async () => { try { this._cachedData = await this.extractTextureContentAsync(); resolve(this._cachedData); } catch (e) { reject(e); } }); return; } const size = texture.getSize(); TextureTools.GetTextureDataAsync(texture, size.width, size.height).then((data) => { this._cachedData = { width: size.width, height: size.height, data: new Uint8ClampedArray(data) }; texture.dispose(); resolve(this._cachedData); }).catch(reject); }); } /** * Builds the block * @param state defines the current build state */ _build(state) { if (this._sourceTexture) { this.texture._storedValue = this._sourceTexture; return; } if (!this._textureDataUrl && !this._url) { this.texture._storedValue = null; return; } if (this._textureDataUrl) { this.texture._storedValue = new Texture(this._textureDataUrl, state.scene); return; } this.texture._storedValue = new Texture(this._url, state.scene); } serialize() { const serializationObject = super.serialize(); serializationObject.url = this.url; serializationObject.serializedCachedData = this.serializedCachedData; if (this.serializedCachedData) { serializationObject.textureDataUrl = this.textureDataUrl; } return serializationObject; } _deserialize(serializationObject) { super._deserialize(serializationObject); this.url = serializationObject.url; this.serializedCachedData = !!serializationObject.serializedCachedData; if (serializationObject.textureDataUrl) { this.textureDataUrl = serializationObject.textureDataUrl; } } dispose() { if (!this._sourceTexture) { if (this.texture._storedValue) { this.texture._storedValue.dispose(); this.texture._storedValue = null; } } super.dispose(); } }; RegisterClass("BABYLON.ParticleTextureSourceBlock", ParticleTextureSourceBlock); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/Blocks/Update/updatePositionBlock.js init_typeStore(); var UpdatePositionBlock = class extends NodeParticleBlock { static { __name(this, "UpdatePositionBlock"); } /** * Create a new UpdateDirectionBlock * @param name defines the block name */ constructor(name260) { super(name260); this.registerInput("particle", NodeParticleBlockConnectionPointTypes.Particle); this.registerInput("position", NodeParticleBlockConnectionPointTypes.Vector3); this.registerOutput("output", NodeParticleBlockConnectionPointTypes.Particle); } /** * Gets the particle component */ get particle() { return this._inputs[0]; } /** * Gets the position input component */ get position() { return this._inputs[1]; } /** * Gets the output component */ get output() { return this._outputs[0]; } /** * Gets the current class name * @returns the class name */ getClassName() { return "UpdatePositionBlock"; } /** * Builds the block * @param state defines the current build state */ _build(state) { const system = this.particle.getConnectedValue(state); this.output._storedValue = system; if (!this.position.isConnected) { return; } const processPosition = /* @__PURE__ */ __name((particle) => { state.particleContext = particle; state.systemContext = system; particle.position.copyFrom(this.position.getConnectedValue(state)); }, "processPosition"); const positionProcessing = { process: processPosition, previousItem: null, nextItem: null }; if (system._updateQueueStart) { _ConnectAtTheEnd(positionProcessing, system._updateQueueStart); } else { system._updateQueueStart = positionProcessing; } } }; RegisterClass("BABYLON.UpdatePositionBlock", UpdatePositionBlock); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/Blocks/particleMathBlock.js init_tslib_es6(); init_typeStore(); init_math_vector(); init_math_color(); var ParticleMathBlockOperations; (function(ParticleMathBlockOperations2) { ParticleMathBlockOperations2[ParticleMathBlockOperations2["Add"] = 0] = "Add"; ParticleMathBlockOperations2[ParticleMathBlockOperations2["Subtract"] = 1] = "Subtract"; ParticleMathBlockOperations2[ParticleMathBlockOperations2["Multiply"] = 2] = "Multiply"; ParticleMathBlockOperations2[ParticleMathBlockOperations2["Divide"] = 3] = "Divide"; ParticleMathBlockOperations2[ParticleMathBlockOperations2["Max"] = 4] = "Max"; ParticleMathBlockOperations2[ParticleMathBlockOperations2["Min"] = 5] = "Min"; })(ParticleMathBlockOperations || (ParticleMathBlockOperations = {})); var ParticleMathBlock = class extends NodeParticleBlock { static { __name(this, "ParticleMathBlock"); } /** * Create a new ParticleMathBlock * @param name defines the block name */ constructor(name260) { super(name260); this.operation = ParticleMathBlockOperations.Add; this.registerInput("left", NodeParticleBlockConnectionPointTypes.AutoDetect); this.registerInput("right", NodeParticleBlockConnectionPointTypes.AutoDetect); this.registerOutput("output", NodeParticleBlockConnectionPointTypes.BasedOnInput); this.output._typeConnectionSource = this.left; const excludedConnectionPointTypes = [ NodeParticleBlockConnectionPointTypes.Matrix, NodeParticleBlockConnectionPointTypes.Particle, NodeParticleBlockConnectionPointTypes.Texture, NodeParticleBlockConnectionPointTypes.System, NodeParticleBlockConnectionPointTypes.FloatGradient, NodeParticleBlockConnectionPointTypes.Color4Gradient, NodeParticleBlockConnectionPointTypes.Vector2Gradient, NodeParticleBlockConnectionPointTypes.Vector3Gradient ]; this.left.excludedConnectionPointTypes.push(...excludedConnectionPointTypes); this.right.excludedConnectionPointTypes.push(...excludedConnectionPointTypes); this._linkConnectionTypes(0, 1); this._connectionObservers = [ this.left.onConnectionObservable.add(() => this._updateInputOutputTypes()), this.left.onDisconnectionObservable.add(() => this._updateInputOutputTypes()), this.right.onConnectionObservable.add(() => this._updateInputOutputTypes()), this.right.onDisconnectionObservable.add(() => this._updateInputOutputTypes()) ]; } /** * Gets the current class name * @returns the class name */ getClassName() { return "ParticleMathBlock"; } /** * Gets the left input component */ get left() { return this._inputs[0]; } /** * Gets the right input component */ get right() { return this._inputs[1]; } /** * Gets the geometry output component */ get output() { return this._outputs[0]; } _build(state) { let func; const left = this.left; const right = this.right; if (!left.isConnected || !right.isConnected) { this.output._storedFunction = null; this.output._storedValue = null; return; } const leftIsScalar = left.type === NodeParticleBlockConnectionPointTypes.Float || left.type === NodeParticleBlockConnectionPointTypes.Int; const rightIsScalar = right.type === NodeParticleBlockConnectionPointTypes.Float || right.type === NodeParticleBlockConnectionPointTypes.Int; const isScalar = leftIsScalar && rightIsScalar; switch (this.operation) { case ParticleMathBlockOperations.Add: { if (isScalar) { func = /* @__PURE__ */ __name((state2) => { return left.getConnectedValue(state2) + right.getConnectedValue(state2); }, "func"); } else if (leftIsScalar) { func = /* @__PURE__ */ __name((state2) => { return state2.adapt(left, right.type).add(right.getConnectedValue(state2)); }, "func"); } else { func = /* @__PURE__ */ __name((state2) => { return left.getConnectedValue(state2).add(state2.adapt(right, left.type)); }, "func"); } break; } case ParticleMathBlockOperations.Subtract: { if (isScalar) { func = /* @__PURE__ */ __name((state2) => { return left.getConnectedValue(state2) - right.getConnectedValue(state2); }, "func"); } else if (leftIsScalar) { func = /* @__PURE__ */ __name((state2) => { return state2.adapt(left, right.type).subtract(right.getConnectedValue(state2)); }, "func"); } else { func = /* @__PURE__ */ __name((state2) => { return left.getConnectedValue(state2).subtract(state2.adapt(right, left.type)); }, "func"); } break; } case ParticleMathBlockOperations.Multiply: { if (isScalar) { func = /* @__PURE__ */ __name((state2) => { return left.getConnectedValue(state2) * right.getConnectedValue(state2); }, "func"); } else if (leftIsScalar) { func = /* @__PURE__ */ __name((state2) => { return state2.adapt(left, right.type).multiply(right.getConnectedValue(state2)); }, "func"); } else { func = /* @__PURE__ */ __name((state2) => { return left.getConnectedValue(state2).multiply(state2.adapt(right, left.type)); }, "func"); } break; } case ParticleMathBlockOperations.Divide: { if (isScalar) { func = /* @__PURE__ */ __name((state2) => { return left.getConnectedValue(state2) / right.getConnectedValue(state2); }, "func"); } else if (leftIsScalar) { func = /* @__PURE__ */ __name((state2) => { return state2.adapt(left, right.type).divide(right.getConnectedValue(state2)); }, "func"); } else { func = /* @__PURE__ */ __name((state2) => { return left.getConnectedValue(state2).divide(state2.adapt(right, left.type)); }, "func"); } break; } case ParticleMathBlockOperations.Min: { if (isScalar) { func = /* @__PURE__ */ __name((state2) => { return Math.min(left.getConnectedValue(state2), right.getConnectedValue(state2)); }, "func"); } else { const [vector, scalar] = leftIsScalar ? [right, left] : [left, right]; switch (vector.type) { case NodeParticleBlockConnectionPointTypes.Vector2: { func = /* @__PURE__ */ __name((state2) => { return Vector2.Minimize(vector.getConnectedValue(state2), state2.adapt(scalar, vector.type)); }, "func"); break; } case NodeParticleBlockConnectionPointTypes.Vector3: { func = /* @__PURE__ */ __name((state2) => { return Vector3.Minimize(vector.getConnectedValue(state2), state2.adapt(scalar, vector.type)); }, "func"); break; } case NodeParticleBlockConnectionPointTypes.Color4: { func = /* @__PURE__ */ __name((state2) => { const other = vector.getConnectedValue(state2); const { r, g, b, a } = state2.adapt(scalar, vector.type); return new Color4(Math.min(other.r, r), Math.min(other.g, g), Math.min(other.b, b), Math.min(other.a, a)); }, "func"); break; } } } break; } case ParticleMathBlockOperations.Max: { if (isScalar) { func = /* @__PURE__ */ __name((state2) => { return Math.max(left.getConnectedValue(state2), right.getConnectedValue(state2)); }, "func"); } else { const [vector, scalar] = leftIsScalar ? [right, left] : [left, right]; switch (vector.type) { case NodeParticleBlockConnectionPointTypes.Vector2: { func = /* @__PURE__ */ __name((state2) => { return Vector2.Maximize(vector.getConnectedValue(state2), state2.adapt(scalar, vector.type)); }, "func"); break; } case NodeParticleBlockConnectionPointTypes.Vector3: { func = /* @__PURE__ */ __name((state2) => { return Vector3.Maximize(vector.getConnectedValue(state2), state2.adapt(scalar, vector.type)); }, "func"); break; } case NodeParticleBlockConnectionPointTypes.Color4: { func = /* @__PURE__ */ __name((state2) => { const other = vector.getConnectedValue(state2); const { r, g, b, a } = state2.adapt(scalar, vector.type); return new Color4(Math.max(other.r, r), Math.min(other.g, g), Math.min(other.b, b), Math.min(other.a, a)); }, "func"); break; } } break; } } } this.output._storedFunction = (state2) => { if (left.type === NodeParticleBlockConnectionPointTypes.Int) { return func(state2) | 0; } return func(state2); }; } _updateInputOutputTypes() { this.output._typeConnectionSource = this.left; if (this.left.isConnected && this.right.isConnected) { if (this.left.type === NodeParticleBlockConnectionPointTypes.Int || this.left.type === NodeParticleBlockConnectionPointTypes.Float && this.right.type !== NodeParticleBlockConnectionPointTypes.Int) { this.output._typeConnectionSource = this.right; } } else if (this.left.isConnected !== this.right.isConnected) { this.output._typeConnectionSource = this.left.isConnected ? this.left : this.right; } if (this.left.isConnected || this.right.isConnected) { for (const [first, second] of [ [this.left, this.right], [this.right, this.left] ]) { first.acceptedConnectionPointTypes = [NodeParticleBlockConnectionPointTypes.Int, NodeParticleBlockConnectionPointTypes.Float]; if (second.isConnected) { first.acceptedConnectionPointTypes.push(second.type); if (second.type === NodeParticleBlockConnectionPointTypes.Int || second.type === NodeParticleBlockConnectionPointTypes.Float) { first.acceptedConnectionPointTypes.push(NodeParticleBlockConnectionPointTypes.Vector2, NodeParticleBlockConnectionPointTypes.Vector3, NodeParticleBlockConnectionPointTypes.Color4); } } } } } /** * Release resources */ dispose() { super.dispose(); for (const observer of this._connectionObservers) { observer.remove(); } this._connectionObservers.length = 0; } /** * Serializes this block in a JSON representation * @returns the serialized block object */ serialize() { const serializationObject = super.serialize(); serializationObject.operation = this.operation; return serializationObject; } _deserialize(serializationObject) { super._deserialize(serializationObject); this.operation = serializationObject.operation; } }; __decorate([ editableInPropertyPage("Operation", 5, "ADVANCED", { notifiers: { rebuild: true }, embedded: true, options: [ { label: "Add", value: ParticleMathBlockOperations.Add }, { label: "Subtract", value: ParticleMathBlockOperations.Subtract }, { label: "Multiply", value: ParticleMathBlockOperations.Multiply }, { label: "Divide", value: ParticleMathBlockOperations.Divide }, { label: "Max", value: ParticleMathBlockOperations.Max }, { label: "Min", value: ParticleMathBlockOperations.Min } ] }) ], ParticleMathBlock.prototype, "operation", void 0); RegisterClass("BABYLON.ParticleMathBlock", ParticleMathBlock); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/Blocks/Emitters/boxShapeBlock.js init_typeStore(); init_math_vector(); init_math_scalar_functions(); var BoxShapeBlock = class extends NodeParticleBlock { static { __name(this, "BoxShapeBlock"); } /** * Create a new BoxShapeBlock * @param name defines the block name */ constructor(name260) { super(name260); this.registerInput("particle", NodeParticleBlockConnectionPointTypes.Particle); this.registerInput("direction1", NodeParticleBlockConnectionPointTypes.Vector3, true, new Vector3(0, 1, 0)); this.registerInput("direction2", NodeParticleBlockConnectionPointTypes.Vector3, true, new Vector3(0, 1, 0)); this.registerInput("minEmitBox", NodeParticleBlockConnectionPointTypes.Vector3, true, new Vector3(-0.5, -0.5, -0.5)); this.registerInput("maxEmitBox", NodeParticleBlockConnectionPointTypes.Vector3, true, new Vector3(0.5, 0.5, 0.5)); this.registerOutput("output", NodeParticleBlockConnectionPointTypes.Particle); } /** * Gets the current class name * @returns the class name */ getClassName() { return "BoxShapeBlock"; } /** * Gets the particle input component */ get particle() { return this._inputs[0]; } /** * Gets the direction1 input component */ get direction1() { return this._inputs[1]; } /** * Gets the direction2 input component */ get direction2() { return this._inputs[2]; } /** * Gets the minEmitBox input component */ get minEmitBox() { return this._inputs[3]; } /** * Gets the maxEmitBox input component */ get maxEmitBox() { return this._inputs[4]; } /** * Gets the output component */ get output() { return this._outputs[0]; } /** * Builds the block * @param state defines the build state */ _build(state) { const system = this.particle.getConnectedValue(state); system._directionCreation.process = (particle) => { state.particleContext = particle; state.systemContext = system; const direction1 = this.direction1.getConnectedValue(state); const direction2 = this.direction2.getConnectedValue(state); const randX = RandomRange(direction1.x, direction2.x); const randY = RandomRange(direction1.y, direction2.y); const randZ = RandomRange(direction1.z, direction2.z); if (state.isEmitterTransformNode) { Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, state.emitterWorldMatrix, particle.direction); } else { particle.direction.copyFromFloats(randX, randY, randZ); } particle._initialDirection = particle.direction.clone(); }; system._positionCreation.process = (particle) => { state.particleContext = particle; state.systemContext = system; const minEmitBox = this.minEmitBox.getConnectedValue(state); const maxEmitBox = this.maxEmitBox.getConnectedValue(state); const randX = RandomRange(minEmitBox.x, maxEmitBox.x); const randY = RandomRange(minEmitBox.y, maxEmitBox.y); const randZ = RandomRange(minEmitBox.z, maxEmitBox.z); if (state.isEmitterTransformNode) { Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, state.emitterWorldMatrix, particle.position); } else { particle.position.copyFromFloats(randX, randY, randZ); particle.position.addInPlace(state.emitterPosition); } }; this.output._storedValue = system; } }; RegisterClass("BABYLON.BoxShapeBlock", BoxShapeBlock); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/Blocks/Emitters/createParticleBlock.js init_math_color(); init_math_vector(); init_typeStore(); var ColorDiff = new Color4(); var CreateParticleBlock = class extends NodeParticleBlock { static { __name(this, "CreateParticleBlock"); } /** * Create a new CreateParticleBlock * @param name defines the block name */ constructor(name260) { super(name260); this.registerInput("emitPower", NodeParticleBlockConnectionPointTypes.Float, true, 1); this.registerInput("lifeTime", NodeParticleBlockConnectionPointTypes.Float, true, 1); this.registerInput("color", NodeParticleBlockConnectionPointTypes.Color4, true, new Color4(1, 1, 1, 1)); this.registerInput("colorDead", NodeParticleBlockConnectionPointTypes.Color4, true, new Color4(0, 0, 0, 0)); this.registerInput("scale", NodeParticleBlockConnectionPointTypes.Vector2, true, new Vector2(1, 1)); this.registerInput("angle", NodeParticleBlockConnectionPointTypes.Float, true, 0); this.registerOutput("particle", NodeParticleBlockConnectionPointTypes.Particle); this.scale.acceptedConnectionPointTypes.push(NodeParticleBlockConnectionPointTypes.Float); } /** * Gets the current class name * @returns the class name */ getClassName() { return "CreateParticleBlock"; } /** * Gets the emitPower input component */ get emitPower() { return this._inputs[0]; } /** * Gets the lifeTime input component */ get lifeTime() { return this._inputs[1]; } /** * Gets the color input component */ get color() { return this._inputs[2]; } /** * Gets the color dead input component */ get colorDead() { return this._inputs[3]; } /** * Gets the scale input component */ get scale() { return this._inputs[4]; } /** * Gets the angle input component */ get angle() { return this._inputs[5]; } /** * Gets the particle output component */ get particle() { return this._outputs[0]; } /** * @internal */ _build(state) { const system = new ParticleSystem(this.name, state.capacity, state.scene, null, false, void 0, true); system.particleEmitterType = new PointParticleEmitter(); system._lifeTimeCreation.process = (particle, system2) => { state.particleContext = particle; particle.lifeTime = this.lifeTime.getConnectedValue(state); system2._emitPower = this.emitPower.getConnectedValue(state); }; system._colorCreation.process = (particle) => { state.particleContext = particle; particle.color.copyFrom(this.color.getConnectedValue(state)); }; system._colorDeadCreation.process = (particle) => { state.particleContext = particle; particle.colorDead.copyFrom(this.colorDead.getConnectedValue(state)); particle.initialColor.copyFrom(particle.color); particle.colorDead.subtractToRef(particle.initialColor, ColorDiff); ColorDiff.scaleToRef(1 / particle.lifeTime, particle.colorStep); }; system._sizeCreation.process = (particle) => { state.particleContext = particle; particle.size = 1; const scale = this.scale.getConnectedValue(state); if (scale.x !== void 0) { particle.scale.x = scale.x; particle.scale.y = scale.y; } else { particle.scale.x = scale; particle.scale.y = scale; } }; system._angleCreation.process = (particle) => { state.particleContext = particle; particle.angle = this.angle.getConnectedValue(state); }; this.particle._storedValue = system; } }; RegisterClass("BABYLON.CreateParticleBlock", CreateParticleBlock); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Particles/Node/nodeParticleSystemSet.js init_tslib_es6(); init_decorators(); init_decorators_serialization(); init_observable(); init_typeStore(); init_webRequest(); init_tools(); init_abstractEngine(); var NodeParticleSystemSet = class _NodeParticleSystemSet { static { __name(this, "NodeParticleSystemSet"); } /** * Gets the system blocks */ get systemBlocks() { return this._systemBlocks; } /** * Gets the list of input blocks attached to this material * @returns an array of InputBlocks */ get inputBlocks() { const blocks = []; for (const block of this.attachedBlocks) { if (block.isInput) { blocks.push(block); } } return blocks; } /** * 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 */ getBlockByName(name260) { let result = null; for (const block of this.attachedBlocks) { if (block.name === name260) { if (!result) { result = block; } else { Tools.Warn("More than one block was found with the name `" + name260 + "`"); return result; } } } return result; } /** * Get a block using a predicate * @param predicate defines the predicate used to find the good candidate * @returns the required block or null if not found */ getBlockByPredicate(predicate) { for (const block of this.attachedBlocks) { if (predicate(block)) { return block; } } return null; } /** * Get an input block using a predicate * @param predicate defines the predicate used to find the good candidate * @returns the required input block or null if not found */ getInputBlockByPredicate(predicate) { for (const block of this.attachedBlocks) { if (block.isInput && predicate(block)) { return block; } } return null; } /** * Creates a new set * @param name defines the name of the set */ constructor(name260) { this._systemBlocks = []; this._buildId = 0; this.attachedBlocks = []; this.editorData = null; this.onBuildObservable = new Observable(); this.BJSNODEPARTICLEEDITOR = this._getGlobalNodeParticleEditor(); this.name = name260; } /** * Gets the current class name of the node particle set e.g. "NodeParticleSystemSet" * @returns the class name */ getClassName() { return "NodeParticleSystemSet"; } _initializeBlock(node, autoConfigure = true) { if (this.attachedBlocks.indexOf(node) === -1) { this.attachedBlocks.push(node); } for (const input of node.inputs) { const connectedPoint = input.connectedPoint; if (connectedPoint) { const block = connectedPoint.ownerBlock; if (block !== node) { this._initializeBlock(block, autoConfigure); } } } } /** Get the editor from bundle or global * @returns the global NPE */ _getGlobalNodeParticleEditor() { if (typeof NODEPARTICLEEDITOR !== "undefined") { return NODEPARTICLEEDITOR; } if (typeof BABYLON !== "undefined" && typeof BABYLON.NodeParticleEditor !== "undefined") { return BABYLON; } return void 0; } /** Creates the node editor window. * @param additionalConfig Define the configuration of the editor */ _createNodeParticleEditor(additionalConfig) { const nodeEditorConfig = { nodeParticleSet: this, ...additionalConfig }; this.BJSNODEPARTICLEEDITOR.NodeParticleEditor.Show(nodeEditorConfig); } /** * Launch the node particle editor * @param config Define the configuration of the editor * @returns a promise fulfilled when the node editor is visible */ async editAsync(config) { return await new Promise((resolve) => { this.BJSNODEPARTICLEEDITOR = this.BJSNODEPARTICLEEDITOR || this._getGlobalNodeParticleEditor(); if (typeof this.BJSNODEPARTICLEEDITOR == "undefined") { const editorUrl = config && config.editorURL ? config.editorURL : _NodeParticleSystemSet.EditorURL; Tools.LoadBabylonScript(editorUrl, () => { this.BJSNODEPARTICLEEDITOR = this.BJSNODEPARTICLEEDITOR || this._getGlobalNodeParticleEditor(); this._createNodeParticleEditor(config?.nodeEditorConfig); resolve(); }); } else { this._createNodeParticleEditor(config?.nodeEditorConfig); resolve(); } }); } /** * Builds the particle system set from the defined blocks. * @param scene defines the hosting scene * @param verbose defines whether to log detailed information during the build process (false by default) * @returns a promise that resolves to the built particle system set */ async buildAsync(scene, verbose = false) { return await new Promise((resolve) => { const output = new ParticleSystemSet(); for (const block of this._systemBlocks) { this._initializeBlock(block); } for (const block of this.systemBlocks) { const state = new NodeParticleBuildState(); state.buildId = this._buildId++; state.scene = scene; state.verbose = verbose; const system = block.createSystem(state); system._source = this; system._blockReference = block._internalId; state.emitErrors(); output.systems.push(system); } this.onBuildObservable.notifyObservers(this); resolve(output); }); } /** * Clear the current node particle set */ clear() { this.attachedBlocks.length = 0; this._systemBlocks.length = 0; } /** * Clear the current set and restore it to a default state */ setToDefault() { this.clear(); this.editorData = null; const system = new SystemBlock("Particle system"); const updatePositionBlock = new UpdatePositionBlock("Update position"); updatePositionBlock.output.connectTo(system.particle); const positionBlock = new ParticleInputBlock("Position"); positionBlock.contextualValue = NodeParticleContextualSources.Position; const directionBlock = new ParticleInputBlock("Scaled direction"); directionBlock.contextualValue = NodeParticleContextualSources.ScaledDirection; const addBlock = new ParticleMathBlock("Add"); addBlock.operation = ParticleMathBlockOperations.Add; positionBlock.output.connectTo(addBlock.left); directionBlock.output.connectTo(addBlock.right); addBlock.output.connectTo(updatePositionBlock.position); const createParticleBlock = new CreateParticleBlock("Create particle"); const emitterShape = new BoxShapeBlock("Box shape"); createParticleBlock.particle.connectTo(emitterShape.particle); emitterShape.output.connectTo(updatePositionBlock.particle); const textureBlock = new ParticleTextureSourceBlock("Texture"); textureBlock.texture.connectTo(system.texture); textureBlock.url = "https://assets.babylonjs.com/textures/flare.png"; this._systemBlocks.push(system); } /** * Remove a block from the current system set * @param block defines the block to remove */ removeBlock(block) { const attachedBlockIndex = this.attachedBlocks.indexOf(block); if (attachedBlockIndex > -1) { this.attachedBlocks.splice(attachedBlockIndex, 1); } if (block.isSystem) { const index = this._systemBlocks.indexOf(block); if (index > -1) { this._systemBlocks.splice(index, 1); } } } /** * Clear the current graph and load a new one from a serialization object * @param source defines the JSON representation of the particle set * @param merge defines whether or not the source must be merged or replace the current content */ parseSerializedObject(source, merge = false) { if (!merge) { this.clear(); } const map = {}; for (const parsedBlock of source.blocks) { const blockType = GetClass(parsedBlock.customType); if (blockType) { const block = new blockType(); block._deserialize(parsedBlock); map[parsedBlock.id] = block; this.attachedBlocks.push(block); if (block.isSystem) { this._systemBlocks.push(block); } } } for (const block of this.attachedBlocks) { if (block.isTeleportOut) { const teleportOut = block; const id = teleportOut._tempEntryPointUniqueId; if (id) { const source2 = map[id]; if (source2) { source2.attachToEndpoint(teleportOut); } } } } for (let blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) { const parsedBlock = source.blocks[blockIndex]; const block = map[parsedBlock.id]; if (!block) { continue; } if (block.inputs.length && parsedBlock.inputs.some((i) => i.targetConnectionName) && !merge) { continue; } this._restoreConnections(block, source, map); } if (source.locations || source.editorData && source.editorData.locations) { const locations = source.locations || source.editorData.locations; for (const location2 of locations) { if (map[location2.blockId]) { location2.blockId = map[location2.blockId].uniqueId; } } if (merge && this.editorData && this.editorData.locations) { locations.concat(this.editorData.locations); } if (source.locations) { this.editorData = { locations }; } else { this.editorData = source.editorData; this.editorData.locations = locations; } const blockMap = {}; for (const key in map) { blockMap[key] = map[key].uniqueId; } this.editorData.map = blockMap; } this.comment = source.comment; } _restoreConnections(block, source, map) { for (const outputPoint of block.outputs) { for (const candidate of source.blocks) { const target = map[candidate.id]; if (!target) { continue; } for (const input of candidate.inputs) { if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) { const inputPoint = target.getInputByName(input.inputName); if (!inputPoint || inputPoint.isConnected) { continue; } outputPoint.connectTo(inputPoint, true); this._restoreConnections(target, source, map); continue; } } } } } /** * Serializes this node particle set in a JSON representation * @param selectedBlocks defines the list of blocks to save (if null the whole node particle set will be saved) * @returns the serialized particle system set object */ serialize(selectedBlocks) { const serializationObject = selectedBlocks ? {} : SerializationHelper.Serialize(this); serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData)); let blocks = []; if (selectedBlocks) { blocks = selectedBlocks; } else { serializationObject.customType = "BABYLON.NodeParticleSystemSet"; } serializationObject.blocks = []; for (const block of blocks) { serializationObject.blocks.push(block.serialize()); } if (!selectedBlocks) { for (const block of this.attachedBlocks) { if (blocks.indexOf(block) !== -1) { continue; } serializationObject.blocks.push(block.serialize()); } } return serializationObject; } /** * Makes a duplicate of the current particle system set. * @param name defines the name to use for the new particle system set * @returns the cloned particle system set */ clone(name260) { const serializationObject = this.serialize(); const clone = SerializationHelper.Clone(() => new _NodeParticleSystemSet(name260), this); clone.name = name260; clone.snippetId = this.snippetId; clone.parseSerializedObject(serializationObject); clone._buildId = this._buildId; return clone; } /** * Disposes the resources */ dispose() { for (const block of this.attachedBlocks) { block.dispose(); } this.attachedBlocks.length = 0; this.onBuildObservable.clear(); } /** * Creates a new node particle set set to default basic configuration * @param name defines the name of the particle set * @returns a new NodeParticleSystemSet */ static CreateDefault(name260) { const nodeParticleSet = new _NodeParticleSystemSet(name260); nodeParticleSet.setToDefault(); return nodeParticleSet; } /** * Creates a node particle set from parsed data * @param source defines the JSON representation of the particle set * @returns a new node particle set */ static Parse(source) { const nodeParticleSet = SerializationHelper.Parse(() => new _NodeParticleSystemSet(source.name), source, null); nodeParticleSet.parseSerializedObject(source); return nodeParticleSet; } /** * Creates a node particle set from a snippet saved in a remote file * @param name defines the name of the node particle set to create * @param url defines the url to load from * @param nodeParticleSet defines a node particle set to update (instead of creating a new one) * @returns a promise that will resolve to the new node particle set */ // eslint-disable-next-line @typescript-eslint/promise-function-async, no-restricted-syntax static ParseFromFileAsync(name260, url, nodeParticleSet) { return new Promise((resolve, reject) => { const request = new WebRequest(); request.addEventListener("readystatechange", () => { if (request.readyState == 4) { if (request.status == 200) { const serializationObject = JSON.parse(request.responseText); if (!nodeParticleSet) { nodeParticleSet = SerializationHelper.Parse(() => new _NodeParticleSystemSet(name260), serializationObject, null); } nodeParticleSet.parseSerializedObject(serializationObject); resolve(nodeParticleSet); } else { reject("Unable to load the node particle system set"); } } }); request.open("GET", url); request.send(); }); } /** * Creates a node particle set from a snippet saved by the node particle editor * @param snippetId defines the snippet to load * @param nodeParticleSet defines a node particle set to update (instead of creating a new one) * @returns a promise that will resolve to the new node particle set */ // eslint-disable-next-line @typescript-eslint/promise-function-async, no-restricted-syntax static ParseFromSnippetAsync(snippetId, nodeParticleSet) { if (snippetId === "_BLANK") { return Promise.resolve(_NodeParticleSystemSet.CreateDefault("blank")); } return new Promise((resolve, reject) => { const request = new WebRequest(); request.addEventListener("readystatechange", () => { if (request.readyState == 4) { if (request.status == 200) { const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); const serializationObject = JSON.parse(snippet.nodeParticle); if (!nodeParticleSet) { nodeParticleSet = SerializationHelper.Parse(() => new _NodeParticleSystemSet(snippetId), serializationObject, null); } nodeParticleSet.parseSerializedObject(serializationObject); nodeParticleSet.snippetId = snippetId; try { resolve(nodeParticleSet); } catch (err) { reject(err); } } else { reject("Unable to load the snippet " + snippetId); } } }); request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); request.send(); }); } }; NodeParticleSystemSet.EditorURL = `${Tools._DefaultCdnUrl}/v${AbstractEngine.Version}/nodeParticleEditor/babylon.nodeParticleEditor.js`; NodeParticleSystemSet.SnippetUrl = `https://snippet.babylonjs.com`; __decorate([ serialize() ], NodeParticleSystemSet.prototype, "name", void 0); __decorate([ serialize("comment") ], NodeParticleSystemSet.prototype, "comment", void 0); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Events/clipboardEvents.js var ClipboardEventTypes = class { static { __name(this, "ClipboardEventTypes"); } }; ClipboardEventTypes.COPY = 1; ClipboardEventTypes.CUT = 2; ClipboardEventTypes.PASTE = 3; var ClipboardInfo = class { static { __name(this, "ClipboardInfo"); } /** *Creates an instance of ClipboardInfo. * @param type Defines the type of event (BABYLON.ClipboardEventTypes) * @param event Defines the related dom event */ constructor(type, 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. * @returns {number} */ static GetTypeFromCharacter(keyCode) { const charCode = keyCode; switch (charCode) { case 67: return ClipboardEventTypes.COPY; case 86: return ClipboardEventTypes.PASTE; case 88: return ClipboardEventTypes.CUT; default: return -1; } } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Engines/Extensions/engine.dynamicTexture.js init_tools_functions(); init_thinEngine(); init_internalTexture(); ThinEngine.prototype.createDynamicTexture = function(width, height, generateMipMaps, samplingMode) { const texture = new InternalTexture( this, 4 /* InternalTextureSource.Dynamic */ ); texture.baseWidth = width; texture.baseHeight = height; if (generateMipMaps) { width = this.needPOTTextures ? GetExponentOfTwo(width, this._caps.maxTextureSize) : width; height = this.needPOTTextures ? GetExponentOfTwo(height, this._caps.maxTextureSize) : height; } 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; }; ThinEngine.prototype.updateDynamicTexture = function(texture, source, invertY, premulAlpha = false, format, forceBindTexture = false, allowGPUOptimization = false) { if (!texture) { return; } const gl = this._gl; const target = gl.TEXTURE_2D; const wasPreviouslyBound = this._bindTextureDirectly(target, texture, true, forceBindTexture); this._unpackFlipY(invertY === void 0 ? texture.invertY : invertY); if (premulAlpha) { gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); } const textureType = this._getWebGLTextureType(texture.type); const glformat = this._getInternalFormat(format ? format : texture.format); const internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, glformat); gl.texImage2D(target, 0, internalFormat, glformat, textureType, source); if (texture.generateMipMaps) { gl.generateMipmap(target); } if (!wasPreviouslyBound) { this._bindTextureDirectly(target, null); } if (premulAlpha) { gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0); } if (format) { texture.format = format; } texture._dynamicTextureSource = source; texture._premulAlpha = premulAlpha; texture.invertY = invertY || false; texture.isReady = true; }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/Textures/dynamicTexture.js init_logger(); init_texture(); var DynamicTexture = class _DynamicTexture extends Texture { static { __name(this, "DynamicTexture"); } /** @internal */ constructor(name260, canvasOrSize, sceneOrOptions, generateMipMaps = false, samplingMode = 3, format = 5, invertY) { const isScene2 = !sceneOrOptions || sceneOrOptions._isScene; const scene = isScene2 ? sceneOrOptions : sceneOrOptions?.scene; const noMipmap = isScene2 ? !generateMipMaps : sceneOrOptions; super(null, scene, noMipmap, invertY, samplingMode, void 0, void 0, void 0, void 0, format); this.name = name260; this.wrapU = Texture.CLAMP_ADDRESSMODE; this.wrapV = Texture.CLAMP_ADDRESSMODE; this._generateMipMaps = generateMipMaps; const engine = this._getEngine(); if (!engine) { return; } if (canvasOrSize.getContext) { this._canvas = canvasOrSize; this._ownCanvas = false; this._texture = engine.createDynamicTexture(this._canvas.width, this._canvas.height, generateMipMaps, samplingMode); } else { this._canvas = engine.createCanvas(1, 1); this._ownCanvas = true; const optionsAsSize = canvasOrSize; if (optionsAsSize.width || optionsAsSize.width === 0) { this._texture = engine.createDynamicTexture(optionsAsSize.width, optionsAsSize.height, generateMipMaps, samplingMode); } else { this._texture = engine.createDynamicTexture(canvasOrSize, canvasOrSize, generateMipMaps, samplingMode); } } const textureSize = this.getSize(); if (this._canvas.width !== textureSize.width) { this._canvas.width = textureSize.width; } if (this._canvas.height !== textureSize.height) { this._canvas.height = textureSize.height; } this._context = this._canvas.getContext("2d"); } /** * Get the current class name of the texture useful for serialization or dynamic coding. * @returns "DynamicTexture" */ getClassName() { return "DynamicTexture"; } /** * Gets the current state of canRescale */ get canRescale() { return true; } _recreate(textureSize) { this._canvas.width = textureSize.width; this._canvas.height = textureSize.height; this.releaseInternalTexture(); this._texture = this._getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this.samplingMode); } /** * Scales the texture * @param ratio the scale factor to apply to both width and height */ scale(ratio) { const textureSize = this.getSize(); textureSize.width *= ratio; textureSize.height *= ratio; this._recreate(textureSize); } /** * Resizes the texture * @param width the new width * @param height the new height */ scaleTo(width, height) { const textureSize = this.getSize(); textureSize.width = width; textureSize.height = height; this._recreate(textureSize); } /** * Gets the context of the canvas used by the texture * @returns the canvas context of the dynamic texture */ getContext() { return this._context; } /** * Clears the texture * @param clearColor Defines the clear color to use */ clear(clearColor) { const size = this.getSize(); if (clearColor) { this._context.fillStyle = clearColor; } this._context.clearRect(0, 0, size.width, size.height); } /** * Updates the texture * @param invertY defines the direction for the Y axis (default is true - y increases downwards) * @param premulAlpha defines if alpha is stored as premultiplied (default is false) * @param allowGPUOptimization true to allow some specific GPU optimizations (subject to engine feature "allowGPUOptimizationsForGUI" being true) */ update(invertY, premulAlpha = false, allowGPUOptimization = false) { if (!this._texture) { return; } this._getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === void 0 ? true : invertY, premulAlpha, this._format || void 0, void 0, allowGPUOptimization); } /** * Draws text onto the texture * @param text defines the text to be drawn * @param x defines the placement of the text from the left * @param y defines the placement of the text from the top when invertY is true and from the bottom when false * @param font defines the font to be used with font-style, font-size, font-name * @param color defines the color used for the text * @param fillColor defines the color for the canvas, use null to not overwrite canvas (this bleands with the background to replace, use the clear function) * @param invertY defines the direction for the Y axis (default is true - y increases downwards) * @param update defines whether texture is immediately update (default is true) */ drawText(text, x, y, font, color, fillColor, invertY, update = true) { const size = this.getSize(); if (fillColor) { this._context.fillStyle = fillColor; this._context.fillRect(0, 0, size.width, size.height); } this._context.font = font; if (x === null || x === void 0) { const textSize = this._context.measureText(text); x = (size.width - textSize.width) / 2; } if (y === null || y === void 0) { const fontSize = parseInt(font.replace(/\D/g, "")); y = size.height / 2 + fontSize / 3.65; } this._context.fillStyle = color || ""; this._context.fillText(text, x, y); if (update) { this.update(invertY); } } /** * Disposes the dynamic texture. */ dispose() { super.dispose(); if (this._ownCanvas) { this._canvas?.remove?.(); } this._canvas = null; this._context = null; } /** * Clones the texture * @returns the clone of the texture. */ clone() { const scene = this.getScene(); if (!scene) { return this; } const textureSize = this.getSize(); const newTexture = new _DynamicTexture(this.name, textureSize, scene, this._generateMipMaps); newTexture.hasAlpha = this.hasAlpha; newTexture.level = this.level; newTexture.wrapU = this.wrapU; newTexture.wrapV = this.wrapV; return newTexture; } /** * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized * @returns a serialized dynamic texture object */ serialize() { const scene = this.getScene(); if (scene && !scene.isReady()) { Logger.Warn("The scene must be ready before serializing the dynamic texture"); } const serializationObject = super.serialize(); if (_DynamicTexture._IsCanvasElement(this._canvas)) { serializationObject.base64String = this._canvas.toDataURL(); } serializationObject.invertY = this._invertY; serializationObject.samplingMode = this.samplingMode; return serializationObject; } static _IsCanvasElement(canvas) { return canvas.toDataURL !== void 0; } /** @internal */ _rebuild() { this.update(); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Layers/layerSceneComponent.js init_sceneComponent(); init_engineStore(); var LayerSceneComponent = class { static { __name(this, "LayerSceneComponent"); } /** * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ constructor(scene) { this.name = SceneComponentConstants.NAME_LAYER; this.scene = scene || EngineStore.LastCreatedScene; if (!this.scene) { return; } this._engine = this.scene.getEngine(); } /** * Registers the component in a given scene */ register() { this.scene._beforeCameraDrawStage.registerStep(SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawCameraBackground); this.scene._afterCameraDrawStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawCameraForegroundWithPostProcessing); this.scene._afterCameraPostProcessStage.registerStep(SceneComponentConstants.STEP_AFTERCAMERAPOSTPROCESS_LAYER, this, this._drawCameraForegroundWithoutPostProcessing); this.scene._beforeRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_BEFORERENDERTARGETDRAW_LAYER, this, this._drawRenderTargetBackground); this.scene._afterRenderTargetDrawStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERTARGETDRAW_LAYER, this, this._drawRenderTargetForegroundWithPostProcessing); this.scene._afterRenderTargetPostProcessStage.registerStep(SceneComponentConstants.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER, this, this._drawRenderTargetForegroundWithoutPostProcessing); } /** * Rebuilds the elements related to this component in case of * context lost for instance. */ rebuild() { const layers = this.scene.layers; for (const layer of layers) { layer._rebuild(); } } /** * Disposes the component and the associated resources. */ dispose() { const layers = this.scene.layers; while (layers.length) { layers[0].dispose(); } } _draw(predicate) { const layers = this.scene.layers; if (layers.length) { this._engine.setDepthBuffer(false); for (const layer of layers) { if (predicate(layer)) { layer.render(); } } this._engine.setDepthBuffer(true); } } _drawCameraPredicate(layer, isBackground, applyPostProcess, cameraLayerMask) { return !layer.renderOnlyInRenderTargetTextures && layer.isBackground === isBackground && layer.applyPostProcess === applyPostProcess && (layer.layerMask & cameraLayerMask) !== 0; } _drawCameraBackground(camera) { this._draw((layer) => { return this._drawCameraPredicate(layer, true, true, camera.layerMask); }); } _drawCameraForegroundWithPostProcessing(camera) { this._draw((layer) => { return this._drawCameraPredicate(layer, false, true, camera.layerMask); }); } _drawCameraForegroundWithoutPostProcessing(camera) { this._draw((layer) => { return this._drawCameraPredicate(layer, false, false, camera.layerMask); }); } _drawRenderTargetPredicate(layer, isBackground, applyPostProcess, cameraLayerMask, renderTargetTexture) { return layer.renderTargetTextures.length > 0 && layer.isBackground === isBackground && layer.applyPostProcess === applyPostProcess && layer.renderTargetTextures.indexOf(renderTargetTexture) > -1 && (layer.layerMask & cameraLayerMask) !== 0; } _drawRenderTargetBackground(renderTarget) { this._draw((layer) => { return this._drawRenderTargetPredicate(layer, true, true, this.scene.activeCamera ? this.scene.activeCamera.layerMask : 0, renderTarget); }); } _drawRenderTargetForegroundWithPostProcessing(renderTarget) { this._draw((layer) => { return this._drawRenderTargetPredicate(layer, false, true, this.scene.activeCamera ? this.scene.activeCamera.layerMask : 0, renderTarget); }); } _drawRenderTargetForegroundWithoutPostProcessing(renderTarget) { this._draw((layer) => { return this._drawRenderTargetPredicate(layer, false, false, this.scene.activeCamera ? this.scene.activeCamera.layerMask : 0, renderTarget); }); } /** * Adds all the elements from the container to the scene * @param container the container holding the elements */ addFromContainer(container) { if (!container.layers) { return; } for (const layer of container.layers) { 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) */ removeFromContainer(container, dispose = false) { if (!container.layers) { return; } for (const layer of container.layers) { const index = this.scene.layers.indexOf(layer); if (index !== -1) { this.scene.layers.splice(index, 1); } if (dispose) { layer.dispose(); } } } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Layers/layer.js init_observable(); init_math_vector(); init_math_color(); init_engineStore(); init_buffer(); init_texture(); init_sceneComponent(); init_drawWrapper(); var Layer = class _Layer { static { __name(this, "Layer"); } /** * Determines if the layer is drawn before (true) or after (false) post-processing. * If the layer is background, it is always before. */ set applyPostProcess(value) { this._applyPostProcess = value; } get applyPostProcess() { return this.isBackground || this._applyPostProcess; } /** * Back compatibility with callback before the onDisposeObservable existed. * The set callback will be triggered when the layer has been disposed. */ set onDispose(callback) { if (this._onDisposeObserver) { this.onDisposeObservable.remove(this._onDisposeObserver); } this._onDisposeObserver = this.onDisposeObservable.add(callback); } /** * Back compatibility with callback before the onBeforeRenderObservable existed. * The set callback will be triggered just before rendering the layer. */ set onBeforeRender(callback) { if (this._onBeforeRenderObserver) { this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver); } this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback); } /** * Back compatibility with callback before the onAfterRenderObservable existed. * The set callback will be triggered just after rendering the layer. */ set onAfterRender(callback) { if (this._onAfterRenderObserver) { this.onAfterRenderObservable.remove(this._onAfterRenderObserver); } this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback); } /** * Gets the shader language used in this material. */ get shaderLanguage() { return this._shaderLanguage; } /** * 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 * @param forceGLSL Use the GLSL code generation for the shader (even on WebGPU). Default is false */ constructor(name260, imgUrl, scene, isBackground, color, forceGLSL = false) { this.name = name260; this._applyPostProcess = true; this.scale = new Vector2(1, 1); this.offset = new Vector2(0, 0); this.alphaBlendingMode = 2; this.layerMask = 268435455; this.renderTargetTextures = []; this.renderOnlyInRenderTargetTextures = false; this.convertToLinearSpace = false; this.isEnabled = true; this._vertexBuffers = {}; this.onDisposeObservable = new Observable(); this.onBeforeRenderObservable = new Observable(); this.onAfterRenderObservable = new Observable(); this._shaderLanguage = 0; this._shadersLoaded = false; this.texture = imgUrl ? new Texture(imgUrl, scene, true) : null; this.isBackground = isBackground === void 0 ? true : isBackground; this.color = color === void 0 ? new Color4(1, 1, 1, 1) : color; this._scene = scene || EngineStore.LastCreatedScene; const engine = this._scene.getEngine(); if (engine.isWebGPU && !forceGLSL && !_Layer.ForceGLSL) { this._shaderLanguage = 1; } let layerComponent = this._scene._getComponent(SceneComponentConstants.NAME_LAYER); if (!layerComponent) { layerComponent = new LayerSceneComponent(this._scene); this._scene._addComponent(layerComponent); } this._scene.layers.push(this); this._drawWrapper = new DrawWrapper(engine); const vertices = []; vertices.push(1, 1); vertices.push(-1, 1); vertices.push(-1, -1); vertices.push(1, -1); const vertexBuffer = new VertexBuffer(engine, vertices, VertexBuffer.PositionKind, false, false, 2); this._vertexBuffers[VertexBuffer.PositionKind] = vertexBuffer; this._createIndexBuffer(); } _createIndexBuffer() { const engine = this._scene.getEngine(); const indices = []; indices.push(0); indices.push(1); indices.push(2); indices.push(0); indices.push(2); indices.push(3); this._indexBuffer = engine.createIndexBuffer(indices); } /** @internal */ _rebuild() { const vb = this._vertexBuffers[VertexBuffer.PositionKind]; if (vb) { vb._rebuild(); } this._createIndexBuffer(); } /** * Checks if the layer is ready to be rendered * @returns true if the layer is ready. False otherwise. */ isReady() { const engine = this._scene.getEngine(); let defines = ""; if (this.alphaTest) { defines = "#define ALPHATEST"; } if (this.texture) { if (this.texture.gammaSpace) { if (this.convertToLinearSpace) { defines += "\n#define CONVERT_TO_LINEAR"; } } else if (!this.convertToLinearSpace) { defines += "\n#define CONVERT_TO_GAMMA"; } } if (this._previousDefines !== defines) { this._previousDefines = defines; this._drawWrapper.effect = engine.createEffect("layer", [VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], defines, void 0, void 0, void 0, void 0, this._shaderLanguage, this._shadersLoaded ? void 0 : async () => { if (this._shaderLanguage === 1) { await Promise.all([Promise.resolve().then(() => (init_layer_vertex(), layer_vertex_exports)), Promise.resolve().then(() => (init_layer_fragment(), layer_fragment_exports))]); } else { await Promise.all([Promise.resolve().then(() => (init_layer_vertex2(), layer_vertex_exports2)), Promise.resolve().then(() => (init_layer_fragment2(), layer_fragment_exports2))]); } this._shadersLoaded = true; }); } const currentEffect = this._drawWrapper.effect; return !!currentEffect?.isReady() && (!this.texture || this.texture.isReady()); } /** * Renders the layer in the scene. */ render() { if (!this.isEnabled) { return; } const engine = this._scene.getEngine(); if (!this.isReady()) { return; } const currentEffect = this._drawWrapper.effect; this.onBeforeRenderObservable.notifyObservers(this); engine.enableEffect(this._drawWrapper); engine.setState(false); if (this.texture) { currentEffect.setTexture("textureSampler", this.texture); currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix()); } currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a); currentEffect.setVector2("offset", this.offset); currentEffect.setVector2("scale", this.scale); engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect); if (!this.alphaTest) { engine.setAlphaMode(this.alphaBlendingMode); engine.drawElementsType(Material.TriangleFillMode, 0, 6); engine.setAlphaMode(0); } else { engine.drawElementsType(Material.TriangleFillMode, 0, 6); } this.onAfterRenderObservable.notifyObservers(this); } /** * Disposes and releases the associated resources. */ dispose() { const vertexBuffer = this._vertexBuffers[VertexBuffer.PositionKind]; if (vertexBuffer) { vertexBuffer.dispose(); this._vertexBuffers[VertexBuffer.PositionKind] = null; } if (this._indexBuffer) { this._scene.getEngine()._releaseBuffer(this._indexBuffer); this._indexBuffer = null; } if (this.texture) { this.texture.dispose(); this.texture = null; } this.renderTargetTextures = []; const index = this._scene.layers.indexOf(this); this._scene.layers.splice(index, 1); this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); this.onAfterRenderObservable.clear(); this.onBeforeRenderObservable.clear(); } }; Layer.ForceGLSL = false; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/gui/2D/valueAndUnit.js init_observable(); var ValueAndUnit = class _ValueAndUnit { static { __name(this, "ValueAndUnit"); } /** * Creates a new ValueAndUnit * @param value defines the value to store * @param unit defines the unit to store - defaults to ValueAndUnit.UNITMODE_PIXEL * @param negativeValueAllowed defines a boolean indicating if the value can be negative */ constructor(value, unit = _ValueAndUnit.UNITMODE_PIXEL, negativeValueAllowed = true) { this.negativeValueAllowed = negativeValueAllowed; this._value = 1; this._unit = _ValueAndUnit.UNITMODE_PIXEL; this.ignoreAdaptiveScaling = false; this.onChangedObservable = new Observable(); this._value = value; this._unit = unit; this._originalUnit = unit; } /** Gets a boolean indicating if the value is a percentage */ get isPercentage() { return this._unit === _ValueAndUnit.UNITMODE_PERCENTAGE; } /** Gets a boolean indicating if the value is store as pixel */ get isPixel() { return this._unit === _ValueAndUnit.UNITMODE_PIXEL; } /** * Gets value (without units) * @deprecated use value property instead */ get internalValue() { return this._value; } /** Gets value (without units) */ get value() { return this._value; } /** Sets value (without units) */ set value(value) { if (value !== this._value) { this._value = value; this.onChangedObservable.notifyObservers(); } } /** Gets units (without value) */ get unit() { return this._unit; } /** Sets units (without value) */ set unit(value) { if (value !== this._unit) { this._unit = value; this.onChangedObservable.notifyObservers(); } } /** * Gets value as pixel * @param host defines the root host * @param refValue defines the reference value for percentages * @returns the value as pixel */ getValueInPixel(host, refValue) { if (this.isPixel) { return this.getValue(host); } return this.getValue(host) * refValue; } /** * Update the current value and unit. * @param value defines the value to store * @param unit defines the unit to store * @returns the current ValueAndUnit */ updateInPlace(value, unit = _ValueAndUnit.UNITMODE_PIXEL) { if (this.value !== value || this.unit !== unit) { this._value = value; this._unit = unit; this.onChangedObservable.notifyObservers(); } return this; } /** * Gets the value accordingly to its unit * @param host defines the root host * @returns the value */ getValue(host) { if (host && !this.ignoreAdaptiveScaling && this.unit !== _ValueAndUnit.UNITMODE_PERCENTAGE) { let width = 0; let height = 0; if (host.idealWidth) { width = Math.ceil(this._value * host.getSize().width / host.idealWidth); } if (host.idealHeight) { height = Math.ceil(this._value * host.getSize().height / host.idealHeight); } if (host.useSmallestIdeal && host.idealWidth && host.idealHeight) { return window.innerWidth < window.innerHeight ? width : height; } if (host.idealWidth) { return width; } if (host.idealHeight) { return height; } } return this._value; } /** * Gets a string representation of the value * @param host defines the root host * @param decimals defines an optional number of decimals to display * @returns a string */ toString(host, decimals) { switch (this._unit) { case _ValueAndUnit.UNITMODE_PERCENTAGE: { const percentage = this.getValue(host) * 100; return (decimals ? percentage.toFixed(decimals) : percentage) + "%"; } case _ValueAndUnit.UNITMODE_PIXEL: { const pixels = this.getValue(host); return (decimals ? pixels.toFixed(decimals) : pixels) + "px"; } } return this._unit.toString(); } /** * Store a value parsed from a string * @param source defines the source string * @returns true if the value was successfully parsed and updated */ fromString(source) { const match = _ValueAndUnit._Regex.exec(source.toString()); if (!match || match.length === 0) { return false; } let sourceValue = parseFloat(match[1]); let sourceUnit = this._originalUnit; if (!this.negativeValueAllowed) { if (sourceValue < 0) { sourceValue = 0; } } if (match.length === 4) { switch (match[3]) { case "px": sourceUnit = _ValueAndUnit.UNITMODE_PIXEL; break; case "%": sourceUnit = _ValueAndUnit.UNITMODE_PERCENTAGE; sourceValue /= 100; break; } } if (sourceValue === this._value && sourceUnit === this._unit) { return false; } this._value = sourceValue; this._unit = sourceUnit; this.onChangedObservable.notifyObservers(); return true; } /** UNITMODE_PERCENTAGE */ static get UNITMODE_PERCENTAGE() { return _ValueAndUnit._UNITMODE_PERCENTAGE; } /** UNITMODE_PIXEL */ static get UNITMODE_PIXEL() { return _ValueAndUnit._UNITMODE_PIXEL; } }; ValueAndUnit._Regex = /(^-?\d*(\.\d+)?)(%|px)?/; ValueAndUnit._UNITMODE_PERCENTAGE = 0; ValueAndUnit._UNITMODE_PIXEL = 1; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/gui/2D/measure.js init_math_vector(); var TmpRect = [new Vector2(0, 0), new Vector2(0, 0), new Vector2(0, 0), new Vector2(0, 0)]; var TmpRect2 = [new Vector2(0, 0), new Vector2(0, 0), new Vector2(0, 0), new Vector2(0, 0)]; var TmpV1 = new Vector2(0, 0); var TmpV2 = new Vector2(0, 0); var Measure = class _Measure { static { __name(this, "Measure"); } /** * Creates a new measure * @param left defines left coordinate * @param top defines top coordinate * @param width defines width dimension * @param height defines height dimension */ constructor(left, top, width, height) { this.left = left; this.top = top; this.width = width; this.height = height; } /** * Copy from another measure * @param other defines the other measure to copy from */ copyFrom(other) { this.left = other.left; this.top = other.top; this.width = other.width; this.height = other.height; } /** * Copy from a group of 4 floats * @param left defines left coordinate * @param top defines top coordinate * @param width defines width dimension * @param height defines height dimension */ copyFromFloats(left, top, width, height) { this.left = left; this.top = top; this.width = width; this.height = height; } /** * Computes the axis aligned bounding box measure for two given measures * @param a Input measure * @param b Input measure * @param result the resulting bounding measure */ static CombineToRef(a, b, result) { const left = Math.min(a.left, b.left); const top = Math.min(a.top, b.top); const right = Math.max(a.left + a.width, b.left + b.width); const bottom = Math.max(a.top + a.height, b.top + b.height); result.left = left; result.top = top; result.width = right - left; result.height = bottom - top; } /** * Computes the axis aligned bounding box of the measure after it is modified by a given transform * @param transform the matrix to transform the measure before computing the AABB * @param addX number to add to left * @param addY number to add to top * @param addWidth number to add to width * @param addHeight number to add to height * @param result the resulting AABB */ addAndTransformToRef(transform, addX, addY, addWidth, addHeight, result) { const left = this.left + addX; const top = this.top + addY; const width = this.width + addWidth; const height = this.height + addHeight; TmpRect[0].copyFromFloats(left, top); TmpRect[1].copyFromFloats(left + width, top); TmpRect[2].copyFromFloats(left + width, top + height); TmpRect[3].copyFromFloats(left, top + height); TmpV1.copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE); TmpV2.copyFromFloats(0, 0); for (let i = 0; i < 4; i++) { transform.transformCoordinates(TmpRect[i].x, TmpRect[i].y, TmpRect2[i]); TmpV1.x = Math.floor(Math.min(TmpV1.x, TmpRect2[i].x)); TmpV1.y = Math.floor(Math.min(TmpV1.y, TmpRect2[i].y)); TmpV2.x = Math.ceil(Math.max(TmpV2.x, TmpRect2[i].x)); TmpV2.y = Math.ceil(Math.max(TmpV2.y, TmpRect2[i].y)); } result.left = TmpV1.x; result.top = TmpV1.y; result.width = TmpV2.x - TmpV1.x; result.height = TmpV2.y - TmpV1.y; } /** * Computes the axis aligned bounding box of the measure after it is modified by a given transform * @param transform the matrix to transform the measure before computing the AABB * @param result the resulting AABB */ transformToRef(transform, result) { this.addAndTransformToRef(transform, 0, 0, 0, 0, result); } /** * Check equality between this measure and another one * @param other defines the other measures * @returns true if both measures are equals */ isEqualsTo(other) { if (this.left !== other.left) { return false; } if (this.top !== other.top) { return false; } if (this.width !== other.width) { return false; } if (this.height !== other.height) { return false; } return true; } /** * Creates an empty measure * @returns a new measure */ static Empty() { return new _Measure(0, 0, 0, 0); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/gui/2D/math2D.js init_math_vector(); init_math_constants(); var Vector2WithInfo = class extends Vector2 { static { __name(this, "Vector2WithInfo"); } /** * Creates a new Vector2WithInfo * @param source defines the vector2 data to transport * @param buttonIndex defines the current mouse button index */ constructor(source, buttonIndex = 0) { super(source.x, source.y); this.buttonIndex = buttonIndex; } }; var Matrix2D = class _Matrix2D { static { __name(this, "Matrix2D"); } /** * Creates a new matrix * @param m00 defines value for (0, 0) * @param m01 defines value for (0, 1) * @param m10 defines value for (1, 0) * @param m11 defines value for (1, 1) * @param m20 defines value for (2, 0) * @param m21 defines value for (2, 1) */ constructor(m00, m01, m10, m11, m20, m21) { this.m = new Float32Array(6); this.fromValues(m00, m01, m10, m11, m20, m21); } /** * Fills the matrix from direct values * @param m00 defines value for (0, 0) * @param m01 defines value for (0, 1) * @param m10 defines value for (1, 0) * @param m11 defines value for (1, 1) * @param m20 defines value for (2, 0) * @param m21 defines value for (2, 1) * @returns the current modified matrix */ fromValues(m00, m01, m10, m11, m20, m21) { this.m[0] = m00; this.m[1] = m01; this.m[2] = m10; this.m[3] = m11; this.m[4] = m20; this.m[5] = m21; return this; } /** * Gets matrix determinant * @returns the determinant */ determinant() { return this.m[0] * this.m[3] - this.m[1] * this.m[2]; } /** * Inverses the matrix and stores it in a target matrix * @param result defines the target matrix * @returns the current matrix */ invertToRef(result) { const l0 = this.m[0]; const l1 = this.m[1]; const l2 = this.m[2]; const l3 = this.m[3]; const l4 = this.m[4]; const l5 = this.m[5]; const det = this.determinant(); if (det < Epsilon * Epsilon) { result.m[0] = 0; result.m[1] = 0; result.m[2] = 0; result.m[3] = 0; result.m[4] = 0; result.m[5] = 0; return this; } const detDiv = 1 / det; const det4 = l2 * l5 - l3 * l4; const det5 = l1 * l4 - l0 * l5; result.m[0] = l3 * detDiv; result.m[1] = -l1 * detDiv; result.m[2] = -l2 * detDiv; result.m[3] = l0 * detDiv; result.m[4] = det4 * detDiv; result.m[5] = det5 * detDiv; return this; } /** * Multiplies the current matrix with another one * @param other defines the second operand * @param result defines the target matrix * @returns the current matrix */ multiplyToRef(other, result) { const l0 = this.m[0]; const l1 = this.m[1]; const l2 = this.m[2]; const l3 = this.m[3]; const l4 = this.m[4]; const l5 = this.m[5]; const r0 = other.m[0]; const r1 = other.m[1]; const r2 = other.m[2]; const r3 = other.m[3]; const r4 = other.m[4]; const r5 = other.m[5]; result.m[0] = l0 * r0 + l1 * r2; result.m[1] = l0 * r1 + l1 * r3; result.m[2] = l2 * r0 + l3 * r2; result.m[3] = l2 * r1 + l3 * r3; result.m[4] = l4 * r0 + l5 * r2 + r4; result.m[5] = l4 * r1 + l5 * r3 + r5; return this; } /** * Applies the current matrix to a set of 2 floats and stores the result in a vector2 * @param x defines the x coordinate to transform * @param y defines the x coordinate to transform * @param result defines the target vector2 * @returns the current matrix */ transformCoordinates(x, y, result) { result.x = x * this.m[0] + y * this.m[2] + this.m[4]; result.y = x * this.m[1] + y * this.m[3] + this.m[5]; return this; } // Statics /** * Creates an identity matrix * @returns a new matrix */ static Identity() { return new _Matrix2D(1, 0, 0, 1, 0, 0); } /** * Creates an identity matrix and stores it in a target matrix * @param result defines the target matrix */ static IdentityToRef(result) { result.m[0] = 1; result.m[1] = 0; result.m[2] = 0; result.m[3] = 1; result.m[4] = 0; result.m[5] = 0; } /** * Creates a translation matrix and stores it in a target matrix * @param x defines the x coordinate of the translation * @param y defines the y coordinate of the translation * @param result defines the target matrix */ static TranslationToRef(x, y, result) { result.fromValues(1, 0, 0, 1, x, y); } /** * Creates a scaling matrix and stores it in a target matrix * @param x defines the x coordinate of the scaling * @param y defines the y coordinate of the scaling * @param result defines the target matrix */ static ScalingToRef(x, y, result) { result.fromValues(x, 0, 0, y, 0, 0); } /** * Creates a rotation matrix and stores it in a target matrix * @param angle defines the rotation angle * @param result defines the target matrix */ static RotationToRef(angle, result) { const s = Math.sin(angle); const c = Math.cos(angle); result.fromValues(c, s, -s, c, 0, 0); } /** * Composes a matrix from translation, rotation, scaling and parent matrix and stores it in a target matrix * @param tx defines the x coordinate of the translation * @param ty defines the y coordinate of the translation * @param angle defines the rotation angle * @param scaleX defines the x coordinate of the scaling * @param scaleY defines the y coordinate of the scaling * @param parentMatrix defines the parent matrix to multiply by (can be null) * @param result defines the target matrix */ static ComposeToRef(tx, ty, angle, scaleX, scaleY, parentMatrix, result) { _Matrix2D.TranslationToRef(tx, ty, _Matrix2D._TempPreTranslationMatrix); _Matrix2D.ScalingToRef(scaleX, scaleY, _Matrix2D._TempScalingMatrix); _Matrix2D.RotationToRef(angle, _Matrix2D._TempRotationMatrix); _Matrix2D.TranslationToRef(-tx, -ty, _Matrix2D._TempPostTranslationMatrix); _Matrix2D._TempPreTranslationMatrix.multiplyToRef(_Matrix2D._TempScalingMatrix, _Matrix2D._TempCompose0); _Matrix2D._TempCompose0.multiplyToRef(_Matrix2D._TempRotationMatrix, _Matrix2D._TempCompose1); if (parentMatrix) { _Matrix2D._TempCompose1.multiplyToRef(_Matrix2D._TempPostTranslationMatrix, _Matrix2D._TempCompose2); _Matrix2D._TempCompose2.multiplyToRef(parentMatrix, result); } else { _Matrix2D._TempCompose1.multiplyToRef(_Matrix2D._TempPostTranslationMatrix, result); } } }; Matrix2D._TempPreTranslationMatrix = Matrix2D.Identity(); Matrix2D._TempPostTranslationMatrix = Matrix2D.Identity(); Matrix2D._TempRotationMatrix = Matrix2D.Identity(); Matrix2D._TempScalingMatrix = Matrix2D.Identity(); Matrix2D._TempCompose0 = Matrix2D.Identity(); Matrix2D._TempCompose1 = Matrix2D.Identity(); Matrix2D._TempCompose2 = Matrix2D.Identity(); var MathTools = class _MathTools { static { __name(this, "MathTools"); } /** * Rounds a number to the nearest multiple of a given precision * @param value the value to be rounded * @param precision the multiple to which the value will be rounded. Default is 100 (2 decimal digits) * @returns */ static Round(value, precision = _MathTools.DefaultRoundingPrecision) { return Math.round(value * precision) / precision; } }; MathTools.DefaultRoundingPrecision = 100; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/gui/2D/controls/control.js init_tslib_es6(); init_observable(); init_math_vector(); init_pointerEvents(); init_logger(); init_tools(); init_typeStore(); init_decorators(); init_decorators_serialization(); init_engineStore(); var Control = class _Control { static { __name(this, "Control"); } /** * Gets or sets a boolean indicating if the control is readonly (default: false). * A readonly control will still raise pointer events but will not react to them */ get isReadOnly() { return this._isReadOnly; } set isReadOnly(value) { this._isReadOnly = value; } /** * Gets the transformed measure, that is the bounding box of the control after applying all transformations */ get transformedMeasure() { return this._evaluatedMeasure; } /** * Sets/Gets a boolean indicating if the children are clipped to the current control bounds. * Please note that not clipping children may generate issues with adt.useInvalidateRectOptimization so it is recommended to turn this optimization off if you want to use unclipped children */ set clipChildren(value) { this._clipChildren = value; } get clipChildren() { return this._clipChildren; } /** * Sets/Gets a boolean indicating that control content must be clipped * Please note that not clipping content may generate issues with adt.useInvalidateRectOptimization so it is recommended to turn this optimization off if you want to use unclipped children */ set clipContent(value) { this._clipContent = value; } get clipContent() { return this._clipContent; } /** Gets or sets a value indicating the offset to apply on X axis to render the shadow */ get shadowOffsetX() { return this._shadowOffsetX; } set shadowOffsetX(value) { if (this._shadowOffsetX === value) { return; } this._shadowOffsetX = value; this._markAsDirty(); } /** Gets or sets a value indicating the offset to apply on Y axis to render the shadow */ get shadowOffsetY() { return this._shadowOffsetY; } set shadowOffsetY(value) { if (this._shadowOffsetY === value) { return; } this._shadowOffsetY = value; this._markAsDirty(); } /** Gets or sets a value indicating the amount of blur to use to render the shadow */ get shadowBlur() { return this._shadowBlur; } set shadowBlur(value) { if (this._shadowBlur === value) { return; } this._previousShadowBlur = this._shadowBlur; this._shadowBlur = value; this._markAsDirty(); } /** Gets or sets a value indicating the color of the shadow (black by default ie. "#000") */ get shadowColor() { return this._shadowColor; } set shadowColor(value) { if (this._shadowColor === value) { return; } this._shadowColor = value; this._markAsDirty(); } // Properties /** Gets the control type name */ get typeName() { return this._getTypeName(); } /** * Get the current class name of the control. * @returns current class name */ getClassName() { return this._getTypeName(); } /** * Gets or sets the accessibility tag to describe the control for accessibility purpose. * By default, GUI controls already indicate accessibility info, but one can override the info using this tag. */ set accessibilityTag(value) { this._accessibilityTag = value; this.onAccessibilityTagChangedObservable.notifyObservers(value); } get accessibilityTag() { return this._accessibilityTag; } /** * Get the hosting AdvancedDynamicTexture */ get host() { return this._host; } /** Gets or set information about font offsets (used to render and align text) */ get fontOffset() { return this._fontOffset; } set fontOffset(offset) { this._fontOffset = offset; } /** Gets or sets alpha value for the control (1 means opaque and 0 means entirely transparent) */ get alpha() { return this._alpha; } set alpha(value) { if (this._alpha === value) { return; } this._alphaSet = true; this._alpha = value; this._markAsDirty(); } /** * Gets or sets a number indicating size of stroke we want to highlight the control with (mostly for debugging purpose) */ get highlightLineWidth() { return this._highlightLineWidth; } set highlightLineWidth(value) { if (this._highlightLineWidth === value) { return; } this._highlightLineWidth = value; this._markAsDirty(); } /** * Gets or sets a boolean indicating that we want to highlight the control (mostly for debugging purpose) */ get isHighlighted() { return this._isHighlighted; } set isHighlighted(value) { if (this._isHighlighted === value) { return; } this._isHighlighted = value; this._markAsDirty(); } /** * Gets or sets a string defining the color to use for highlighting this control */ get highlightColor() { return this._highlightColor; } set highlightColor(value) { if (this._highlightColor === value) { return; } this._highlightColor = value; this._markAsDirty(); } /** Gets or sets a value indicating the scale factor on X axis (1 by default) * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#rotation-and-scaling */ get scaleX() { return this._scaleX; } set scaleX(value) { if (this._scaleX === value) { return; } this._scaleX = value; this._markAsDirty(); this._markMatrixAsDirty(); } /** Gets or sets a value indicating the scale factor on Y axis (1 by default) * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#rotation-and-scaling */ get scaleY() { return this._scaleY; } set scaleY(value) { if (this._scaleY === value) { return; } this._scaleY = value; this._markAsDirty(); this._markMatrixAsDirty(); } /** Gets or sets the rotation angle (0 by default) * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#rotation-and-scaling */ get rotation() { return this._rotation; } set rotation(value) { if (this._rotation === value) { return; } this._rotation = value; this._markAsDirty(); this._markMatrixAsDirty(); } /** Gets or sets the transformation center on Y axis (0 by default) * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#rotation-and-scaling */ get transformCenterY() { return this._transformCenterY; } set transformCenterY(value) { if (this._transformCenterY === value) { return; } this._transformCenterY = value; this._markAsDirty(); this._markMatrixAsDirty(); } /** Gets or sets the transformation center on X axis (0 by default) * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#rotation-and-scaling */ get transformCenterX() { return this._transformCenterX; } set transformCenterX(value) { if (this._transformCenterX === value) { return; } this._transformCenterX = value; this._markAsDirty(); this._markMatrixAsDirty(); } /** * Gets or sets the horizontal alignment * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#alignments */ get horizontalAlignment() { return this._horizontalAlignment; } set horizontalAlignment(value) { if (this._horizontalAlignment === value) { return; } this._horizontalAlignment = value; this._markAsDirty(); } /** * Gets or sets the vertical alignment * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#alignments */ get verticalAlignment() { return this._verticalAlignment; } set verticalAlignment(value) { if (this._verticalAlignment === value) { return; } this._verticalAlignment = value; this._markAsDirty(); } set fixedRatio(value) { if (this._fixedRatio === value) { return; } this._fixedRatio = value; this._markAsDirty(); } /** * Gets or sets a fixed ratio for this control. * When different from 0, the ratio is used to compute the "second" dimension. * The first dimension used in the computation is the last one set (by setting width / widthInPixels or height / heightInPixels), and the * second dimension is computed as first dimension * fixedRatio */ get fixedRatio() { return this._fixedRatio; } set fixedRatioMasterIsWidth(value) { if (this._fixedRatioMasterIsWidth === value) { return; } this._fixedRatioMasterIsWidth = value; this._markAsDirty(); } /** * Gets or sets a boolean indicating that the fixed ratio is set on the width instead of the height. True by default. * When the height of a control is set, this property is changed to false. */ get fixedRatioMasterIsWidth() { return this._fixedRatioMasterIsWidth; } /** * Gets or sets control width * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get width() { return this._width.toString(this._host); } set width(value) { this._fixedRatioMasterIsWidth = true; if (this._width.toString(this._host) === value) { return; } if (this._width.fromString(value)) { this._markAsDirty(); } } /** * Gets or sets the control width in pixel * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get widthInPixels() { return this._width.getValueInPixel(this._host, this._cachedParentMeasure.width); } set widthInPixels(value) { if (isNaN(value)) { return; } this._fixedRatioMasterIsWidth = true; this.width = value + "px"; } /** * Gets or sets control height * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get height() { return this._height.toString(this._host); } set height(value) { this._fixedRatioMasterIsWidth = false; if (this._height.toString(this._host) === value) { return; } if (this._height.fromString(value)) { this._markAsDirty(); } } /** * Gets or sets control height in pixel * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get heightInPixels() { return this._height.getValueInPixel(this._host, this._cachedParentMeasure.height); } set heightInPixels(value) { if (isNaN(value)) { return; } this._fixedRatioMasterIsWidth = false; this.height = value + "px"; } /** Gets or set font family */ get fontFamily() { return this._fontFamily; } set fontFamily(value) { if (this._fontFamily === value) { return; } this._fontFamily = value; this._resetFontCache(); } /** Gets or sets font style */ get fontStyle() { return this._fontStyle; } set fontStyle(value) { if (this._fontStyle === value) { return; } this._fontStyle = value; this._resetFontCache(); } /** Gets or sets font weight */ get fontWeight() { return this._fontWeight; } set fontWeight(value) { if (this._fontWeight === value) { return; } this._fontWeight = value; this._resetFontCache(); } /** * Gets or sets style * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#styles */ get style() { return this._style; } set style(value) { if (this._style) { this._style.onChangedObservable.remove(this._styleObserver); this._styleObserver = null; } this._style = value; if (this._style) { this._styleObserver = this._style.onChangedObservable.add(() => { this._markAsDirty(); this._resetFontCache(); }); } this._markAsDirty(); this._resetFontCache(); } /** @internal */ get _isFontSizeInPercentage() { return this._fontSize.isPercentage; } /** Gets or sets font size in pixels */ get fontSizeInPixels() { const fontSizeToUse = this._style ? this._style._fontSize : this._fontSize; if (fontSizeToUse.isPixel) { return fontSizeToUse.getValue(this._host); } return fontSizeToUse.getValueInPixel(this._host, this._tempParentMeasure.height || this._cachedParentMeasure.height); } set fontSizeInPixels(value) { if (isNaN(value)) { return; } this.fontSize = value + "px"; } /** Gets or sets font size */ get fontSize() { return this._fontSize.toString(this._host); } set fontSize(value) { if (this._fontSize.toString(this._host) === value) { return; } if (this._fontSize.fromString(value)) { this._markAsDirty(); this._resetFontCache(); } } /** Gets or sets foreground color */ get color() { return this._color; } set color(value) { if (this._color === value) { return; } this._color = value; this._markAsDirty(); } /** Gets or sets gradient. Setting a gradient will override the color */ get gradient() { return this._gradient; } set gradient(value) { if (this._gradient === value) { return; } this._gradient = value; this._markAsDirty(); } /** Gets or sets z index which is used to reorder controls on the z axis */ get zIndex() { return this._zIndex; } set zIndex(value) { if (this.zIndex === value) { return; } this._zIndex = value; if (this.parent) { this.parent._reOrderControl(this); } } /** Gets or sets a boolean indicating if the control can be rendered */ get notRenderable() { return this._doNotRender; } set notRenderable(value) { if (this._doNotRender === value) { return; } this._doNotRender = value; this._markAsDirty(); } /** Gets or sets a boolean indicating if the control is visible */ get isVisible() { return this._isVisible; } set isVisible(value) { if (this._isVisible === value) { return; } this._isVisible = value; this._markAsDirty(true); this.onIsVisibleChangedObservable.notifyObservers(value); } /** Gets a boolean indicating that the control needs to update its rendering */ get isDirty() { return this._isDirty; } /** * Gets the current linked mesh (or null if none) */ get linkedMesh() { return this._linkedMesh; } /** * Gets or sets a value indicating the padding should work like in CSS. * Basically, it will add the padding amount on each side of the parent control for its children. */ get descendantsOnlyPadding() { return this._descendantsOnlyPadding; } set descendantsOnlyPadding(value) { if (this._descendantsOnlyPadding === value) { return; } this._descendantsOnlyPadding = value; this._markAsDirty(); } /** * Gets or sets a value indicating the padding to use on the left of the control * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get paddingLeft() { return this._paddingLeft.toString(this._host); } set paddingLeft(value) { if (this._paddingLeft.fromString(value)) { this._markAsDirty(); } } /** * Gets or sets a value indicating the padding in pixels to use on the left of the control * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get paddingLeftInPixels() { return this._paddingLeft.getValueInPixel(this._host, this._cachedParentMeasure.width); } set paddingLeftInPixels(value) { if (isNaN(value)) { return; } this.paddingLeft = value + "px"; } /** @internal */ get _paddingLeftInPixels() { if (this._descendantsOnlyPadding) { return 0; } return this.paddingLeftInPixels; } /** * Gets or sets a value indicating the padding to use on the right of the control * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get paddingRight() { return this._paddingRight.toString(this._host); } set paddingRight(value) { if (this._paddingRight.fromString(value)) { this._markAsDirty(); } } /** * Gets or sets a value indicating the padding in pixels to use on the right of the control * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get paddingRightInPixels() { return this._paddingRight.getValueInPixel(this._host, this._cachedParentMeasure.width); } set paddingRightInPixels(value) { if (isNaN(value)) { return; } this.paddingRight = value + "px"; } /** @internal */ get _paddingRightInPixels() { if (this._descendantsOnlyPadding) { return 0; } return this.paddingRightInPixels; } /** * Gets or sets a value indicating the padding to use on the top of the control * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get paddingTop() { return this._paddingTop.toString(this._host); } set paddingTop(value) { if (this._paddingTop.fromString(value)) { this._markAsDirty(); } } /** * Gets or sets a value indicating the padding in pixels to use on the top of the control * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get paddingTopInPixels() { return this._paddingTop.getValueInPixel(this._host, this._cachedParentMeasure.height); } set paddingTopInPixels(value) { if (isNaN(value)) { return; } this.paddingTop = value + "px"; } /** @internal */ get _paddingTopInPixels() { if (this._descendantsOnlyPadding) { return 0; } return this.paddingTopInPixels; } /** * Gets or sets a value indicating the padding to use on the bottom of the control * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get paddingBottom() { return this._paddingBottom.toString(this._host); } set paddingBottom(value) { if (this._paddingBottom.fromString(value)) { this._markAsDirty(); } } /** * Gets or sets a value indicating the padding in pixels to use on the bottom of the control * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get paddingBottomInPixels() { return this._paddingBottom.getValueInPixel(this._host, this._cachedParentMeasure.height); } set paddingBottomInPixels(value) { if (isNaN(value)) { return; } this.paddingBottom = value + "px"; } /** @internal */ get _paddingBottomInPixels() { if (this._descendantsOnlyPadding) { return 0; } return this.paddingBottomInPixels; } /** * Gets or sets a value indicating the left coordinate of the control * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get left() { return this._left.toString(this._host); } set left(value) { if (this._left.fromString(value)) { this._markAsDirty(); } } /** * Gets or sets a value indicating the left coordinate in pixels of the control * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get leftInPixels() { return this._left.getValueInPixel(this._host, this._cachedParentMeasure.width); } set leftInPixels(value) { if (isNaN(value)) { return; } this.left = value + "px"; } /** * Gets or sets a value indicating the top coordinate of the control * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get top() { return this._top.toString(this._host); } set top(value) { if (this._top.fromString(value)) { this._markAsDirty(); } } /** * Gets or sets a value indicating the top coordinate in pixels of the control * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ get topInPixels() { return this._top.getValueInPixel(this._host, this._cachedParentMeasure.height); } set topInPixels(value) { if (isNaN(value)) { return; } this.top = value + "px"; } /** * Gets or sets a value indicating the offset on X axis to the linked mesh * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#tracking-positions */ get linkOffsetX() { return this._linkOffsetX.toString(this._host); } set linkOffsetX(value) { if (this._linkOffsetX.fromString(value)) { this._markAsDirty(); } } /** * Gets or sets a value indicating the offset in pixels on X axis to the linked mesh * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#tracking-positions */ get linkOffsetXInPixels() { return this._linkOffsetX.getValueInPixel(this._host, this._cachedParentMeasure.width); } set linkOffsetXInPixels(value) { if (isNaN(value)) { return; } this.linkOffsetX = value + "px"; } /** * Gets or sets a value indicating the offset on Y axis to the linked mesh * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#tracking-positions */ get linkOffsetY() { return this._linkOffsetY.toString(this._host); } set linkOffsetY(value) { if (this._linkOffsetY.fromString(value)) { this._markAsDirty(); } } /** * Gets or sets a value indicating the offset in pixels on Y axis to the linked mesh * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#tracking-positions */ get linkOffsetYInPixels() { return this._linkOffsetY.getValueInPixel(this._host, this._cachedParentMeasure.height); } set linkOffsetYInPixels(value) { if (isNaN(value)) { return; } this.linkOffsetY = value + "px"; } /** Gets the center coordinate on X axis */ get centerX() { return this._currentMeasure.left + this._currentMeasure.width / 2; } /** Gets the center coordinate on Y axis */ get centerY() { return this._currentMeasure.top + this._currentMeasure.height / 2; } /** Gets or sets if control is Enabled */ get isEnabled() { return this._isEnabled; } set isEnabled(value) { if (this._isEnabled === value) { return; } this._isEnabled = value; this._markAsDirty(); const recursivelyFirePointerOut = /* @__PURE__ */ __name((control) => { if (!control.host) { return; } for (const pointer in control.host._lastControlOver) { if (control === this.host._lastControlOver[pointer]) { control._onPointerOut(control, null, true); delete control.host._lastControlOver[pointer]; } } if (control.children !== void 0) { for (const child of control.children) { recursivelyFirePointerOut(child); } } }, "recursivelyFirePointerOut"); recursivelyFirePointerOut(this); this.onEnabledStateChangedObservable.notifyObservers(value); } /** Gets or sets background color of control if it's disabled. Only applies to Button class. */ get disabledColor() { return this._disabledColor; } set disabledColor(value) { if (this._disabledColor === value) { return; } this._disabledColor = value; this._markAsDirty(); } /** Gets or sets front color of control if it's disabled. Only applies to Checkbox class. */ get disabledColorItem() { return this._disabledColorItem; } set disabledColorItem(value) { if (this._disabledColorItem === value) { return; } this._disabledColorItem = value; this._markAsDirty(); } /** * Border color when control is focused * When not defined the ADT color will be used. If no ADT color is defined, focused state won't have any border */ get focusedColor() { return this._focusedColor; } set focusedColor(value) { this._focusedColor = value; } /** @internal */ onBlur() { if (this._isFocused) { this._isFocused = false; if (this.focusedColor && this._unfocusedColor != null) { this.color = this._unfocusedColor; } this.onBlurObservable.notifyObservers(this); } } /** @internal */ onFocus() { this._isFocused = true; if (this.focusedColor) { this._unfocusedColor = this.color; this.color = this.focusedColor; } this.onFocusObservable.notifyObservers(this); } /** * Function called to get the list of controls that should not steal the focus from this control * @returns an array of controls */ keepsFocusWith() { return null; } /** * Function to focus a button programmatically */ focus() { this._host.moveFocusToControl(this); } /** * Function to unfocus a button programmatically */ blur() { this._host.focusedControl = null; } /** * Handles the keyboard event * @param evt Defines the KeyboardEvent */ processKeyboard(evt) { if (evt.key === "Enter") { this.onEnterPressedObservable.notifyObservers(this); } this.onKeyboardEventProcessedObservable.notifyObservers(evt, -1, this); } // Functions /** * Creates a new control * @param name defines the name of the control */ constructor(name260) { this.name = name260; this._alpha = 1; this._alphaSet = false; this._zIndex = 0; this._currentMeasure = Measure.Empty(); this._tempPaddingMeasure = Measure.Empty(); this._fontFamily = ""; this._fontStyle = ""; this._fontWeight = ""; this._fontSize = new ValueAndUnit(18, ValueAndUnit.UNITMODE_PIXEL, false); this._width = new ValueAndUnit(1, ValueAndUnit.UNITMODE_PERCENTAGE, false); this._height = new ValueAndUnit(1, ValueAndUnit.UNITMODE_PERCENTAGE, false); this._color = ""; this._style = null; this._horizontalAlignment = _Control.HORIZONTAL_ALIGNMENT_CENTER; this._verticalAlignment = _Control.VERTICAL_ALIGNMENT_CENTER; this._isDirty = true; this._wasDirty = false; this._tempParentMeasure = Measure.Empty(); this._prevCurrentMeasureTransformedIntoGlobalSpace = Measure.Empty(); this._cachedParentMeasure = Measure.Empty(); this._descendantsOnlyPadding = false; this._paddingLeft = new ValueAndUnit(0); this._paddingRight = new ValueAndUnit(0); this._paddingTop = new ValueAndUnit(0); this._paddingBottom = new ValueAndUnit(0); this._left = new ValueAndUnit(0); this._top = new ValueAndUnit(0); this._scaleX = 1; this._scaleY = 1; this._rotation = 0; this._transformCenterX = 0.5; this._transformCenterY = 0.5; this._transformMatrix = Matrix2D.Identity(); this._invertTransformMatrix = Matrix2D.Identity(); this._transformedPosition = Vector2.Zero(); this._isMatrixDirty = true; this._isVisible = true; this._isHighlighted = false; this._highlightColor = "#4affff"; this._highlightLineWidth = 2; this._fontSet = false; this._dummyVector2 = Vector2.Zero(); this._downCount = 0; this._enterCount = -1; this._doNotRender = false; this._downPointerIds = {}; this._evaluatedMeasure = new Measure(0, 0, 0, 0); this._evaluatedParentMeasure = new Measure(0, 0, 0, 0); this._isEnabled = true; this._disabledColor = "#9a9a9a"; this._disabledColorItem = "#6a6a6a"; this._isReadOnly = false; this._gradient = null; this._rebuildLayout = false; this.onEnabledStateChangedObservable = new Observable(); this._customData = {}; this._isClipped = false; this._automaticSize = false; this.metadata = null; this.isHitTestVisible = true; this.isPointerBlocker = false; this.isFocusInvisible = false; this._clipChildren = true; this._clipContent = true; this.useBitmapCache = false; this._shadowOffsetX = 0; this._shadowOffsetY = 0; this._shadowBlur = 0; this._previousShadowBlur = 0; this._shadowColor = "black"; this.hoverCursor = ""; this._linkOffsetX = new ValueAndUnit(0); this._linkOffsetY = new ValueAndUnit(0); this._accessibilityTag = null; this.onAccessibilityTagChangedObservable = new Observable(); this.onWheelObservable = new Observable(); this.onPointerMoveObservable = new Observable(); this.onPointerOutObservable = new Observable(); this.onPointerDownObservable = new Observable(); this.onPointerUpObservable = new Observable(); this.onPointerClickObservable = new Observable(); this.onEnterPressedObservable = new Observable(); this.onPointerEnterObservable = new Observable(); this.onDirtyObservable = new Observable(); this.onBeforeDrawObservable = new Observable(); this.onAfterDrawObservable = new Observable(); this.onDisposeObservable = new Observable(); this.onIsVisibleChangedObservable = new Observable(); this.isSerializable = true; this._fixedRatio = 0; this._fixedRatioMasterIsWidth = true; this.animations = null; this._focusedColor = null; this.tabIndex = -1; this._isFocused = false; this._unfocusedColor = null; this.onFocusObservable = new Observable(); this.onBlurObservable = new Observable(); this.onKeyboardEventProcessedObservable = new Observable(); this._tmpMeasureA = new Measure(0, 0, 0, 0); } /** @internal */ _getTypeName() { return "Control"; } /** * Gets the first ascendant in the hierarchy of the given type * @param className defines the required type * @returns the ascendant or null if not found */ getAscendantOfClass(className2) { if (!this.parent) { return null; } if (this.parent.getClassName() === className2) { return this.parent; } return this.parent.getAscendantOfClass(className2); } /** * Mark control element as dirty * @param force force non visible elements to be marked too */ markAsDirty(force = false) { this._markAsDirty(force); } /** * Mark the element and its children as dirty */ markAllAsDirty() { this._markAllAsDirty(); } /** @internal */ _resetFontCache() { this._fontSet = true; this._markAsDirty(); } /** * Determines if a container is an ascendant of the current control * @param container defines the container to look for * @returns true if the container is one of the ascendant of the control */ isAscendant(container) { if (!this.parent) { return false; } if (this.parent === container) { return true; } return this.parent.isAscendant(container); } /** * Gets coordinates in local control space * @param globalCoordinates defines the coordinates to transform * @returns the new coordinates in local space */ getLocalCoordinates(globalCoordinates) { const result = Vector2.Zero(); this.getLocalCoordinatesToRef(globalCoordinates, result); return result; } /** * Gets coordinates in local control space * @param globalCoordinates defines the coordinates to transform * @param result defines the target vector2 where to store the result * @returns the current control */ getLocalCoordinatesToRef(globalCoordinates, result) { result.x = globalCoordinates.x - this._currentMeasure.left; result.y = globalCoordinates.y - this._currentMeasure.top; return this; } /** * Gets coordinates in parent local control space * @param globalCoordinates defines the coordinates to transform * @returns the new coordinates in parent local space */ getParentLocalCoordinates(globalCoordinates) { const result = Vector2.Zero(); result.x = globalCoordinates.x - this._cachedParentMeasure.left; result.y = globalCoordinates.y - this._cachedParentMeasure.top; return result; } /** * Move the current control to a vector3 position projected onto the screen. * @param position defines the target position * @param scene defines the hosting scene */ moveToVector3(position, scene) { if (!this._host || this.parent !== this._host._rootContainer) { Tools.Error("Cannot move a control to a vector3 if the control is not at root level"); return; } this.horizontalAlignment = _Control.HORIZONTAL_ALIGNMENT_LEFT; this.verticalAlignment = _Control.VERTICAL_ALIGNMENT_TOP; const globalViewport = this._host._getGlobalViewport(); const projectedPosition = Vector3.Project(position, Matrix.IdentityReadOnly, scene.getTransformMatrix(), globalViewport); this._moveToProjectedPosition(projectedPosition); if (projectedPosition.z < 0 || projectedPosition.z > 1) { this.notRenderable = true; return; } this.notRenderable = false; } /** * Will store all controls that have this control as ascendant in a given array * @param results defines the array where to store the descendants * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored */ getDescendantsToRef(results, directDescendantsOnly = false, predicate) { } /** * Will return all controls that have this control as ascendant * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored * @returns all child controls */ getDescendants(directDescendantsOnly, predicate) { const results = []; this.getDescendantsToRef(results, directDescendantsOnly, predicate); return results; } /** * Link current control with a target mesh * @param mesh defines the mesh to link with * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#tracking-positions */ linkWithMesh(mesh) { if (!this._host || this.parent && this.parent !== this._host._rootContainer) { if (mesh) { Tools.Error("Cannot link a control to a mesh if the control is not at root level"); } return; } const index = this._host._linkedControls.indexOf(this); if (index !== -1) { this._linkedMesh = mesh; if (!mesh) { this._host._linkedControls.splice(index, 1); } return; } else if (!mesh) { return; } this.horizontalAlignment = _Control.HORIZONTAL_ALIGNMENT_LEFT; this.verticalAlignment = _Control.VERTICAL_ALIGNMENT_TOP; this._linkedMesh = mesh; this._host._linkedControls.push(this); } /** * Shorthand function to set the top, right, bottom, and left padding values on the control. * @param { string | number} paddingTop - The value of the top padding. * @param { string | number} paddingRight - The value of the right padding. If omitted, top is used. * @param { string | number} paddingBottom - The value of the bottom padding. If omitted, top is used. * @param { string | number} paddingLeft - The value of the left padding. If omitted, right is used. * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ setPadding(paddingTop, paddingRight, paddingBottom, paddingLeft) { const top = paddingTop; const right = paddingRight ?? top; const bottom = paddingBottom ?? top; const left = paddingLeft ?? right; this.paddingTop = top; this.paddingRight = right; this.paddingBottom = bottom; this.paddingLeft = left; } /** * Shorthand funtion to set the top, right, bottom, and left padding values in pixels on the control. * @param { number} paddingTop - The value in pixels of the top padding. * @param { number} paddingRight - The value in pixels of the right padding. If omitted, top is used. * @param { number} paddingBottom - The value in pixels of the bottom padding. If omitted, top is used. * @param { number} paddingLeft - The value in pixels of the left padding. If omitted, right is used. * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#position-and-size */ setPaddingInPixels(paddingTop, paddingRight, paddingBottom, paddingLeft) { const top = paddingTop; const right = paddingRight ?? top; const bottom = paddingBottom ?? top; const left = paddingLeft ?? right; this.paddingTopInPixels = top; this.paddingRightInPixels = right; this.paddingBottomInPixels = bottom; this.paddingLeftInPixels = left; } /** * @internal */ _moveToProjectedPosition(projectedPosition) { const oldLeft = this._left.getValue(this._host); const oldTop = this._top.getValue(this._host); const parentMeasure = this.parent?._currentMeasure; if (parentMeasure) { this._processMeasures(parentMeasure, this._host.getContext()); } let newLeft = projectedPosition.x + this._linkOffsetX.getValue(this._host) - this._currentMeasure.width / 2; let newTop = projectedPosition.y + this._linkOffsetY.getValue(this._host) - this._currentMeasure.height / 2; if (this._left.ignoreAdaptiveScaling && this._top.ignoreAdaptiveScaling) { if (Math.abs(newLeft - oldLeft) < 0.5) { newLeft = oldLeft; } if (Math.abs(newTop - oldTop) < 0.5) { newTop = oldTop; } } if (oldLeft === newLeft && oldTop === newTop) { return; } this.left = newLeft + "px"; this.top = newTop + "px"; this._left.ignoreAdaptiveScaling = true; this._top.ignoreAdaptiveScaling = true; this._markAsDirty(); } /** * @internal */ _offsetLeft(offset) { this._isDirty = true; this._currentMeasure.left += offset; } /** * @internal */ _offsetTop(offset) { this._isDirty = true; this._currentMeasure.top += offset; } /** @internal */ _markMatrixAsDirty() { this._isMatrixDirty = true; this._flagDescendantsAsMatrixDirty(); } /** @internal */ _flagDescendantsAsMatrixDirty() { } /** * @internal */ _intersectsRect(rect, context) { this._transform(context); if (this._evaluatedMeasure.left >= rect.left + rect.width) { return false; } if (this._evaluatedMeasure.top >= rect.top + rect.height) { return false; } if (this._evaluatedMeasure.left + this._evaluatedMeasure.width <= rect.left) { return false; } if (this._evaluatedMeasure.top + this._evaluatedMeasure.height <= rect.top) { return false; } return true; } /** @internal */ _computeAdditionalOffsetX() { return 0; } /** @internal */ _computeAdditionalOffsetY() { return 0; } /** @internal */ // eslint-disable-next-line @typescript-eslint/naming-convention invalidateRect() { this._transform(); if (this.host && this.host.useInvalidateRectOptimization) { this._currentMeasure.transformToRef(this._transformMatrix, this._tmpMeasureA); Measure.CombineToRef(this._tmpMeasureA, this._prevCurrentMeasureTransformedIntoGlobalSpace, this._tmpMeasureA); const shadowOffsetX = this.shadowOffsetX; const shadowOffsetY = this.shadowOffsetY; const shadowBlur = Math.max(this._previousShadowBlur, this.shadowBlur); const leftShadowOffset = Math.min(Math.min(shadowOffsetX, 0) - shadowBlur * 2, 0); const rightShadowOffset = Math.max(Math.max(shadowOffsetX, 0) + shadowBlur * 2, 0); const topShadowOffset = Math.min(Math.min(shadowOffsetY, 0) - shadowBlur * 2, 0); const bottomShadowOffset = Math.max(Math.max(shadowOffsetY, 0) + shadowBlur * 2, 0); const offsetX = this._computeAdditionalOffsetX(); const offsetY = this._computeAdditionalOffsetY(); this.host.invalidateRect(Math.floor(this._tmpMeasureA.left + leftShadowOffset - offsetX), Math.floor(this._tmpMeasureA.top + topShadowOffset - offsetY), Math.ceil(this._tmpMeasureA.left + this._tmpMeasureA.width + rightShadowOffset + offsetX), Math.ceil(this._tmpMeasureA.top + this._tmpMeasureA.height + bottomShadowOffset + offsetY)); } } /** * @internal */ _markAsDirty(force = false) { if (!this._isVisible && !force) { return; } this._isDirty = true; this._markMatrixAsDirty(); if (this._host) { this._host.markAsDirty(); } } /** @internal */ _markAllAsDirty() { this._markAsDirty(); if (this._font) { this._prepareFont(); } } /** * @internal */ _link(host) { this._host = host; if (this._host) { this.uniqueId = this._host.getScene().getUniqueId(); } } /** * @internal */ _transform(context) { if (!this._isMatrixDirty && this._scaleX === 1 && this._scaleY === 1 && this._rotation === 0) { return; } const offsetX = this._currentMeasure.width * this._transformCenterX + this._currentMeasure.left; const offsetY = this._currentMeasure.height * this._transformCenterY + this._currentMeasure.top; if (context) { context.translate(offsetX, offsetY); context.rotate(this._rotation); context.scale(this._scaleX, this._scaleY); context.translate(-offsetX, -offsetY); } if (this._isMatrixDirty || this._cachedOffsetX !== offsetX || this._cachedOffsetY !== offsetY) { this._cachedOffsetX = offsetX; this._cachedOffsetY = offsetY; this._isMatrixDirty = false; this._flagDescendantsAsMatrixDirty(); Matrix2D.ComposeToRef(-offsetX, -offsetY, this._rotation, this._scaleX, this._scaleY, this.parent ? this.parent._transformMatrix : null, this._transformMatrix); this._transformMatrix.invertToRef(this._invertTransformMatrix); this._currentMeasure.transformToRef(this._transformMatrix, this._evaluatedMeasure); } } /** * @internal */ _renderHighlight(context) { if (!this.isHighlighted) { return; } context.save(); context.strokeStyle = this._highlightColor; context.lineWidth = this._highlightLineWidth; this._renderHighlightSpecific(context); context.restore(); } /** * @internal */ _renderHighlightSpecific(context) { context.strokeRect(this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height); } _getColor(context) { return this.gradient ? this.gradient.getCanvasGradient(context) : this.color; } /** * Applies the control's state to the provided context. Important: unless this is a temporary context, * be sure to call context.save() before calling _applyStates() and later call context.restore() when * you are done using these state updates. * @internal */ _applyStates(context) { if (this._isFontSizeInPercentage) { this._fontSet = true; } if (this._host && this._host.useSmallestIdeal && !this._font) { this._fontSet = true; } if (this._fontSet) { this._prepareFont(); this._fontSet = false; } if (this._font) { context.font = this._font; } if (this._color || this.gradient) { context.fillStyle = this._getColor(context); } if (_Control.AllowAlphaInheritance) { context.globalAlpha *= this._alpha; } else if (this._alphaSet) { context.globalAlpha = this.parent && !this.parent.renderToIntermediateTexture ? this.parent.alpha * this._alpha : this._alpha; } } /** * @internal */ _layout(parentMeasure, context) { if (!this.isDirty && (!this.isVisible || this.notRenderable)) { return false; } if (this._isDirty || !this._cachedParentMeasure.isEqualsTo(parentMeasure)) { this.host._numLayoutCalls++; this._currentMeasure.addAndTransformToRef(this._transformMatrix, -this._paddingLeftInPixels | 0, -this._paddingTopInPixels | 0, this._paddingRightInPixels | 0, this._paddingBottomInPixels | 0, this._prevCurrentMeasureTransformedIntoGlobalSpace); context.save(); let rebuildCount = 0; do { this._rebuildLayout = false; this._processMeasures(parentMeasure, context); rebuildCount++; } while (this._rebuildLayout && rebuildCount < 4); if (rebuildCount >= 4) { Logger.Error(`Layout cycle detected in GUI (Control name=${this.name}, uniqueId=${this.uniqueId})`); } context.restore(); this.invalidateRect(); this._evaluateClippingState(parentMeasure); } this._wasDirty = this._isDirty; this._isDirty = false; return true; } /** * @internal */ _processMeasures(parentMeasure, context) { context.save(); this._applyStates(context); this._tempPaddingMeasure.copyFrom(parentMeasure); if (this.parent && this.parent.descendantsOnlyPadding) { this._tempPaddingMeasure.left += this.parent.paddingLeftInPixels; this._tempPaddingMeasure.top += this.parent.paddingTopInPixels; this._tempPaddingMeasure.width -= this.parent.paddingLeftInPixels + this.parent.paddingRightInPixels; this._tempPaddingMeasure.height -= this.parent.paddingTopInPixels + this.parent.paddingBottomInPixels; } this._currentMeasure.copyFrom(this._tempPaddingMeasure); this._preMeasure(this._tempPaddingMeasure, context); this._measure(); this._postMeasure(this._tempPaddingMeasure, context); this._computeAlignment(this._tempPaddingMeasure, context); this._currentMeasure.left = this._currentMeasure.left | 0; this._currentMeasure.top = this._currentMeasure.top | 0; this._currentMeasure.width = this._currentMeasure.width | 0; this._currentMeasure.height = this._currentMeasure.height | 0; this._additionalProcessing(this._tempPaddingMeasure, context); this._cachedParentMeasure.copyFrom(this._tempPaddingMeasure); this._currentMeasure.transformToRef(this._transformMatrix, this._evaluatedMeasure); if (this.onDirtyObservable.hasObservers()) { this.onDirtyObservable.notifyObservers(this); } context.restore(); } _evaluateClippingState(parentMeasure) { this._transform(); this._currentMeasure.transformToRef(this._transformMatrix, this._evaluatedMeasure); if (this.parent && this.parent.clipChildren) { parentMeasure.transformToRef(this.parent._transformMatrix, this._evaluatedParentMeasure); if (this._evaluatedMeasure.left > this._evaluatedParentMeasure.left + this._evaluatedParentMeasure.width) { this._isClipped = true; return; } if (this._evaluatedMeasure.left + this._evaluatedMeasure.width < this._evaluatedParentMeasure.left) { this._isClipped = true; return; } if (this._evaluatedMeasure.top > this._evaluatedParentMeasure.top + this._evaluatedParentMeasure.height) { this._isClipped = true; return; } if (this._evaluatedMeasure.top + this._evaluatedMeasure.height < this._evaluatedParentMeasure.top) { this._isClipped = true; return; } } this._isClipped = false; } /** @internal */ _measure() { if (this._width.isPixel) { this._currentMeasure.width = this._width.getValue(this._host); } else { this._currentMeasure.width *= this._width.getValue(this._host); } if (this._height.isPixel) { this._currentMeasure.height = this._height.getValue(this._host); } else { this._currentMeasure.height *= this._height.getValue(this._host); } if (this._fixedRatio !== 0) { if (this._fixedRatioMasterIsWidth) { this._currentMeasure.height = this._currentMeasure.width * this._fixedRatio; } else { this._currentMeasure.width = this._currentMeasure.height * this._fixedRatio; } } } /** * @internal */ _computeAlignment(parentMeasure, context) { const width = this._currentMeasure.width; const height = this._currentMeasure.height; const parentWidth = parentMeasure.width; const parentHeight = parentMeasure.height; let x = 0; let y = 0; switch (this.horizontalAlignment) { case _Control.HORIZONTAL_ALIGNMENT_LEFT: x = 0; break; case _Control.HORIZONTAL_ALIGNMENT_RIGHT: x = parentWidth - width; break; case _Control.HORIZONTAL_ALIGNMENT_CENTER: x = (parentWidth - width) / 2; break; } switch (this.verticalAlignment) { case _Control.VERTICAL_ALIGNMENT_TOP: y = 0; break; case _Control.VERTICAL_ALIGNMENT_BOTTOM: y = parentHeight - height; break; case _Control.VERTICAL_ALIGNMENT_CENTER: y = (parentHeight - height) / 2; break; } if (!this.descendantsOnlyPadding) { if (this._paddingLeft.isPixel) { this._currentMeasure.left += this._paddingLeft.getValue(this._host); this._currentMeasure.width -= this._paddingLeft.getValue(this._host); } else { this._currentMeasure.left += parentWidth * this._paddingLeft.getValue(this._host); this._currentMeasure.width -= parentWidth * this._paddingLeft.getValue(this._host); } if (this._paddingRight.isPixel) { this._currentMeasure.width -= this._paddingRight.getValue(this._host); } else { this._currentMeasure.width -= parentWidth * this._paddingRight.getValue(this._host); } if (this._paddingTop.isPixel) { this._currentMeasure.top += this._paddingTop.getValue(this._host); this._currentMeasure.height -= this._paddingTop.getValue(this._host); } else { this._currentMeasure.top += parentHeight * this._paddingTop.getValue(this._host); this._currentMeasure.height -= parentHeight * this._paddingTop.getValue(this._host); } if (this._paddingBottom.isPixel) { this._currentMeasure.height -= this._paddingBottom.getValue(this._host); } else { this._currentMeasure.height -= parentHeight * this._paddingBottom.getValue(this._host); } } if (this._left.isPixel) { this._currentMeasure.left += this._left.getValue(this._host); } else { this._currentMeasure.left += parentWidth * this._left.getValue(this._host); } if (this._top.isPixel) { this._currentMeasure.top += this._top.getValue(this._host); } else { this._currentMeasure.top += parentHeight * this._top.getValue(this._host); } this._currentMeasure.left += x; this._currentMeasure.top += y; } /** * @internal */ _preMeasure(parentMeasure, context) { } /** * @internal */ _postMeasure(parentMeasure, context) { } /** * @internal */ _additionalProcessing(parentMeasure, context) { } /** * @internal */ _clipForChildren(context) { } _clip(context, invalidatedRectangle) { context.beginPath(); _Control._ClipMeasure.copyFrom(this._currentMeasure); if (invalidatedRectangle) { invalidatedRectangle.transformToRef(this._invertTransformMatrix, this._tmpMeasureA); const intersection = new Measure(0, 0, 0, 0); intersection.left = Math.max(this._tmpMeasureA.left, this._currentMeasure.left); intersection.top = Math.max(this._tmpMeasureA.top, this._currentMeasure.top); intersection.width = Math.min(this._tmpMeasureA.left + this._tmpMeasureA.width, this._currentMeasure.left + this._currentMeasure.width) - intersection.left; intersection.height = Math.min(this._tmpMeasureA.top + this._tmpMeasureA.height, this._currentMeasure.top + this._currentMeasure.height) - intersection.top; _Control._ClipMeasure.copyFrom(intersection); } if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) { const shadowOffsetX = this.shadowOffsetX; const shadowOffsetY = this.shadowOffsetY; const shadowBlur = this.shadowBlur; const leftShadowOffset = Math.min(Math.min(shadowOffsetX, 0) - shadowBlur * 2, 0); const rightShadowOffset = Math.max(Math.max(shadowOffsetX, 0) + shadowBlur * 2, 0); const topShadowOffset = Math.min(Math.min(shadowOffsetY, 0) - shadowBlur * 2, 0); const bottomShadowOffset = Math.max(Math.max(shadowOffsetY, 0) + shadowBlur * 2, 0); context.rect(_Control._ClipMeasure.left + leftShadowOffset, _Control._ClipMeasure.top + topShadowOffset, _Control._ClipMeasure.width + rightShadowOffset - leftShadowOffset, _Control._ClipMeasure.height + bottomShadowOffset - topShadowOffset); } else { context.rect(_Control._ClipMeasure.left, _Control._ClipMeasure.top, _Control._ClipMeasure.width, _Control._ClipMeasure.height); } context.clip(); } /** * @internal */ _render(context, invalidatedRectangle) { if (!this.isVisible || this.notRenderable || this._isClipped) { this._isDirty = false; return false; } this.host._numRenderCalls++; context.save(); this._applyStates(context); this._transform(context); if (this.clipContent) { this._clip(context, invalidatedRectangle); } if (this.onBeforeDrawObservable.hasObservers()) { this.onBeforeDrawObservable.notifyObservers(this); } if (this.useBitmapCache && !this._wasDirty && this._cacheData) { context.putImageData(this._cacheData, this._currentMeasure.left, this._currentMeasure.top); } else { this._draw(context, invalidatedRectangle); } if (this.useBitmapCache && this._wasDirty) { this._cacheData = context.getImageData(this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height); } this._renderHighlight(context); if (this.onAfterDrawObservable.hasObservers()) { this.onAfterDrawObservable.notifyObservers(this); } context.restore(); return true; } /** * @internal */ _draw(context, invalidatedRectangle) { } /** * Tests if a given coordinates belong to the current control * @param x defines x coordinate to test * @param y defines y coordinate to test * @returns true if the coordinates are inside the control */ contains(x, y) { this._invertTransformMatrix.transformCoordinates(x, y, this._transformedPosition); x = this._transformedPosition.x; y = this._transformedPosition.y; if (x < this._currentMeasure.left) { return false; } if (x > this._currentMeasure.left + this._currentMeasure.width) { return false; } if (y < this._currentMeasure.top) { return false; } if (y > this._currentMeasure.top + this._currentMeasure.height) { return false; } if (this.isPointerBlocker) { this._host._shouldBlockPointer = true; } return true; } /** * @internal */ _processPicking(x, y, pi, type, pointerId, buttonIndex, deltaX, deltaY) { if (!this._isEnabled) { return false; } if (!this.isHitTestVisible || !this.isVisible || this._doNotRender) { return false; } if (!this.contains(x, y)) { return false; } this._processObservables(type, x, y, pi, pointerId, buttonIndex, deltaX, deltaY); return true; } /** * @internal */ _onPointerMove(target, coordinates, pointerId, pi) { const canNotify = this.onPointerMoveObservable.notifyObservers(coordinates, -1, target, this, pi); if (canNotify && this.parent != null && !this.isPointerBlocker) { this.parent._onPointerMove(target, coordinates, pointerId, pi); } } /** * @internal */ _onPointerEnter(target, pi) { if (!this._isEnabled) { return false; } if (this._enterCount > 0) { return false; } if (this._enterCount === -1) { this._enterCount = 0; } this._enterCount++; const canNotify = this.onPointerEnterObservable.notifyObservers(this, -1, target, this, pi); if (canNotify && this.parent != null && !this.isPointerBlocker) { this.parent._onPointerEnter(target, pi); } return true; } /** * @internal */ _onPointerOut(target, pi, force = false) { if (!force && !this._isEnabled) { return; } this._enterCount = 0; let canNotify = true; if (!target.isAscendant(this)) { canNotify = this.onPointerOutObservable.notifyObservers(this, -1, target, this, pi); } if (canNotify && this.parent != null && !this.isPointerBlocker) { this.parent._onPointerOut(target, pi, force); } } /** * @internal */ _onPointerDown(target, coordinates, pointerId, buttonIndex, pi) { this._onPointerEnter(this, pi); if (this.tabIndex !== -1) { this.host.focusedControl = this; } if (this._downCount !== 0) { return false; } this._downCount++; this._downPointerIds[pointerId] = true; const canNotify = this.onPointerDownObservable.notifyObservers(new Vector2WithInfo(coordinates, buttonIndex), -1, target, this, pi); if (canNotify && this.parent != null && !this.isPointerBlocker) { this.parent._onPointerDown(target, coordinates, pointerId, buttonIndex, pi); } if (pi && this.uniqueId !== this._host.rootContainer.uniqueId) { this._host._capturedPointerIds.add(pi.event.pointerId); } return true; } /** * @internal */ _onPointerUp(target, coordinates, pointerId, buttonIndex, notifyClick, pi) { if (!this._isEnabled) { return; } this._downCount = 0; delete this._downPointerIds[pointerId]; let canNotifyClick = notifyClick; if (notifyClick && (this._enterCount > 0 || this._enterCount === -1)) { if (!this._host.usePointerTapForClickEvent) { canNotifyClick = this.onPointerClickObservable.notifyObservers(new Vector2WithInfo(coordinates, buttonIndex), -1, target, this, pi); } } const canNotify = this.onPointerUpObservable.notifyObservers(new Vector2WithInfo(coordinates, buttonIndex), -1, target, this, pi); if (canNotify && this.parent != null && !this.isPointerBlocker) { this.parent._onPointerUp(target, coordinates, pointerId, buttonIndex, canNotifyClick, pi); } if (pi && this.uniqueId !== this._host.rootContainer.uniqueId) { this._host._capturedPointerIds.delete(pi.event.pointerId); } if (this._host.usePointerTapForClickEvent && this.isPointerBlocker) { this._host._shouldBlockPointer = false; } } _onPointerPick(target, coordinates, pointerId, buttonIndex, notifyClick, pi) { if (!this._host.usePointerTapForClickEvent) { return false; } let canNotifyClick = notifyClick; if (notifyClick && (this._enterCount > 0 || this._enterCount === -1)) { canNotifyClick = this.onPointerClickObservable.notifyObservers(new Vector2WithInfo(coordinates, buttonIndex), -1, target, this, pi); } const canNotify = this.onPointerUpObservable.notifyObservers(new Vector2WithInfo(coordinates, buttonIndex), -1, target, this, pi); if (canNotify && this.parent != null && !this.isPointerBlocker) { this.parent._onPointerPick(target, coordinates, pointerId, buttonIndex, canNotifyClick, pi); } if (this._host.usePointerTapForClickEvent && this.isPointerBlocker) { this._host._shouldBlockPointer = true; } return true; } /** * @internal */ _forcePointerUp(pointerId = null) { if (pointerId !== null) { this._onPointerUp(this, Vector2.Zero(), pointerId, 0, true); } else { for (const key in this._downPointerIds) { this._onPointerUp(this, Vector2.Zero(), +key, 0, true); } } } /** * @internal */ _onWheelScroll(deltaX, deltaY) { if (!this._isEnabled) { return; } const canNotify = this.onWheelObservable.notifyObservers(new Vector2(deltaX, deltaY)); if (canNotify && this.parent != null) { this.parent._onWheelScroll(deltaX, deltaY); } } /** @internal */ _onCanvasBlur() { } /** * @internal */ _processObservables(type, x, y, pi, pointerId, buttonIndex, deltaX, deltaY) { if (!this._isEnabled) { return false; } this._dummyVector2.copyFromFloats(x, y); if (type === PointerEventTypes.POINTERMOVE) { this._onPointerMove(this, this._dummyVector2, pointerId, pi); const previousControlOver = this._host._lastControlOver[pointerId]; if (previousControlOver && previousControlOver !== this) { previousControlOver._onPointerOut(this, pi); } if (previousControlOver !== this) { this._onPointerEnter(this, pi); } this._host._lastControlOver[pointerId] = this; return true; } else if (type === PointerEventTypes.POINTERDOWN) { this._onPointerDown(this, this._dummyVector2, pointerId, buttonIndex, pi); this._host._registerLastControlDown(this, pointerId); this._host._lastPickedControl = this; return true; } else if (type === PointerEventTypes.POINTERUP) { if (this._host._lastControlDown[pointerId]) { this._host._lastControlDown[pointerId]._onPointerUp(this, this._dummyVector2, pointerId, buttonIndex, true, pi); } if (!this._host.usePointerTapForClickEvent) { delete this._host._lastControlDown[pointerId]; } return true; } else if (type === PointerEventTypes.POINTERWHEEL) { if (this._host._lastControlOver[pointerId]) { this._host._lastControlOver[pointerId]._onWheelScroll(deltaX, deltaY); return true; } } else if (type === PointerEventTypes.POINTERTAP) { if (this._host._lastControlDown[pointerId]) { this._host._lastControlDown[pointerId]._onPointerPick(this, this._dummyVector2, pointerId, buttonIndex, true, pi); } delete this._host._lastControlDown[pointerId]; return true; } return false; } _getStyleProperty(propName, defaultValue) { const prop = (this._style && this._style[propName]) ?? this[propName]; if (!prop && this.parent) { return this.parent._getStyleProperty(propName, defaultValue); } else if (!this.parent) { return defaultValue; } else { return prop; } } _prepareFont() { if (!this._font && !this._fontSet) { return; } this._font = this._getStyleProperty("fontStyle", "") + " " + this._getStyleProperty("fontWeight", "") + " " + this.fontSizeInPixels + "px " + this._getStyleProperty("fontFamily", "Arial"); this._fontOffset = _Control._GetFontOffset(this._font, this._host?.getScene()?.getEngine()); const descendants = this.getDescendants(); for (const child of descendants) { child._markAllAsDirty(); } } /** * A control has a dimension fully defined if that dimension doesn't depend on the parent's dimension. * As an example, a control that has dimensions in pixels is fully defined, while in percentage is not fully defined. * @param dim the dimension to check (width or height) * @returns if the dimension is fully defined */ isDimensionFullyDefined(dim) { return this.getDimension(dim).isPixel; } /** * Gets the dimension of the control along a specified axis * @param dim the dimension to retrieve (width or height) * @returns the dimension value along the specified axis */ getDimension(dim) { if (dim === "width") { return this._width; } else { return this._height; } } /** * Clones a control and its descendants * @param host the texture where the control will be instantiated. Can be empty, in which case the control will be created on the same texture * @returns the cloned control */ clone(host) { const serialization = {}; this.serialize(serialization, true); const controlType = Tools.Instantiate("BABYLON.GUI." + serialization.className); const cloned = new controlType(); cloned.parse(serialization, host); return cloned; } /** * Parses a serialized object into this control * @param serializedObject the object with the serialized properties * @param host the texture where the control will be instantiated. Can be empty, in which case the control will be created on the same texture * @param urlRewriter defines an url rewriter to update urls before sending them to the controls * @returns this control */ parse(serializedObject, host, urlRewriter) { this._urlRewriter = urlRewriter; SerializationHelper.Parse(() => this, serializedObject, null); this.name = serializedObject.name; this._parseFromContent(serializedObject, host ?? this._host); return this; } /** * Serializes the current control * @param serializationObject defined the JSON serialized object * @param force if the control should be serialized even if the isSerializable flag is set to false (default false) * @param allowCanvas defines if the control is allowed to use a Canvas2D object to serialize (true by default) */ serialize(serializationObject, force = false, allowCanvas = true) { if (!this.isSerializable && !force) { return; } let idealWidth = 0; let idealHeight = 0; if (this.host) { idealHeight = this.host.idealHeight; idealWidth = this.host.idealWidth; this.host.idealWidth = 0; this.host.idealHeight = 0; } SerializationHelper.Serialize(this, serializationObject); serializationObject.name = this.name; serializationObject.className = this.getClassName(); if (allowCanvas) { this._prepareFont(); } if (this._fontFamily) { serializationObject.fontFamily = this._fontFamily; } if (this.fontSize) { serializationObject.fontSize = this.fontSize; } if (this.fontWeight) { serializationObject.fontWeight = this.fontWeight; } if (this.fontStyle) { serializationObject.fontStyle = this.fontStyle; } if (this._gradient) { serializationObject.gradient = {}; this._gradient.serialize(serializationObject.gradient); } SerializationHelper.AppendSerializedAnimations(this, serializationObject); if (this.host) { this.host.idealWidth = idealWidth; this.host.idealHeight = idealHeight; } } /** * @internal */ _parseFromContent(serializedObject, host, urlRewriter) { if (serializedObject.fontFamily) { this.fontFamily = serializedObject.fontFamily; } if (serializedObject.fontSize) { this.fontSize = serializedObject.fontSize; } if (serializedObject.fontWeight) { this.fontWeight = serializedObject.fontWeight; } if (serializedObject.fontStyle) { this.fontStyle = serializedObject.fontStyle; } if (serializedObject.gradient) { const className2 = Tools.Instantiate("BABYLON.GUI." + serializedObject.gradient.className); this._gradient = new className2(); this._gradient?.parse(serializedObject.gradient); } if (serializedObject.animations) { this.animations = []; for (let animationIndex = 0; animationIndex < serializedObject.animations.length; animationIndex++) { const parsedAnimation = serializedObject.animations[animationIndex]; const internalClass = GetClass("BABYLON.Animation"); if (internalClass) { this.animations.push(internalClass.Parse(parsedAnimation)); } } if (serializedObject.autoAnimate && this._host && this._host.getScene()) { this._host.getScene().beginAnimation(this, serializedObject.autoAnimateFrom, serializedObject.autoAnimateTo, serializedObject.autoAnimateLoop, serializedObject.autoAnimateSpeed || 1); } } this.fixedRatioMasterIsWidth = serializedObject.fixedRatioMasterIsWidth ?? this.fixedRatioMasterIsWidth; } /** Releases associated resources */ dispose() { this.onDirtyObservable.clear(); this.onBeforeDrawObservable.clear(); this.onAfterDrawObservable.clear(); this.onPointerDownObservable.clear(); this.onPointerEnterObservable.clear(); this.onPointerMoveObservable.clear(); this.onPointerOutObservable.clear(); this.onPointerUpObservable.clear(); this.onPointerClickObservable.clear(); this.onWheelObservable.clear(); this.onBlurObservable.clear(); this.onFocusObservable.clear(); this.onKeyboardEventProcessedObservable.clear(); if (this._styleObserver && this._style) { this._style.onChangedObservable.remove(this._styleObserver); this._styleObserver = null; } if (this.parent) { this.parent.removeControl(this); this.parent = null; } if (this._host) { const index = this._host._linkedControls.indexOf(this); if (index > -1) { this.linkWithMesh(null); } } this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); } /** HORIZONTAL_ALIGNMENT_LEFT */ static get HORIZONTAL_ALIGNMENT_LEFT() { return _Control._HORIZONTAL_ALIGNMENT_LEFT; } /** HORIZONTAL_ALIGNMENT_RIGHT */ static get HORIZONTAL_ALIGNMENT_RIGHT() { return _Control._HORIZONTAL_ALIGNMENT_RIGHT; } /** HORIZONTAL_ALIGNMENT_CENTER */ static get HORIZONTAL_ALIGNMENT_CENTER() { return _Control._HORIZONTAL_ALIGNMENT_CENTER; } /** VERTICAL_ALIGNMENT_TOP */ static get VERTICAL_ALIGNMENT_TOP() { return _Control._VERTICAL_ALIGNMENT_TOP; } /** VERTICAL_ALIGNMENT_BOTTOM */ static get VERTICAL_ALIGNMENT_BOTTOM() { return _Control._VERTICAL_ALIGNMENT_BOTTOM; } /** VERTICAL_ALIGNMENT_CENTER */ static get VERTICAL_ALIGNMENT_CENTER() { return _Control._VERTICAL_ALIGNMENT_CENTER; } /** * @internal */ static _GetFontOffset(font, engineToUse) { if (_Control._FontHeightSizes[font]) { return _Control._FontHeightSizes[font]; } const engine = engineToUse || EngineStore.LastCreatedEngine; if (!engine) { throw new Error("Invalid engine. Unable to create a canvas."); } const result = engine.getFontOffset(font); _Control._FontHeightSizes[font] = result; return result; } /** * Creates a Control from parsed data * @param serializedObject defines parsed data * @param host defines the hosting AdvancedDynamicTexture * @param urlRewriter defines an url rewriter to update urls before sending them to the controls * @returns a new Control */ static Parse(serializedObject, host, urlRewriter) { const controlType = Tools.Instantiate("BABYLON.GUI." + serializedObject.className); const control = SerializationHelper.Parse(() => { const newControl = new controlType(); newControl._urlRewriter = urlRewriter; return newControl; }, serializedObject, null); control.name = serializedObject.name; control._parseFromContent(serializedObject, host, urlRewriter); return control; } /** * @internal */ static drawEllipse(x, y, width, height, arc, context) { context.translate(x, y); context.scale(width, height); context.beginPath(); context.arc(0, 0, 1, 0, 2 * Math.PI * arc, arc < 0); if (arc >= 1) { context.closePath(); } context.scale(1 / width, 1 / height); context.translate(-x, -y); } /** * Returns true if the control is ready to be used * @returns */ isReady() { return true; } }; Control.AllowAlphaInheritance = false; Control._ClipMeasure = new Measure(0, 0, 0, 0); Control._HORIZONTAL_ALIGNMENT_LEFT = 0; Control._HORIZONTAL_ALIGNMENT_RIGHT = 1; Control._HORIZONTAL_ALIGNMENT_CENTER = 2; Control._VERTICAL_ALIGNMENT_TOP = 0; Control._VERTICAL_ALIGNMENT_BOTTOM = 1; Control._VERTICAL_ALIGNMENT_CENTER = 2; Control._FontHeightSizes = {}; Control.AddHeader = () => { }; __decorate([ serialize() ], Control.prototype, "metadata", void 0); __decorate([ serialize() ], Control.prototype, "isHitTestVisible", void 0); __decorate([ serialize() ], Control.prototype, "isPointerBlocker", void 0); __decorate([ serialize() ], Control.prototype, "isFocusInvisible", void 0); __decorate([ serialize() ], Control.prototype, "clipChildren", null); __decorate([ serialize() ], Control.prototype, "clipContent", null); __decorate([ serialize() ], Control.prototype, "useBitmapCache", void 0); __decorate([ serialize() ], Control.prototype, "shadowOffsetX", null); __decorate([ serialize() ], Control.prototype, "shadowOffsetY", null); __decorate([ serialize() ], Control.prototype, "shadowBlur", null); __decorate([ serialize() ], Control.prototype, "shadowColor", null); __decorate([ serialize() ], Control.prototype, "hoverCursor", void 0); __decorate([ serialize() ], Control.prototype, "fontOffset", null); __decorate([ serialize() ], Control.prototype, "alpha", null); __decorate([ serialize() ], Control.prototype, "isSerializable", void 0); __decorate([ serialize() ], Control.prototype, "scaleX", null); __decorate([ serialize() ], Control.prototype, "scaleY", null); __decorate([ serialize() ], Control.prototype, "rotation", null); __decorate([ serialize() ], Control.prototype, "transformCenterY", null); __decorate([ serialize() ], Control.prototype, "transformCenterX", null); __decorate([ serialize() ], Control.prototype, "horizontalAlignment", null); __decorate([ serialize() ], Control.prototype, "verticalAlignment", null); __decorate([ serialize() ], Control.prototype, "fixedRatio", null); __decorate([ serialize() ], Control.prototype, "fixedRatioMasterIsWidth", null); __decorate([ serialize() ], Control.prototype, "width", null); __decorate([ serialize() ], Control.prototype, "height", null); __decorate([ serialize() ], Control.prototype, "style", null); __decorate([ serialize() ], Control.prototype, "color", null); __decorate([ serialize() ], Control.prototype, "gradient", null); __decorate([ serialize() ], Control.prototype, "zIndex", null); __decorate([ serialize() ], Control.prototype, "notRenderable", null); __decorate([ serialize() ], Control.prototype, "isVisible", null); __decorate([ serialize() ], Control.prototype, "descendantsOnlyPadding", null); __decorate([ serialize() ], Control.prototype, "paddingLeft", null); __decorate([ serialize() ], Control.prototype, "paddingRight", null); __decorate([ serialize() ], Control.prototype, "paddingTop", null); __decorate([ serialize() ], Control.prototype, "paddingBottom", null); __decorate([ serialize() ], Control.prototype, "left", null); __decorate([ serialize() ], Control.prototype, "top", null); __decorate([ serialize() ], Control.prototype, "linkOffsetX", null); __decorate([ serialize() ], Control.prototype, "linkOffsetY", null); __decorate([ serialize() ], Control.prototype, "isEnabled", null); __decorate([ serialize() ], Control.prototype, "disabledColor", null); __decorate([ serialize() ], Control.prototype, "disabledColorItem", null); __decorate([ serialize() ], Control.prototype, "overlapGroup", void 0); __decorate([ serialize() ], Control.prototype, "overlapDeltaMultiplier", void 0); RegisterClass("BABYLON.GUI.Control", Control); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/gui/2D/controls/container.js init_tslib_es6(); init_logger(); init_typeStore(); init_decorators(); init_texture(); init_observable(); init_tools(); var Container = class extends Control { static { __name(this, "Container"); } /** Gets or sets boolean indicating if children should be rendered to an intermediate texture rather than directly to host, useful for alpha blending */ get renderToIntermediateTexture() { return this._renderToIntermediateTexture; } set renderToIntermediateTexture(value) { if (this._renderToIntermediateTexture === value) { return; } this._renderToIntermediateTexture = value; this._markAsDirty(); } /** Gets or sets a boolean indicating if the container should try to adapt to its children height */ get adaptHeightToChildren() { return this._adaptHeightToChildren; } set adaptHeightToChildren(value) { if (this._adaptHeightToChildren === value) { return; } this._adaptHeightToChildren = value; if (value) { this.height = "100%"; } this._markAsDirty(); } /** Gets or sets a boolean indicating if the container should try to adapt to its children width */ get adaptWidthToChildren() { return this._adaptWidthToChildren; } set adaptWidthToChildren(value) { if (this._adaptWidthToChildren === value) { return; } this._adaptWidthToChildren = value; if (value) { this.width = "100%"; } this._markAsDirty(); } /** Gets or sets background color */ get background() { return this._background; } set background(value) { if (this._background === value) { return; } this._background = value; this._markAsDirty(); } /** Gets or sets background gradient color. Takes precedence over background */ get backgroundGradient() { return this._backgroundGradient; } set backgroundGradient(value) { if (this._backgroundGradient === value) { return; } this._backgroundGradient = value; this._markAsDirty(); } /** Gets the list of children */ get children() { return this._children; } get isReadOnly() { return this._isReadOnly; } set isReadOnly(value) { this._isReadOnly = value; for (const child of this._children) { child.isReadOnly = value; } } /** * Creates a new Container * @param name defines the name of the container */ constructor(name260) { super(name260); this.name = name260; this._children = new Array(); this._measureForChildren = Measure.Empty(); this._background = ""; this._backgroundGradient = null; this._adaptWidthToChildren = false; this._adaptHeightToChildren = false; this._renderToIntermediateTexture = false; this._intermediateTexture = null; this.delegatePickingToChildren = false; this.logLayoutCycleErrors = false; this.maxLayoutCycle = 3; this.onControlAddedObservable = new Observable(); this.onControlRemovedObservable = new Observable(); this._inverseTransformMatrix = Matrix2D.Identity(); this._inverseMeasure = new Measure(0, 0, 0, 0); } _getTypeName() { return "Container"; } _flagDescendantsAsMatrixDirty() { for (const child of this.children) { child._isClipped = false; child._markMatrixAsDirty(); } } /** * Gets a child using its name * @param name defines the child name to look for * @returns the child control if found */ getChildByName(name260) { for (const child of this.children) { if (child.name === name260) { return child; } } return null; } /** * Gets a child using its type and its name * @param name defines the child name to look for * @param type defines the child type to look for * @returns the child control if found */ getChildByType(name260, type) { for (const child of this.children) { if (child.typeName === type) { return child; } } return null; } /** * Search for a specific control in children * @param control defines the control to look for * @returns true if the control is in child list */ containsControl(control) { return this.children.indexOf(control) !== -1; } /** * Adds a new control to the current container * @param control defines the control to add * @returns the current container */ addControl(control) { if (!control) { return this; } const index = this._children.indexOf(control); if (index !== -1) { return this; } control._link(this._host); control._markAllAsDirty(); this._reOrderControl(control); this._markAsDirty(); this.onControlAddedObservable.notifyObservers(control); return this; } /** * Removes all controls from the current container * @returns the current container */ clearControls() { const children = this.children.slice(); for (const child of children) { this.removeControl(child); } return this; } /** * Removes a control from the current container * @param control defines the control to remove * @returns the current container */ removeControl(control) { const index = this._children.indexOf(control); if (index !== -1) { this._children.splice(index, 1); control.parent = null; } control.linkWithMesh(null); if (this._host) { this._host._cleanControlAfterRemoval(control); } this._markAsDirty(); this.onControlRemovedObservable.notifyObservers(control); return this; } /** * @internal */ _reOrderControl(control) { const linkedMesh = control.linkedMesh; this.removeControl(control); let wasAdded = false; for (let index = 0; index < this._children.length; index++) { if (this._children[index].zIndex > control.zIndex) { this._children.splice(index, 0, control); wasAdded = true; break; } } if (!wasAdded) { this._children.push(control); } control.parent = this; if (linkedMesh) { control.linkWithMesh(linkedMesh); } this._markAsDirty(); } /** * @internal */ _offsetLeft(offset) { super._offsetLeft(offset); for (const child of this._children) { child._offsetLeft(offset); } } /** * @internal */ _offsetTop(offset) { super._offsetTop(offset); for (const child of this._children) { child._offsetTop(offset); } } /** @internal */ _markAllAsDirty() { super._markAllAsDirty(); for (let index = 0; index < this._children.length; index++) { this._children[index]._markAllAsDirty(); } } _getBackgroundColor(context) { return this._backgroundGradient ? this._backgroundGradient.getCanvasGradient(context) : this._background; } /** * @internal */ _localDraw(context) { if (this._background || this._backgroundGradient) { context.save(); if (this.shadowBlur || this.shadowOffsetX || this.shadowOffsetY) { context.shadowColor = this.shadowColor; context.shadowBlur = this.shadowBlur; context.shadowOffsetX = this.shadowOffsetX; context.shadowOffsetY = this.shadowOffsetY; } context.fillStyle = this._getBackgroundColor(context); context.fillRect(this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height); context.restore(); } } /** * @internal */ _link(host) { super._link(host); for (const child of this._children) { child._link(host); } } /** @internal */ _beforeLayout() { } /** * @internal */ _processMeasures(parentMeasure, context) { if (this._isDirty || !this._cachedParentMeasure.isEqualsTo(parentMeasure)) { super._processMeasures(parentMeasure, context); this._evaluateClippingState(parentMeasure); if (this._renderToIntermediateTexture) { if (this._intermediateTexture && this._host.getScene() != this._intermediateTexture.getScene()) { this._intermediateTexture.dispose(); this._intermediateTexture = null; } if (!this._intermediateTexture) { this._intermediateTexture = new DynamicTexture("", { width: this._currentMeasure.width, height: this._currentMeasure.height }, this._host.getScene(), false, Texture.NEAREST_SAMPLINGMODE, Constants.TEXTUREFORMAT_RGBA, false); this._intermediateTexture.hasAlpha = true; } else { this._intermediateTexture.scaleTo(this._currentMeasure.width, this._currentMeasure.height); } } } } /** * @internal */ _layout(parentMeasure, context) { if (!this.isDirty && (!this.isVisible || this.notRenderable)) { return false; } this.host._numLayoutCalls++; if (this._isDirty) { this._currentMeasure.transformToRef(this._transformMatrix, this._prevCurrentMeasureTransformedIntoGlobalSpace); } let rebuildCount = 0; context.save(); this._applyStates(context); this._beforeLayout(); do { let computedWidth = -1; let computedHeight = -1; this._rebuildLayout = false; this._processMeasures(parentMeasure, context); if (!this._isClipped) { for (const child of this._children) { child._tempParentMeasure.copyFrom(this._measureForChildren); if (child._layout(this._measureForChildren, context)) { if (child.isVisible && !child.notRenderable) { if (this.adaptWidthToChildren && child._width.isPixel) { computedWidth = Math.max(computedWidth, child._currentMeasure.width + child._paddingLeftInPixels + child._paddingRightInPixels); } if (this.adaptHeightToChildren && child._height.isPixel) { computedHeight = Math.max(computedHeight, child._currentMeasure.height + child._paddingTopInPixels + child._paddingBottomInPixels); } } } } if (this.adaptWidthToChildren && computedWidth >= 0) { computedWidth += this.paddingLeftInPixels + this.paddingRightInPixels; const width = computedWidth + "px"; if (this.width !== width) { this.parent?._markAsDirty(); this.width = width; this._width.ignoreAdaptiveScaling = true; this._rebuildLayout = true; } } if (this.adaptHeightToChildren && computedHeight >= 0) { computedHeight += this.paddingTopInPixels + this.paddingBottomInPixels; const height = computedHeight + "px"; if (this.height !== height) { this.parent?._markAsDirty(); this.height = height; this._height.ignoreAdaptiveScaling = true; this._rebuildLayout = true; } } this._postMeasure(); } rebuildCount++; } while (this._rebuildLayout && rebuildCount < this.maxLayoutCycle); if (rebuildCount >= 3 && this.logLayoutCycleErrors) { Logger.Error(`Layout cycle detected in GUI (Container name=${this.name}, uniqueId=${this.uniqueId})`); } context.restore(); if (this._isDirty) { this.invalidateRect(); this._isDirty = false; } return true; } _postMeasure() { } /** * @internal */ _draw(context, invalidatedRectangle) { const renderToIntermediateTextureThisDraw = this._renderToIntermediateTexture && this._intermediateTexture; const contextToDrawTo = renderToIntermediateTextureThisDraw ? this._intermediateTexture.getContext() : context; if (renderToIntermediateTextureThisDraw) { contextToDrawTo.save(); contextToDrawTo.translate(-this._currentMeasure.left, -this._currentMeasure.top); if (invalidatedRectangle) { this._transformMatrix.invertToRef(this._inverseTransformMatrix); invalidatedRectangle.transformToRef(this._inverseTransformMatrix, this._inverseMeasure); contextToDrawTo.clearRect(this._inverseMeasure.left, this._inverseMeasure.top, this._inverseMeasure.width, this._inverseMeasure.height); } else { contextToDrawTo.clearRect(this._currentMeasure.left, this._currentMeasure.top, this._currentMeasure.width, this._currentMeasure.height); } } this._localDraw(contextToDrawTo); context.save(); if (this.clipChildren) { this._clipForChildren(contextToDrawTo); } for (const child of this._children) { if (invalidatedRectangle) { if (!child._intersectsRect(invalidatedRectangle)) { continue; } } child._render(contextToDrawTo, invalidatedRectangle); } if (renderToIntermediateTextureThisDraw) { contextToDrawTo.restore(); context.save(); context.globalAlpha = this.alpha; context.drawImage(contextToDrawTo.canvas, this._currentMeasure.left, this._currentMeasure.top); context.restore(); } context.restore(); } getDescendantsToRef(results, directDescendantsOnly = false, predicate) { if (!this.children) { return; } for (let index = 0; index < this.children.length; index++) { const item = this.children[index]; if (!predicate || predicate(item)) { results.push(item); } if (!directDescendantsOnly) { item.getDescendantsToRef(results, false, predicate); } } } /** * @internal */ _processPicking(x, y, pi, type, pointerId, buttonIndex, deltaX, deltaY) { if (!this._isEnabled || !this.isVisible || this.notRenderable) { return false; } const contains = super.contains(x, y); if (!contains && this.clipChildren) { return false; } if (this.delegatePickingToChildren) { let contains2 = false; for (let index = this._children.length - 1; index >= 0; index--) { const child = this._children[index]; if (child.isEnabled && child.isHitTestVisible && child.isVisible && !child.notRenderable && child.contains(x, y)) { contains2 = true; break; } } if (!contains2) { return false; } } for (let index = this._children.length - 1; index >= 0; index--) { const child = this._children[index]; if (child._processPicking(x, y, pi, type, pointerId, buttonIndex, deltaX, deltaY)) { if (child.hoverCursor) { this._host._changeCursor(child.hoverCursor); } return true; } } if (!contains) { return false; } if (!this.isHitTestVisible) { return false; } return this._processObservables(type, x, y, pi, pointerId, buttonIndex, deltaX, deltaY); } /** * @internal */ _additionalProcessing(parentMeasure, context) { super._additionalProcessing(parentMeasure, context); this._measureForChildren.copyFrom(this._currentMeasure); } _getAdaptDimTo(dim) { if (dim === "width") { return this.adaptWidthToChildren; } else { return this.adaptHeightToChildren; } } isDimensionFullyDefined(dim) { if (this._getAdaptDimTo(dim)) { for (const child of this.children) { if (!child.isDimensionFullyDefined(dim)) { return false; } } return true; } return super.isDimensionFullyDefined(dim); } /** * Serializes the current control * @param serializationObject defined the JSON serialized object * @param force force serialization even if isSerializable === false * @param allowCanvas defines if the control is allowed to use a Canvas2D object to serialize (true by default) */ serialize(serializationObject, force = false, allowCanvas = true) { super.serialize(serializationObject, force, allowCanvas); if (!this.isSerializable && !force) { return; } if (this.backgroundGradient) { serializationObject.backgroundGradient = {}; this.backgroundGradient.serialize(serializationObject.backgroundGradient); } if (!this.children.length) { return; } serializationObject.children = []; for (const child of this.children) { if (child.isSerializable || force) { const childSerializationObject = {}; child.serialize(childSerializationObject, force, allowCanvas); serializationObject.children.push(childSerializationObject); } } } /** Releases associated resources */ dispose() { super.dispose(); for (let index = this.children.length - 1; index >= 0; index--) { this.children[index].dispose(); } this._intermediateTexture?.dispose(); } /** * @internal */ _parseFromContent(serializedObject, host, urlRewriter) { super._parseFromContent(serializedObject, host, urlRewriter); this._link(host); if (serializedObject.backgroundGradient) { const className2 = Tools.Instantiate("BABYLON.GUI." + serializedObject.backgroundGradient.className); this._backgroundGradient = new className2(); this._backgroundGradient?.parse(serializedObject.backgroundGradient); } if (!serializedObject.children) { return; } for (const childData of serializedObject.children) { this.addControl(Control.Parse(childData, host, urlRewriter)); } } isReady() { for (const child of this.children) { if (!child.isReady()) { return false; } } return true; } }; __decorate([ serialize() ], Container.prototype, "delegatePickingToChildren", void 0); __decorate([ serialize() ], Container.prototype, "renderToIntermediateTexture", null); __decorate([ serialize() ], Container.prototype, "maxLayoutCycle", void 0); __decorate([ serialize() ], Container.prototype, "adaptHeightToChildren", null); __decorate([ serialize() ], Container.prototype, "adaptWidthToChildren", null); __decorate([ serialize() ], Container.prototype, "background", null); __decorate([ serialize() ], Container.prototype, "backgroundGradient", null); RegisterClass("BABYLON.GUI.Container", Container); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/gui/2D/style.js init_observable(); var Style = class { static { __name(this, "Style"); } /** * Creates a new style object * @param host defines the AdvancedDynamicTexture which hosts this style */ constructor(host) { this._fontFamily = "Arial"; this._fontStyle = ""; this._fontWeight = ""; this._fontSize = new ValueAndUnit(18, ValueAndUnit.UNITMODE_PIXEL, false); this.onChangedObservable = new Observable(); this._host = host; } /** * Gets or sets the font size */ get fontSize() { return this._fontSize.toString(this._host); } set fontSize(value) { if (this._fontSize.toString(this._host) === value) { return; } if (this._fontSize.fromString(value)) { this.onChangedObservable.notifyObservers(this); } } /** * Gets or sets the font family */ get fontFamily() { return this._fontFamily; } set fontFamily(value) { if (this._fontFamily === value) { return; } this._fontFamily = value; this.onChangedObservable.notifyObservers(this); } /** * Gets or sets the font style */ get fontStyle() { return this._fontStyle; } set fontStyle(value) { if (this._fontStyle === value) { return; } this._fontStyle = value; this.onChangedObservable.notifyObservers(this); } /** Gets or sets font weight */ get fontWeight() { return this._fontWeight; } set fontWeight(value) { if (this._fontWeight === value) { return; } this._fontWeight = value; this.onChangedObservable.notifyObservers(this); } /** Dispose all associated resources */ dispose() { this.onChangedObservable.clear(); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/gui/2D/advancedDynamicTexture.js init_observable(); init_math_vector(); init_tools(); init_pointerEvents(); init_keyboardEvents(); init_texture(); init_math_viewport(); init_math_color(); init_webRequest(); init_guid(); init_typeStore(); init_stringTools(); var AdvancedDynamicTexture = class _AdvancedDynamicTexture extends DynamicTexture { static { __name(this, "AdvancedDynamicTexture"); } /** Gets the number of layout calls made the last time the ADT has been rendered */ get numLayoutCalls() { return this._numLayoutCalls; } /** Gets the number of render calls made the last time the ADT has been rendered */ get numRenderCalls() { return this._numRenderCalls; } /** * If set to true, the renderScale will be adjusted automatically to the engine's hardware scaling * If this is set to true, manually setting the renderScale will be ignored * This is useful when the engine's hardware scaling is set to a value other than 1 */ get adjustToEngineHardwareScalingLevel() { return this._adjustToEngineHardwareScalingLevel; } set adjustToEngineHardwareScalingLevel(value) { if (this._adjustToEngineHardwareScalingLevel === value) { return; } this._adjustToEngineHardwareScalingLevel = value; this._onResize(); } /** * Gets or sets a number used to scale rendering size (2 means that the texture will be twice bigger). * Useful when you want more antialiasing */ get renderScale() { return this._renderScale; } set renderScale(value) { if (value === this._renderScale) { return; } this._renderScale = value; this._onResize(); } /** Gets or sets the background color */ get background() { return this._background; } set background(value) { if (this._background === value) { return; } this._background = value; this.markAsDirty(); } /** * Gets or sets the ideal width used to design controls. * The GUI will then rescale everything accordingly * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#adaptive-scaling */ get idealWidth() { return this._idealWidth; } set idealWidth(value) { if (this._idealWidth === value) { return; } this._idealWidth = value; this.markAsDirty(); this._rootContainer._markAllAsDirty(); } /** * Gets or sets the ideal height used to design controls. * The GUI will then rescale everything accordingly * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#adaptive-scaling */ get idealHeight() { return this._idealHeight; } set idealHeight(value) { if (this._idealHeight === value) { return; } this._idealHeight = value; this.markAsDirty(); this._rootContainer._markAllAsDirty(); } /** * Gets or sets a boolean indicating if the smallest ideal value must be used if idealWidth and idealHeight are both set * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#adaptive-scaling */ get useSmallestIdeal() { return this._useSmallestIdeal; } set useSmallestIdeal(value) { if (this._useSmallestIdeal === value) { return; } this._useSmallestIdeal = value; this.markAsDirty(); this._rootContainer._markAllAsDirty(); } /** * Gets or sets a boolean indicating if adaptive scaling must be used * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#adaptive-scaling */ get renderAtIdealSize() { return this._renderAtIdealSize; } set renderAtIdealSize(value) { if (this._renderAtIdealSize === value) { return; } this._renderAtIdealSize = value; this._onResize(); } /** * Gets the ratio used when in "ideal mode" * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#adaptive-scaling * */ get idealRatio() { let rwidth = 0; let rheight = 0; if (this._idealWidth) { rwidth = this.getSize().width / this._idealWidth; } if (this._idealHeight) { rheight = this.getSize().height / this._idealHeight; } if (this._useSmallestIdeal && this._idealWidth && this._idealHeight) { return window.innerWidth < window.innerHeight ? rwidth : rheight; } if (this._idealWidth) { return rwidth; } if (this._idealHeight) { return rheight; } return 1; } /** * Gets the underlying layer used to render the texture when in fullscreen mode */ get layer() { return this._layerToDispose; } /** * Gets the root container control */ get rootContainer() { return this._rootContainer; } /** * Returns an array containing the root container. * This is mostly used to let the Inspector introspects the ADT * @returns an array containing the rootContainer */ getChildren() { return [this._rootContainer]; } /** * Will return all controls that are inside this texture * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored * @returns all child controls */ getDescendants(directDescendantsOnly, predicate) { return this._rootContainer.getDescendants(directDescendantsOnly, predicate); } /** * Will return all controls with the given type name * @param typeName defines the type name to search for * @returns an array of all controls found */ getControlsByType(typeName) { return this._rootContainer.getDescendants(false, (control) => control.typeName === typeName); } /** * Will return the first control with the given name * @param name defines the name to search for * @returns the first control found or null */ getControlByName(name260) { return this._getControlByKey("name", name260); } _getControlByKey(key, value) { return this._rootContainer.getDescendants().find((control) => control[key] === value) || null; } /** * Gets or sets the current focused control */ get focusedControl() { return this._focusedControl; } set focusedControl(control) { if (this._focusedControl == control) { return; } if (this._focusedControl) { this._focusedControl.onBlur(); } if (control) { control.onFocus(); } this._focusedControl = control; } /** * Gets or sets a boolean indicating if the texture must be rendered in background or foreground when in fullscreen mode */ get isForeground() { if (!this.layer) { return true; } return !this.layer.isBackground; } set isForeground(value) { if (!this.layer) { return; } if (this.layer.isBackground === !value) { return; } this.layer.isBackground = !value; } /** * Gets or set information about clipboardData */ get clipboardData() { return this._clipboardData; } set clipboardData(value) { this._clipboardData = value; } /** @internal */ constructor(name260, widthOrOptions, _height = 0, scene, generateMipMaps = false, samplingMode = Texture.NEAREST_SAMPLINGMODE, invertY = true) { widthOrOptions = widthOrOptions ?? 0; const width = typeof widthOrOptions === "object" && widthOrOptions !== void 0 ? widthOrOptions.width ?? 0 : widthOrOptions ?? 0; const height = typeof widthOrOptions === "object" && widthOrOptions !== void 0 ? widthOrOptions.height ?? 0 : _height; super(name260, { width, height }, typeof widthOrOptions === "object" && widthOrOptions !== void 0 ? widthOrOptions : scene, generateMipMaps, samplingMode, Constants.TEXTUREFORMAT_RGBA, invertY); this.useStandalone = false; this.onGuiReadyObservable = new Observable(); this._isDirty = false; this._rootContainer = new Container("root"); this._lastControlOver = {}; this._lastControlDown = {}; this._capturingControl = {}; this._linkedControls = new Array(); this._isFullscreen = false; this._fullscreenViewport = new Viewport(0, 0, 1, 1); this._idealWidth = 0; this._idealHeight = 0; this._useSmallestIdeal = false; this._renderAtIdealSize = false; this._blockNextFocusCheck = false; this._renderScale = 1; this._cursorChanged = false; this._defaultMousePointerId = 0; this._rootChildrenHaveChanged = false; this._adjustToEngineHardwareScalingLevel = false; this._capturedPointerIds = /* @__PURE__ */ new Set(); this._numLayoutCalls = 0; this._numRenderCalls = 0; this._clipboardData = ""; this.onClipboardObservable = new Observable(); this.onControlPickedObservable = new Observable(); this.onBeginLayoutObservable = new Observable(); this.onEndLayoutObservable = new Observable(); this.onBeginRenderObservable = new Observable(); this.onEndRenderObservable = new Observable(); this.premulAlpha = false; this.applyYInversionOnUpdate = true; this.disableTabNavigation = false; this.disablePicking = false; this.usePointerTapForClickEvent = false; this.skipBlockEvents = 0; this.checkPointerEveryFrame = false; this._useInvalidateRectOptimization = true; this._invalidatedRectangle = null; this._alreadyRegisteredForRender = false; this._clearMeasure = new Measure(0, 0, 0, 0); this._focusProperties = { index: 0, total: -1 }; this._onClipboardCopy = (rawEvt) => { const evt = rawEvt; const ev = new ClipboardInfo(ClipboardEventTypes.COPY, evt); this.onClipboardObservable.notifyObservers(ev); evt.preventDefault(); }; this._onClipboardCut = (rawEvt) => { const evt = rawEvt; const ev = new ClipboardInfo(ClipboardEventTypes.CUT, evt); this.onClipboardObservable.notifyObservers(ev); evt.preventDefault(); }; this._onClipboardPaste = (rawEvt) => { const evt = rawEvt; const ev = new ClipboardInfo(ClipboardEventTypes.PASTE, evt); this.onClipboardObservable.notifyObservers(ev); evt.preventDefault(); }; this.parseContent = this.parseSerializedObject; scene = this.getScene(); if (!scene || !this._texture) { return; } this.applyYInversionOnUpdate = invertY; this._rootElement = scene.getEngine().getInputElement(); const adtOptions = widthOrOptions; this.useStandalone = !!adtOptions?.useStandalone; if (!this.useStandalone) { this._renderObserver = scene.onBeforeCameraRenderObservable.add((camera) => this._checkUpdate(camera)); } this._controlAddedObserver = this._rootContainer.onControlAddedObservable.add((control) => { if (control) { this._rootChildrenHaveChanged = true; } }); this._controlRemovedObserver = this._rootContainer.onControlRemovedObservable.add((control) => { if (control) { this._rootChildrenHaveChanged = true; } }); this._preKeyboardObserver = scene.onPreKeyboardObservable.add((info) => { if (!this.disableTabNavigation && info.type === KeyboardEventTypes.KEYDOWN && info.event.code === "Tab") { const forward = !info.event.shiftKey; if (forward && this._focusProperties.index === this._focusProperties.total - 1 || !forward && this._focusProperties.index === 0 && this._focusProperties.total > 0) { this.focusedControl = null; this._focusProperties.index = 0; this._focusProperties.total = -1; return; } this._focusNextElement(forward); info.event.preventDefault(); return; } if (!this._focusedControl) { return; } if (info.type === KeyboardEventTypes.KEYDOWN) { this._focusedControl.processKeyboard(info.event); } info.skipOnPointerObservable = true; }); this._rootContainer._link(this); this.hasAlpha = true; if (!width || !height) { this._resizeObserver = scene.getEngine().onResizeObservable.add(() => this._onResize()); this._onResize(); } this._texture.isReady = true; } /** * Get the current class name of the texture useful for serialization or dynamic coding. * @returns "AdvancedDynamicTexture" */ getClassName() { return "AdvancedDynamicTexture"; } /** * Function used to execute a function on all controls * @param func defines the function to execute * @param container defines the container where controls belong. If null the root container will be used */ executeOnAllControls(func, container) { if (!container) { container = this._rootContainer; } func(container); for (const child of container.children) { if (child.children) { this.executeOnAllControls(func, child); continue; } func(child); } } /** * Gets or sets a boolean indicating if the InvalidateRect optimization should be turned on */ get useInvalidateRectOptimization() { return this._useInvalidateRectOptimization; } set useInvalidateRectOptimization(value) { this._useInvalidateRectOptimization = value; } /** * Invalidates a rectangle area on the gui texture * @param invalidMinX left most position of the rectangle to invalidate in the texture * @param invalidMinY top most position of the rectangle to invalidate in the texture * @param invalidMaxX right most position of the rectangle to invalidate in the texture * @param invalidMaxY bottom most position of the rectangle to invalidate in the texture */ invalidateRect(invalidMinX, invalidMinY, invalidMaxX, invalidMaxY) { if (!this._useInvalidateRectOptimization) { return; } if (!this._invalidatedRectangle) { this._invalidatedRectangle = new Measure(invalidMinX, invalidMinY, invalidMaxX - invalidMinX + 1, invalidMaxY - invalidMinY + 1); } else { const maxX = Math.ceil(Math.max(this._invalidatedRectangle.left + this._invalidatedRectangle.width - 1, invalidMaxX)); const maxY = Math.ceil(Math.max(this._invalidatedRectangle.top + this._invalidatedRectangle.height - 1, invalidMaxY)); this._invalidatedRectangle.left = Math.floor(Math.min(this._invalidatedRectangle.left, invalidMinX)); this._invalidatedRectangle.top = Math.floor(Math.min(this._invalidatedRectangle.top, invalidMinY)); this._invalidatedRectangle.width = maxX - this._invalidatedRectangle.left + 1; this._invalidatedRectangle.height = maxY - this._invalidatedRectangle.top + 1; } } /** * Marks the texture as dirty forcing a complete update */ markAsDirty() { this._isDirty = true; } /** * Helper function used to create a new style * @returns a new style * @see https://doc.babylonjs.com/features/featuresDeepDive/gui/gui#styles */ createStyle() { return new Style(this); } /** * Adds a new control to the root container * @param control defines the control to add * @returns the current texture */ addControl(control) { this._rootContainer.addControl(control); return this; } /** * Removes a control from the root container * @param control defines the control to remove * @returns the current texture */ removeControl(control) { this._rootContainer.removeControl(control); return this; } /** * Moves overlapped controls towards a position where it is not overlapping anymore. * Please note that this method alters linkOffsetXInPixels and linkOffsetYInPixels. * @param overlapGroup the overlap group which will be processed or undefined to process all overlap groups * @param deltaStep the step size (speed) to reach the target non overlapping position (default 0.1) * @param repelFactor how much is the control repelled by other controls */ moveToNonOverlappedPosition(overlapGroup, deltaStep = 1, repelFactor = 1) { let controlsForGroup; if (Array.isArray(overlapGroup)) { controlsForGroup = overlapGroup; } else { const descendants = this.getDescendants(true); controlsForGroup = overlapGroup === void 0 ? descendants.filter((c) => c.overlapGroup !== void 0) : descendants.filter((c) => c.overlapGroup === overlapGroup); } for (const control1 of controlsForGroup) { let velocity = Vector2.Zero(); const center = new Vector2(control1.centerX, control1.centerY); for (const control2 of controlsForGroup) { if (control1 !== control2 && _AdvancedDynamicTexture._Overlaps(control1, control2)) { const diff = center.subtract(new Vector2(control2.centerX, control2.centerY)); const diffLength = diff.length(); if (diffLength > 0) { velocity = velocity.add(diff.normalize().scale(repelFactor / diffLength)); } } } if (velocity.length() > 0) { velocity = velocity.normalize().scale(deltaStep * (control1.overlapDeltaMultiplier ?? 1)); control1.linkOffsetXInPixels += velocity.x; control1.linkOffsetYInPixels += velocity.y; } } } /** * Release all resources */ dispose() { const scene = this.getScene(); if (!scene) { return; } this._rootElement = null; scene.onBeforeCameraRenderObservable.remove(this._renderObserver); if (this._resizeObserver) { scene.getEngine().onResizeObservable.remove(this._resizeObserver); } if (this._prePointerObserver) { scene.onPrePointerObservable.remove(this._prePointerObserver); } if (this._sceneRenderObserver) { scene.onBeforeRenderObservable.remove(this._sceneRenderObserver); } if (this._pointerObserver) { scene.onPointerObservable.remove(this._pointerObserver); } if (this._preKeyboardObserver) { scene.onPreKeyboardObservable.remove(this._preKeyboardObserver); } if (this._canvasPointerOutObserver) { scene.getEngine().onCanvasPointerOutObservable.remove(this._canvasPointerOutObserver); } if (this._canvasBlurObserver) { scene.getEngine().onCanvasBlurObservable.remove(this._canvasBlurObserver); } if (this._controlAddedObserver) { this._rootContainer.onControlAddedObservable.remove(this._controlAddedObserver); } if (this._controlRemovedObserver) { this._rootContainer.onControlRemovedObservable.remove(this._controlRemovedObserver); } if (this._layerToDispose) { this._layerToDispose.texture = null; this._layerToDispose.dispose(); this._layerToDispose = null; } this._rootContainer.dispose(); this.onClipboardObservable.clear(); this.onControlPickedObservable.clear(); this.onBeginRenderObservable.clear(); this.onEndRenderObservable.clear(); this.onBeginLayoutObservable.clear(); this.onEndLayoutObservable.clear(); this.onGuiReadyObservable.clear(); super.dispose(); } _onResize() { const scene = this.getScene(); if (!scene) { return; } const engine = scene.getEngine(); if (this.adjustToEngineHardwareScalingLevel) { this._renderScale = engine.getHardwareScalingLevel(); this._renderScale = 1 / Math.max(this._renderScale, engine.getRenderWidth() / engine.getCaps().maxTextureSize, engine.getRenderHeight() / engine.getCaps().maxTextureSize); } const textureSize = this.getSize(); let renderWidth = engine.getRenderWidth() * this._renderScale; let renderHeight = engine.getRenderHeight() * this._renderScale; if (this._renderAtIdealSize) { if (this._idealWidth) { renderHeight = renderHeight * this._idealWidth / renderWidth; renderWidth = this._idealWidth; } else if (this._idealHeight) { renderWidth = renderWidth * this._idealHeight / renderHeight; renderHeight = this._idealHeight; } } if (textureSize.width !== renderWidth || textureSize.height !== renderHeight) { this.scaleTo(renderWidth, renderHeight); if (this.adjustToEngineHardwareScalingLevel) { const engineRenderScale = 1 / engine.getHardwareScalingLevel(); const scale = this._renderScale * engineRenderScale; this._rootContainer.scaleX = scale; this._rootContainer.scaleY = scale; this._rootContainer.widthInPixels = renderWidth / scale; this._rootContainer.heightInPixels = renderHeight / scale; } this.markAsDirty(); if (this._idealWidth || this._idealHeight) { this._rootContainer._markAllAsDirty(); } if (!this._alreadyRegisteredForRender) { this._alreadyRegisteredForRender = true; Tools.SetImmediate(() => { this.update(this.applyYInversionOnUpdate, this.premulAlpha, _AdvancedDynamicTexture.AllowGPUOptimizations); this._alreadyRegisteredForRender = false; }); } } this.invalidateRect(0, 0, textureSize.width - 1, textureSize.height - 1); } /** @internal */ _getGlobalViewport() { const size = this.getSize(); const globalViewPort = this._fullscreenViewport.toGlobal(size.width, size.height); const targetX = Math.round(globalViewPort.width / this._rootContainer.scaleX); const targetY = Math.round(globalViewPort.height / this._rootContainer.scaleY); const scale = this._adjustToEngineHardwareScalingLevel ? this._renderScale / (this.getScene()?.getEngine().getHardwareScalingLevel() || 1) : 1; globalViewPort.x += (globalViewPort.width / scale - targetX) / 2; globalViewPort.y += (globalViewPort.height / scale - targetY) / 2; globalViewPort.width = targetX; globalViewPort.height = targetY; return globalViewPort; } /** * Get screen coordinates for a vector3 * @param position defines the position to project * @param worldMatrix defines the world matrix to use * @returns the projected position */ getProjectedPosition(position, worldMatrix) { const result = this.getProjectedPositionWithZ(position, worldMatrix); return new Vector2(result.x, result.y); } /** * Get screen coordinates for a vector3 * @param position defines the position to project * @param worldMatrix defines the world matrix to use * @returns the projected position with Z */ getProjectedPositionWithZ(position, worldMatrix) { const scene = this.getScene(); if (!scene) { return Vector3.Zero(); } const globalViewport = this._getGlobalViewport(); const projectedPosition = Vector3.Project(position, worldMatrix, scene.getTransformMatrix(), globalViewport); return new Vector3(projectedPosition.x, projectedPosition.y, projectedPosition.z); } /** @internal */ _checkUpdate(camera, skipUpdate) { if (this._layerToDispose && camera) { if ((camera.layerMask & this._layerToDispose.layerMask) === 0) { return; } } if (this._isFullscreen && this._linkedControls.length) { const scene = this.getScene(); if (!scene) { return; } const globalViewport = this._getGlobalViewport(); for (const control of this._linkedControls) { if (!control.isVisible) { continue; } const mesh = control._linkedMesh; if (!mesh || mesh.isDisposed()) { Tools.SetImmediate(() => { control.linkWithMesh(null); }); continue; } const position = mesh.getBoundingInfo ? mesh.getBoundingInfo().boundingSphere.center : Vector3.ZeroReadOnly; const projectedPosition = Vector3.Project(position, mesh.getWorldMatrix(), scene.getTransformMatrix(), globalViewport); if (projectedPosition.z < 0 || projectedPosition.z > 1) { control.notRenderable = true; continue; } control.notRenderable = false; if (this.useInvalidateRectOptimization) { control.invalidateRect(); } control._moveToProjectedPosition(projectedPosition); } } if (!this._isDirty && !this._rootContainer.isDirty) { return; } this._isDirty = false; this._render(skipUpdate); if (!skipUpdate) { this.update(this.applyYInversionOnUpdate, this.premulAlpha, _AdvancedDynamicTexture.AllowGPUOptimizations); } } _render(skipRender) { const textureSize = this.getSize(); const renderWidth = textureSize.width; const renderHeight = textureSize.height; const context = this.getContext(); context.font = "18px Arial"; context.strokeStyle = "white"; if (this.onGuiReadyObservable.hasObservers()) { this._checkGuiIsReady(); } if (this._rootChildrenHaveChanged) { const camera = this.getScene()?.activeCamera; if (camera) { this._rootChildrenHaveChanged = false; this._checkUpdate(camera, true); } } this.onBeginLayoutObservable.notifyObservers(this); const measure = new Measure(0, 0, renderWidth, renderHeight); this._numLayoutCalls = 0; this._rootContainer._layout(measure, context); this.onEndLayoutObservable.notifyObservers(this); this._isDirty = false; if (skipRender) { return; } if (this._invalidatedRectangle) { this._clearMeasure.copyFrom(this._invalidatedRectangle); } else { this._clearMeasure.copyFromFloats(0, 0, renderWidth, renderHeight); } context.clearRect(this._clearMeasure.left, this._clearMeasure.top, this._clearMeasure.width, this._clearMeasure.height); if (this._background) { context.save(); context.fillStyle = this._background; context.fillRect(this._clearMeasure.left, this._clearMeasure.top, this._clearMeasure.width, this._clearMeasure.height); context.restore(); } this.onBeginRenderObservable.notifyObservers(this); this._numRenderCalls = 0; this._rootContainer._render(context, this._invalidatedRectangle); this.onEndRenderObservable.notifyObservers(this); this._invalidatedRectangle = null; } /** * @internal */ _changeCursor(cursor) { if (this._rootElement) { this._rootElement.style.cursor = cursor; this._cursorChanged = true; } } /** * @internal */ _registerLastControlDown(control, pointerId) { this._lastControlDown[pointerId] = control; this.onControlPickedObservable.notifyObservers(control); } _doPicking(x, y, pi, type, pointerId, buttonIndex, deltaX, deltaY) { const scene = this.getScene(); if (!scene || this.disablePicking) { return; } const engine = scene.getEngine(); const textureSize = this.getSize(); if (this._isFullscreen) { const camera = scene.cameraToUseForPointers || scene.activeCamera; if (!camera) { return; } const viewport = camera.viewport; x = x * (textureSize.width / (engine.getRenderWidth() * viewport.width)); y = y * (textureSize.height / (engine.getRenderHeight() * viewport.height)); } if (this._capturingControl[pointerId]) { if (this._capturingControl[pointerId].isPointerBlocker) { this._shouldBlockPointer = true; } this._capturingControl[pointerId]._processObservables(type, x, y, pi, pointerId, buttonIndex); return; } this._cursorChanged = false; if (!this._rootContainer._processPicking(x, y, pi, type, pointerId, buttonIndex, deltaX, deltaY)) { if (!scene.doNotHandleCursors) { this._changeCursor(""); } if (type === PointerEventTypes.POINTERMOVE) { if (this._lastControlOver[pointerId]) { this._lastControlOver[pointerId]._onPointerOut(this._lastControlOver[pointerId], pi); delete this._lastControlOver[pointerId]; } } } if (!this._cursorChanged && !scene.doNotHandleCursors) { this._changeCursor(""); } this._manageFocus(); } /** * @internal */ _cleanControlAfterRemovalFromList(list, control) { for (const pointerId in list) { if (!Object.prototype.hasOwnProperty.call(list, pointerId)) { continue; } const lastControlOver = list[pointerId]; if (lastControlOver === control) { delete list[pointerId]; } } } /** * @internal */ _cleanControlAfterRemoval(control) { this._cleanControlAfterRemovalFromList(this._lastControlDown, control); this._cleanControlAfterRemovalFromList(this._lastControlOver, control); } /** * This function will run a pointer event on this ADT and will trigger any pointer events on any controls * This will work on a fullscreen ADT only. For mesh based ADT, simulate pointer events using the scene directly. * @param x pointer X on the canvas for the picking * @param y pointer Y on the canvas for the picking * @param pi optional pointer information */ pick(x, y, pi = null) { if (this._isFullscreen && this._scene) { this._translateToPicking(this._scene, new Viewport(0, 0, 0, 0), pi, x, y); } } _translateToPicking(scene, tempViewport, pi, x = scene.pointerX, y = scene.pointerY) { const camera = scene.cameraToUseForPointers || scene.activeCamera; const engine = scene.getEngine(); const originalCameraToUseForPointers = scene.cameraToUseForPointers; if (!camera) { tempViewport.x = 0; tempViewport.y = 0; tempViewport.width = engine.getRenderWidth(); tempViewport.height = engine.getRenderHeight(); } else { if (camera.rigCameras.length) { const rigViewport = new Viewport(0, 0, 1, 1); for (const rigCamera of camera.rigCameras) { rigCamera.viewport.toGlobalToRef(engine.getRenderWidth(), engine.getRenderHeight(), rigViewport); const transformedX2 = x / engine.getHardwareScalingLevel() - rigViewport.x; const transformedY2 = y / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - rigViewport.y - rigViewport.height); if (transformedX2 < 0 || transformedY2 < 0 || x > rigViewport.width || y > rigViewport.height) { return; } scene.cameraToUseForPointers = rigCamera; tempViewport.x = rigViewport.x; tempViewport.y = rigViewport.y; tempViewport.width = rigViewport.width; tempViewport.height = rigViewport.height; } } else { camera.viewport.toGlobalToRef(engine.getRenderWidth(), engine.getRenderHeight(), tempViewport); } } const transformedX = x / engine.getHardwareScalingLevel() - tempViewport.x; const transformedY = y / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - tempViewport.y - tempViewport.height); this._shouldBlockPointer = false; if (pi) { const pointerId = pi.event.pointerId || this._defaultMousePointerId; this._doPicking(transformedX, transformedY, pi, pi.type, pointerId, pi.event.button, pi.event.deltaX, pi.event.deltaY); if (this._shouldBlockPointer && !(pi.type & this.skipBlockEvents) || this._capturingControl[pointerId]) { pi.skipOnPointerObservable = true; } } else { this._doPicking(transformedX, transformedY, null, PointerEventTypes.POINTERMOVE, this._defaultMousePointerId, 0); } scene.cameraToUseForPointers = originalCameraToUseForPointers; } /** Attach to all scene events required to support pointer events */ attach() { const scene = this.getScene(); if (!scene) { return; } const tempViewport = new Viewport(0, 0, 0, 0); this._prePointerObserver = scene.onPrePointerObservable.add((pi) => { if (scene.isPointerCaptured(pi.event.pointerId) && pi.type === PointerEventTypes.POINTERUP && !this._capturedPointerIds.has(pi.event.pointerId)) { return; } if (pi.type !== PointerEventTypes.POINTERMOVE && pi.type !== PointerEventTypes.POINTERUP && pi.type !== PointerEventTypes.POINTERDOWN && pi.type !== PointerEventTypes.POINTERWHEEL && pi.type !== PointerEventTypes.POINTERTAP) { return; } if (pi.type === PointerEventTypes.POINTERMOVE) { if (scene.isPointerCaptured(pi.event.pointerId)) { return; } if (pi.event.pointerId) { this._defaultMousePointerId = pi.event.pointerId; } } this._translateToPicking(scene, tempViewport, pi); }); this._attachPickingToSceneRender(scene, () => this._translateToPicking(scene, tempViewport, null), false); this._attachToOnPointerOut(scene); this._attachToOnBlur(scene); } _focusNextElement(forward = true) { const sortedTabbableControls = []; this.executeOnAllControls((control) => { if (control.isFocusInvisible || !control.isVisible || control.tabIndex < 0) { return; } sortedTabbableControls.push(control); }); if (sortedTabbableControls.length === 0) { return; } sortedTabbableControls.sort((a, b) => { return a.tabIndex === 0 ? 1 : b.tabIndex === 0 ? -1 : a.tabIndex - b.tabIndex; }); this._focusProperties.total = sortedTabbableControls.length; let nextIndex = -1; if (!this._focusedControl) { nextIndex = forward ? 0 : sortedTabbableControls.length - 1; } else { const currentIndex = sortedTabbableControls.indexOf(this._focusedControl); nextIndex = currentIndex + (forward ? 1 : -1); if (nextIndex < 0) { nextIndex = sortedTabbableControls.length - 1; } else if (nextIndex >= sortedTabbableControls.length) { nextIndex = 0; } } sortedTabbableControls[nextIndex].focus(); this._focusProperties.index = nextIndex; } /** * Register the clipboard Events onto the canvas */ registerClipboardEvents() { self.addEventListener("copy", this._onClipboardCopy, false); self.addEventListener("cut", this._onClipboardCut, false); self.addEventListener("paste", this._onClipboardPaste, false); } /** * Unregister the clipboard Events from the canvas */ unRegisterClipboardEvents() { self.removeEventListener("copy", this._onClipboardCopy); self.removeEventListener("cut", this._onClipboardCut); self.removeEventListener("paste", this._onClipboardPaste); } /** * Transform uvs from mesh space to texture space, taking the texture into account * @param uv the uvs in mesh space * @returns the uvs in texture space */ _transformUvs(uv) { const textureMatrix = this.getTextureMatrix(); let result; if (textureMatrix.isIdentityAs3x2()) { result = uv; } else { const homogeneousTextureMatrix = TmpVectors.Matrix[0]; textureMatrix.getRowToRef(0, TmpVectors.Vector4[0]); textureMatrix.getRowToRef(1, TmpVectors.Vector4[1]); textureMatrix.getRowToRef(2, TmpVectors.Vector4[2]); const r0 = TmpVectors.Vector4[0]; const r1 = TmpVectors.Vector4[1]; const r2 = TmpVectors.Vector4[2]; homogeneousTextureMatrix.setRowFromFloats(0, r0.x, r0.y, 0, 0); homogeneousTextureMatrix.setRowFromFloats(1, r1.x, r1.y, 0, 0); homogeneousTextureMatrix.setRowFromFloats(2, 0, 0, 1, 0); homogeneousTextureMatrix.setRowFromFloats(3, r2.x, r2.y, 0, 1); result = TmpVectors.Vector2[0]; Vector2.TransformToRef(uv, homogeneousTextureMatrix, result); } if (this.wrapU === Texture.WRAP_ADDRESSMODE || this.wrapU === Texture.MIRROR_ADDRESSMODE) { if (result.x > 1) { let fX = result.x - Math.trunc(result.x); if (this.wrapU === Texture.MIRROR_ADDRESSMODE && Math.trunc(result.x) % 2 === 1) { fX = 1 - fX; } result.x = fX; } } if (this.wrapV === Texture.WRAP_ADDRESSMODE || this.wrapV === Texture.MIRROR_ADDRESSMODE) { if (result.y > 1) { let fY = result.y - Math.trunc(result.y); if (this.wrapV === Texture.MIRROR_ADDRESSMODE && Math.trunc(result.x) % 2 === 1) { fY = 1 - fY; } result.y = fY; } } return result; } /** * Connect the texture to a hosting mesh to enable interactions * @param mesh defines the mesh to attach to * @param supportPointerMove defines a boolean indicating if pointer move events must be catched as well */ attachToMesh(mesh, supportPointerMove = true) { const scene = this.getScene(); if (!scene) { return; } if (this._pointerObserver) { scene.onPointerObservable.remove(this._pointerObserver); } this._pointerObserver = scene.onPointerObservable.add((pi) => { if (pi.type !== PointerEventTypes.POINTERMOVE && pi.type !== PointerEventTypes.POINTERUP && pi.type !== PointerEventTypes.POINTERDOWN && pi.type !== PointerEventTypes.POINTERWHEEL) { return; } if (pi.type === PointerEventTypes.POINTERMOVE && pi.event.pointerId) { this._defaultMousePointerId = pi.event.pointerId; } const pointerId = pi.event.pointerId || this._defaultMousePointerId; if (pi.pickInfo && pi.pickInfo.hit && pi.pickInfo.pickedMesh === mesh) { let uv = pi.pickInfo.getTextureCoordinates(); if (uv) { uv = this._transformUvs(uv); const size = this.getSize(); this._doPicking(uv.x * size.width, (this.applyYInversionOnUpdate ? 1 - uv.y : uv.y) * size.height, pi, pi.type, pointerId, pi.event.button, pi.event.deltaX, pi.event.deltaY); } } else if (pi.type === PointerEventTypes.POINTERUP) { if (this._lastControlDown[pointerId]) { this._lastControlDown[pointerId]._forcePointerUp(pointerId); } delete this._lastControlDown[pointerId]; if (this.focusedControl) { const friendlyControls = this.focusedControl.keepsFocusWith(); let canMoveFocus = true; if (friendlyControls) { for (const control of friendlyControls) { if (this === control._host) { continue; } const otherHost = control._host; if (otherHost._lastControlOver[pointerId] && otherHost._lastControlOver[pointerId].isAscendant(control)) { canMoveFocus = false; break; } } } if (canMoveFocus) { this.focusedControl = null; } } } else if (pi.type === PointerEventTypes.POINTERMOVE) { if (this._lastControlOver[pointerId]) { this._lastControlOver[pointerId]._onPointerOut(this._lastControlOver[pointerId], pi, true); } delete this._lastControlOver[pointerId]; } }); mesh.enablePointerMoveEvents = supportPointerMove; this._attachPickingToSceneRender(scene, () => { const pointerId = this._defaultMousePointerId; const pick = scene?.pick(scene.pointerX, scene.pointerY); if (pick && pick.hit && pick.pickedMesh === mesh) { let uv = pick.getTextureCoordinates(); if (uv) { uv = this._transformUvs(uv); const size = this.getSize(); this._doPicking(uv.x * size.width, (this.applyYInversionOnUpdate ? 1 - uv.y : uv.y) * size.height, null, PointerEventTypes.POINTERMOVE, pointerId, 0); } } else { if (this._lastControlOver[pointerId]) { this._lastControlOver[pointerId]._onPointerOut(this._lastControlOver[pointerId], null, true); } delete this._lastControlOver[pointerId]; } }, true); this._attachToOnPointerOut(scene); this._attachToOnBlur(scene); } /** * Move the focus to a specific control * @param control defines the control which will receive the focus */ moveFocusToControl(control) { this.focusedControl = control; this._lastPickedControl = control; this._blockNextFocusCheck = true; } _manageFocus() { if (this._blockNextFocusCheck) { this._blockNextFocusCheck = false; this._lastPickedControl = this._focusedControl; return; } if (this._focusedControl) { if (this._focusedControl !== this._lastPickedControl) { if (this._lastPickedControl.isFocusInvisible) { return; } this.focusedControl = null; } } } _attachPickingToSceneRender(scene, pickFunction, forcePicking) { this._sceneRenderObserver = scene.onBeforeRenderObservable.add(() => { if (!this.checkPointerEveryFrame) { return; } if (this._linkedControls.length > 0 || forcePicking) { pickFunction(); } }); } _attachToOnPointerOut(scene) { this._canvasPointerOutObserver = scene.getEngine().onCanvasPointerOutObservable.add((pointerEvent) => { if (this._lastControlOver[pointerEvent.pointerId]) { this._lastControlOver[pointerEvent.pointerId]._onPointerOut(this._lastControlOver[pointerEvent.pointerId], null); } delete this._lastControlOver[pointerEvent.pointerId]; if (this._lastControlDown[pointerEvent.pointerId] && this._lastControlDown[pointerEvent.pointerId] !== this._capturingControl[pointerEvent.pointerId]) { this._lastControlDown[pointerEvent.pointerId]._forcePointerUp(pointerEvent.pointerId); delete this._lastControlDown[pointerEvent.pointerId]; } }); } _attachToOnBlur(scene) { this._canvasBlurObserver = scene.getEngine().onCanvasBlurObservable.add(() => { Object.entries(this._lastControlDown).forEach(([, value]) => { value._onCanvasBlur(); }); this.focusedControl = null; this._lastControlDown = {}; }); } /** * Serializes the entire GUI system * @returns an object with the JSON serialized data */ serializeContent() { const size = this.getSize(); const serializationObject = { root: {}, width: size.width, height: size.height }; this._rootContainer.serialize(serializationObject.root); return serializationObject; } /** * Recreate the content of the ADT from a JSON object * @param serializedObject define the JSON serialized object to restore from * @param scaleToSize defines whether to scale to texture to the saved size * @param urlRewriter defines an url rewriter to update urls before sending them to the controls */ parseSerializedObject(serializedObject, scaleToSize, urlRewriter) { this._rootContainer = Control.Parse(serializedObject.root, this, urlRewriter); if (scaleToSize) { const width = serializedObject.width; const height = serializedObject.height; if (typeof width === "number" && typeof height === "number" && width >= 0 && height >= 0) { this.scaleTo(width, height); } else { this.scaleTo(1920, 1080); } } } /** * Clones the ADT. If no mesh is defined, the GUI will be considered as a fullscreen GUI * @param newName defines the name of the new ADT * @param attachToMesh defines if the new ADT should be attached to a mesh * @returns the clone of the ADT */ clone(newName, attachToMesh) { const scene = this.getScene(); if (!scene) { return this; } const size = this.getSize(); const data = this.serializeContent(); let clone; if (!this._isFullscreen) { if (attachToMesh) { clone = _AdvancedDynamicTexture.CreateForMesh(attachToMesh, size.width, size.height); } else { clone = new _AdvancedDynamicTexture(newName ?? "Clone of " + this.name, size.width, size.height, scene, !this.noMipmap, this.samplingMode); } } else { clone = _AdvancedDynamicTexture.CreateFullscreenUI(newName ?? "Clone of " + this.name); } clone.parseSerializedObject(data); return clone; } /** * Recreate the content of the ADT from a snippet saved by the GUI editor * @param snippetId defines the snippet to load * @param scaleToSize defines whether to scale to texture to the saved size * @param appendToAdt if provided the snippet will be appended to the adt. Otherwise a fullscreen ADT will be created. * @param urlRewriter defines an url rewriter to update urls before sending them to the controls * @returns a promise that will resolve on success */ static async ParseFromSnippetAsync(snippetId, scaleToSize, appendToAdt, urlRewriter) { const adt = appendToAdt ?? _AdvancedDynamicTexture.CreateFullscreenUI("ADT from snippet"); if (snippetId === "_BLANK") { return adt; } const serialized = await _AdvancedDynamicTexture._LoadURLContentAsync(_AdvancedDynamicTexture.SnippetUrl + "/" + snippetId.replace(/#/g, "/"), true); adt.parseSerializedObject(serialized, scaleToSize, urlRewriter); return adt; } /** * Recreate the content of the ADT from a snippet saved by the GUI editor * @param snippetId defines the snippet to load * @param scaleToSize defines whether to scale to texture to the saved size * @param urlRewriter defines an url rewriter to update urls before sending them to the controls * @returns a promise that will resolve on success */ async parseFromSnippetAsync(snippetId, scaleToSize, urlRewriter) { return await _AdvancedDynamicTexture.ParseFromSnippetAsync(snippetId, scaleToSize, this, urlRewriter); } /** * Recreate the content of the ADT from a url json * @param url defines the url to load * @param scaleToSize defines whether to scale to texture to the saved size * @param appendToAdt if provided the snippet will be appended to the adt. Otherwise a fullscreen ADT will be created. * @param urlRewriter defines an url rewriter to update urls before sending them to the controls * @returns a promise that will resolve on success */ static async ParseFromFileAsync(url, scaleToSize, appendToAdt, urlRewriter) { const adt = appendToAdt ?? _AdvancedDynamicTexture.CreateFullscreenUI("ADT from URL"); const serialized = await _AdvancedDynamicTexture._LoadURLContentAsync(url); adt.parseSerializedObject(serialized, scaleToSize, urlRewriter); return adt; } /** * Recreate the content of the ADT from a url json * @param url defines the url to load * @param scaleToSize defines whether to scale to texture to the saved size * @param urlRewriter defines an url rewriter to update urls before sending them to the controls * @returns a promise that will resolve on success */ async parseFromURLAsync(url, scaleToSize, urlRewriter) { return await _AdvancedDynamicTexture.ParseFromFileAsync(url, scaleToSize, this, urlRewriter); } static async _LoadURLContentAsync(url, snippet = false) { if (url === "") { throw new Error("No URL provided"); } return await new Promise((resolve, reject) => { const request = new WebRequest(); request.addEventListener("readystatechange", () => { if (request.readyState == 4) { if (request.status == 200) { let gui; if (snippet) { const payload = JSON.parse(JSON.parse(request.responseText).jsonPayload); gui = payload.encodedGui ? new TextDecoder("utf-8").decode(DecodeBase64ToBinary(payload.encodedGui)) : payload.gui; } else { gui = request.responseText; } const serializationObject = JSON.parse(gui); resolve(serializationObject); } else { reject("Unable to load"); } } }); request.open("GET", url); request.send(); }); } // Statics /** * Compares two rectangle based controls for pixel overlap * @param control1 The first control to compare * @param control2 The second control to compare * @returns true if overlaps, otherwise false */ static _Overlaps(control1, control2) { return !(control1.centerX > control2.centerX + control2.widthInPixels || control1.centerX + control1.widthInPixels < control2.centerX || control1.centerY + control1.heightInPixels < control2.centerY || control1.centerY > control2.centerY + control2.heightInPixels); } /** * Creates a new AdvancedDynamicTexture in projected mode (ie. attached to a mesh) * @param mesh defines the mesh which will receive the texture * @param width defines the texture width (1024 by default) * @param height defines the texture height (1024 by default) * @param supportPointerMove defines a boolean indicating if the texture must capture move events (true by default) * @param onlyAlphaTesting defines a boolean indicating that alpha blending will not be used (only alpha testing) (false by default) * @param invertY defines if the texture needs to be inverted on the y axis during loading (true by default) * @param materialSetupCallback defines a custom way of creating and setting up the material on the mesh * @param sampling defines the texture sampling mode (Texture.TRILINEAR_SAMPLINGMODE by default) * @returns a new AdvancedDynamicTexture */ static CreateForMesh(mesh, width = 1024, height = 1024, supportPointerMove = true, onlyAlphaTesting = false, invertY, materialSetupCallback = this._CreateMaterial, sampling = Texture.TRILINEAR_SAMPLINGMODE) { const uniqueId = RandomGUID(); const result = new _AdvancedDynamicTexture(`AdvancedDynamicTexture for ${mesh.name} [${uniqueId}]`, width, height, mesh.getScene(), true, sampling, invertY); materialSetupCallback(mesh, uniqueId, result, onlyAlphaTesting); result.attachToMesh(mesh, supportPointerMove); return result; } static _CreateMaterial(mesh, uniqueId, texture, onlyAlphaTesting) { const internalClassType = GetClass("BABYLON.StandardMaterial"); if (!internalClassType) { throw "StandardMaterial needs to be imported before as it contains a side-effect required by your code."; } const material = new internalClassType(`AdvancedDynamicTextureMaterial for ${mesh.name} [${uniqueId}]`, mesh.getScene()); material.backFaceCulling = false; material.diffuseColor = Color3.Black(); material.specularColor = Color3.Black(); if (onlyAlphaTesting) { material.diffuseTexture = texture; material.emissiveTexture = texture; texture.hasAlpha = true; } else { material.emissiveTexture = texture; material.opacityTexture = texture; } mesh.material = material; } /** * Creates a new AdvancedDynamicTexture in projected mode (ie. attached to a mesh) BUT do not create a new material for the mesh. You will be responsible for connecting the texture * @param mesh defines the mesh which will receive the texture * @param width defines the texture width (1024 by default) * @param height defines the texture height (1024 by default) * @param supportPointerMove defines a boolean indicating if the texture must capture move events (true by default) * @param invertY defines if the texture needs to be inverted on the y axis during loading (true by default) * @param sampling defines the texture sampling mode (Texture.TRILINEAR_SAMPLINGMODE by default) * @returns a new AdvancedDynamicTexture */ static CreateForMeshTexture(mesh, width = 1024, height = 1024, supportPointerMove = true, invertY, sampling = Texture.TRILINEAR_SAMPLINGMODE) { const result = new _AdvancedDynamicTexture(mesh.name + " AdvancedDynamicTexture", width, height, mesh.getScene(), true, sampling, invertY); result.attachToMesh(mesh, supportPointerMove); return result; } /** * Creates a new AdvancedDynamicTexture in fullscreen mode. * In this mode the texture will rely on a layer for its rendering. * This allows it to be treated like any other layer. * As such, if you have a multi camera setup, you can set the layerMask on the GUI as well. * LayerMask is set through advancedTexture.layer.layerMask * @param name defines name for the texture * @param foreground defines a boolean indicating if the texture must be rendered in foreground (default is true) * @param sceneOrOptions defines the hosting scene or options (IAdvancedDynamicTextureOptions) * @param sampling defines the texture sampling mode (Texture.BILINEAR_SAMPLINGMODE by default) * @param adaptiveScaling defines whether to automatically scale root to match hardwarescaling (false by default) * @returns a new AdvancedDynamicTexture */ static CreateFullscreenUI(name260, foreground = true, sceneOrOptions = null, sampling = Texture.BILINEAR_SAMPLINGMODE, adaptiveScaling = false) { const isScene2 = !sceneOrOptions || sceneOrOptions._isScene; const result = isScene2 ? new _AdvancedDynamicTexture(name260, 0, 0, sceneOrOptions, false, sampling) : new _AdvancedDynamicTexture(name260, sceneOrOptions); const resultScene = result.getScene(); const layer = new Layer(name260 + "_layer", null, resultScene, !foreground); layer.texture = result; result._layerToDispose = layer; result._isFullscreen = true; if (result.useStandalone) { layer.layerMask = 0; } result.adjustToEngineHardwareScalingLevel = adaptiveScaling; result.attach(); return result; } /** * Scales the texture * @param ratio the scale factor to apply to both width and height */ scale(ratio) { super.scale(ratio); this.markAsDirty(); } /** * Resizes the texture * @param width the new width * @param height the new height */ scaleTo(width, height) { super.scaleTo(width, height); this.markAsDirty(); } _checkGuiIsReady() { if (this.guiIsReady()) { this.onGuiReadyObservable.notifyObservers(this); this.onGuiReadyObservable.clear(); } } /** * @returns true if all the GUI components are ready to render */ guiIsReady() { return this._rootContainer.isReady(); } }; AdvancedDynamicTexture.SnippetUrl = Constants.SnippetUrl; AdvancedDynamicTexture.AllowGPUOptimizations = true; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/tools/sound.js function getSoundById(id, scene) { const soundTracks = scene.soundTracks ?? []; if (!soundTracks.length) { soundTracks.push(scene.mainSoundTrack); } for (let i = 0, len = soundTracks.length; i < len; i++) { const sound = soundTracks[i].soundCollection.find((s) => s.id === id); if (sound) { return sound; } } return null; } __name(getSoundById, "getSoundById"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/decorators/apply.js init_math_color(); init_texture(); init_math_vector(); function applyDecorators(scene, object, script, instance, rootUrl) { const ctor = instance.constructor; if (!ctor) { return; } ctor._NodesFromScene?.forEach((params) => { instance[params.propertyKey.toString()] = scene.getNodeByName(params.nodeName); }); ctor._NodesFromDescendants?.forEach((params) => { const descendant = object.getDescendants?.(params.directDescendantsOnly, (node) => node.name === params.nodeName)[0]; instance[params.propertyKey.toString()] = descendant ?? null; }); ctor._AnimationGroups?.forEach((params) => { instance[params.propertyKey.toString()] = scene.getAnimationGroupByName(params.animationGroupName); }); ctor._SoundsFromScene?.forEach((params) => { const sound = scene.getSoundByName?.(params.soundName); instance[params.propertyKey.toString()] = sound ?? null; }); (ctor._GuiFromAsset ?? []).map(async (params) => { const guiUrl = `${rootUrl}assets/${params.pathInAssets}`; try { const response = await fetch(guiUrl); const data = await response.json(); const gui = AdvancedDynamicTexture.CreateFullscreenUI(data.name, true, scene); gui.parseSerializedObject(data.content, false); instance[params.propertyKey.toString()] = gui; params.onGuiCreated?.(instance, gui); } catch (e) { console.error(`Failed to load GUI from asset: ${guiUrl}`); throw e; } }); ctor._ParticleSystemsFromScene?.forEach((params) => { const particleSystem = scene.particleSystems?.find((particleSystem2) => { if (particleSystem2.name !== params.particleSystemName) { return false; } return params.directDescendantsOnly ? particleSystem2.emitter === object : particleSystem2; }); instance[params.propertyKey.toString()] = particleSystem; }); (ctor._VisibleInInspector ?? []).forEach(async (params) => { const propertyKey = params.propertyKey.toString(); const attachedScripts = script.values; if (!attachedScripts) { throw new Error(`No values found for script with key "${script.key}".`); } if (attachedScripts.hasOwnProperty(propertyKey) && attachedScripts[propertyKey].hasOwnProperty("value")) { const value = attachedScripts[propertyKey].value; switch (params.configuration.type) { case "number": case "boolean": case "keymap": case "string": instance[propertyKey] = value; break; case "vector2": instance[propertyKey] = Vector2.FromArray(value); break; case "vector3": instance[propertyKey] = Vector3.FromArray(value); break; case "color3": instance[propertyKey] = Color3.FromArray(value); break; case "color4": instance[propertyKey] = Color4.FromArray(value); break; case "entity": const entityType = params.configuration.entityType; switch (entityType) { case "node": instance[propertyKey] = scene.getNodeById(value) ?? null; break; case "animationGroup": instance[propertyKey] = scene.getAnimationGroupByName(value) ?? null; break; case "sound": instance[propertyKey] = getSoundById(value, scene); break; case "particleSystem": instance[propertyKey] = scene.particleSystems?.find((ps) => ps.id === value) ?? null; break; } break; case "texture": if (value) { instance[propertyKey] = Texture.Parse(value, scene, rootUrl); } break; case "asset": if (value) { const assetType = params.configuration.assetType; const data = scriptAssetsCache.get(value); switch (assetType) { case "json": case "scene": instance[propertyKey] = data; break; case "nodeParticleSystemSet": const npss = NodeParticleSystemSet.Parse(data); instance[propertyKey] = npss; break; case "material": instance[propertyKey] = Material.Parse(data, scene, rootUrl); break; } } } } }); let pointerObserver = null; let keyboardObserver = null; if (ctor._PointerEvents?.length) { const wrongMeshListener = ctor._PointerEvents.find((params) => params.options.mode === "attachedMeshOnly"); if (wrongMeshListener && !isAbstractMesh(object)) { throw new Error(`@onPointerEvent with mode "attachedMeshOnly" can only be used on scripts attached to meshes (extends AbstractMesh).`); } const wrongSceneListener = ctor._PointerEvents.find((params) => params.options.mode !== "global"); if (wrongSceneListener && !isNode(object)) { throw new Error(`@onPointerEvent with mode different from "global" can be used only on scripts attached to Node: Mesh, Light, Camera, TransformNode.`); } pointerObserver = scene.onPointerObservable.add((pointerInfo) => { let pickInfo = null; ctor._PointerEvents.forEach((params) => { if (!params.eventTypes.includes(pointerInfo.type)) { return; } const propertyKey = params.propertyKey.toString(); if (params.options.mode === "global") { return instance[propertyKey]?.(pointerInfo); } pickInfo = pointerInfo.pickInfo; if (!pickInfo) { pickInfo = scene.pick(scene.pointerX, scene.pointerY, (m) => { return m.isVisible && m.isPickable && m.isEnabled(true) && !m._masterMesh; }, false); } const pickedMesh = pickInfo.pickedMesh; if (pickedMesh) { if (params.options.mode === "attachedMeshOnly" && pickedMesh === object) { return instance[propertyKey]?.(pointerInfo); } if (params.options.mode === "includeDescendants" && isNode(object)) { const descendants = [object, ...object.getDescendants(false)]; const pickedDescendant = descendants.find((d) => d === pickedMesh); if (pickedDescendant) { return instance[propertyKey]?.(pointerInfo); } } } }); }); } if (ctor._KeyboardEvents?.length) { keyboardObserver = scene.onKeyboardObservable.add((keyboardInfo) => { ctor._KeyboardEvents.forEach((params) => { if (!params.eventTypes.includes(keyboardInfo.type)) { return; } instance[params.propertyKey.toString()]?.(keyboardInfo); }); }); } if (ctor._SpritesFromSpriteManager?.length) { const spriteManagerNode = object; if (!isTransformNode(spriteManagerNode) || !spriteManagerNode.isSpriteManager) { return console.error(`@spriteFromSpriteManager decorator can only be used on SpriteManagerNode.`); } if (!spriteManagerNode.spriteManager) { return console.error(`SpriteManagerNode "${spriteManagerNode.name}" has no sprite manager assigned.`); } ctor._SpritesFromSpriteManager?.forEach((params) => { const sprite = spriteManagerNode.spriteManager?.sprites.find((s) => s.name === params.spriteName) || null; instance[params.propertyKey.toString()] = sprite; }); } if (ctor._AnimationsFromSprite?.length) { if (!isSprite(object)) { return console.error(`@animationFromSprite decorator can only be used in scripts attached on Sprite.`); } const spriteAnimations = object.metadata?.spriteAnimations; if (!spriteAnimations?.length) { return console.error(`Sprite "${object.name}" has no sprite animations assigned.`); } ctor._AnimationsFromSprite.forEach((params) => { const animation = spriteAnimations.find((a) => a.name === params.animationName); if (animation) { instance[params.propertyKey.toString()] = animation ?? null; } else { console.warn(`Sprite animation named "${params.animationName}" not found on sprite "${object.name}".`); } }); } return { observers: { pointerObserver, keyboardObserver } }; } __name(applyDecorators, "applyDecorators"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/loading/script.js var scriptAssetsCache = /* @__PURE__ */ new Map(); async function _preloadScriptsAssets(rootUrl, scene) { const nodes = [scene, ...scene.transformNodes, ...scene.meshes, ...scene.lights, ...scene.cameras]; const scripts = nodes.filter((node) => node.metadata?.scripts?.length).map((node) => node.metadata.scripts).flat(); scripts.forEach((script) => { if (!script.values) { return; } for (const key in script.values) { if (!script.values.hasOwnProperty(key)) { continue; } const obj = script.values[key]; if (obj.type === "asset" && obj.value) { scriptAssetsCache.set(obj.value, null); } } }); const promises = []; scriptAssetsCache.forEach((_, key) => { if (scriptAssetsCache.get(key)) { return; } promises.push(new Promise(async (resolve) => { try { const extension = key.split(".").pop(); if (extension === "scene") { const filename = key.split("/").pop(); const sceneFilename = filename.replace(".scene", ".babylon"); const container = await LoadAssetContainerAsync(`${rootUrl}${sceneFilename}`, scene, { pluginExtension: ".babylon" }); if (SceneLoaderFlags.ForceFullSceneLoadingForIncremental) { scene.meshes.forEach((m) => isMesh(m) && m._checkDelayState()); } container.addAllToScene(); scriptAssetsCache.set(key, container); } else { const response = await fetch(`${rootUrl}${key}`); const data = await response.json(); scriptAssetsCache.set(key, data); } } catch (e) { console.error(e); } resolve(); })); }); await Promise.all(promises); } __name(_preloadScriptsAssets, "_preloadScriptsAssets"); function _applyScriptsForObject(scene, object, scriptsMap, rootUrl) { if (!object.metadata?.scripts) { return; } object.metadata.scripts?.forEach(async (script) => { if (!script.enabled) { return; } const exports2 = scriptsMap[script.key]; if (!exports2) { return; } let result = exports2; const observers = {}; if (exports2.default) { result = new exports2.default(object); const decoratorsResult = applyDecorators(scene, object, script, result, rootUrl); Object.assign(observers, decoratorsResult?.observers ?? {}); } if (result.onStart) { observers.onStartObserver = scene.onBeforeRenderObservable.addOnce(() => result.onStart(object)); } if (result.onUpdate) { observers.onUpdateObserver = scene.onBeforeRenderObservable.add(() => result.onUpdate(object)); } _registerScriptInstance(object, result, script.key, observers); }); object.metadata.scripts = void 0; } __name(_applyScriptsForObject, "_applyScriptsForObject"); function applyScriptOnObject(object, scriptConstructor, scene) { scene ??= object.getScene?.(); if (!scene) { throw new Error("Cannot apply script on object: no scene available."); } const instance = new scriptConstructor(object); const observers = {}; const script = { values: {} }; applyDecorators(scene, object, script, instance, ""); if (instance.onStart) { observers.onStartObserver = scene.onBeforeRenderObservable.addOnce(() => instance.onStart()); } if (instance.onUpdate) { scene.onBeforeRenderObservable.add(() => instance.onUpdate()); } _registerScriptInstance(object, instance, "runtime", observers); return instance; } __name(applyScriptOnObject, "applyScriptOnObject"); var scriptsDictionary = /* @__PURE__ */ new Map(); function _registerScriptInstance(object, scriptInstance, key, observers) { const registeredScript = { key, observers, instance: scriptInstance }; if (!scriptsDictionary.has(object)) { scriptsDictionary.set(object, [registeredScript]); } else { scriptsDictionary.get(object).push(registeredScript); } if (isNode(object) || isAnyParticleSystem(object) || isScene(object)) { object.onDisposeObservable.addOnce(() => { scriptsDictionary.get(object)?.forEach((s) => { _removeRegisteredScriptInstance(object, s); }); scriptsDictionary.delete(object); }); } } __name(_registerScriptInstance, "_registerScriptInstance"); function _removeRegisteredScriptInstance(object, registeredScript) { registeredScript.observers.onStartObserver?.remove(); registeredScript.observers.onUpdateObserver?.remove(); registeredScript.observers.pointerObserver?.remove(); registeredScript.observers.keyboardObserver?.remove(); try { registeredScript.instance.onStop?.(object); } catch (e) { console.error(`Failed to call onStop for script ${registeredScript.key} on object ${object}`, e); } const runningScripts = scriptsDictionary.get(object); const index = runningScripts?.indexOf(registeredScript) ?? -1; if (index !== -1) { runningScripts?.splice(index, 1); } } __name(_removeRegisteredScriptInstance, "_removeRegisteredScriptInstance"); function getAllScriptsByClassForObject(object, classType) { const data = scriptsDictionary.get(object); const result = data?.filter((s) => s.instance.constructor === classType); return result?.map((r) => r.instance) ?? null; } __name(getAllScriptsByClassForObject, "getAllScriptsByClassForObject"); function getScriptByClassForObject(object, classType) { const result = getAllScriptsByClassForObject(object, classType); return result?.[0] ?? null; } __name(getScriptByClassForObject, "getScriptByClassForObject"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/loading/sound.js init_sceneComponent(); var registered = false; function registerAudioParser() { if (registered) { return; } registered = true; const audioParser = GetParser(SceneComponentConstants.NAME_AUDIO); AddParser("AudioEditorPlugin", (parsedData, scene, container, rootUrl) => { audioParser?.(parsedData, scene, container, rootUrl); parsedData.sounds?.forEach((sound) => { const instance = container.sounds?.find((s) => s.name === sound.name); if (instance) { instance.id = sound.id; instance.uniqueId = sound.uniqueId; } }); }); } __name(registerAudioParser, "registerAudioParser"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/tools/scalar.js function getPowerOfTwoUntil(limit) { let size = 1; while (size <= limit) { size <<= 1; } return size >> 1; } __name(getPowerOfTwoUntil, "getPowerOfTwoUntil"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/loading/texture.js init_decorators_serialization(); var registered2 = false; function registerTextureParser() { if (registered2) { return; } registered2 = true; const textureParser = SerializationHelper._TextureParser; SerializationHelper._TextureParser = (sourceProperty, scene, rootUrl) => { if (scene.loadingTexturesQuality === "high" || !sourceProperty.metadata?.baseSize) { return textureParser(sourceProperty, scene, rootUrl); } const width = sourceProperty.metadata.baseSize.width; const height = sourceProperty.metadata.baseSize.height; const isPowerOfTwo = width === getPowerOfTwoUntil(width) || height === getPowerOfTwoUntil(height); let suffix = ""; switch (scene.loadingTexturesQuality) { case "medium": let midWidth = width * 0.66 >> 0; let midHeight = height * 0.66 >> 0; if (isPowerOfTwo) { midWidth = getPowerOfTwoUntil(midWidth); midHeight = getPowerOfTwoUntil(midHeight); } suffix = `_${midWidth}_${midHeight}`; break; case "low": case "very-low": let lowWidth = width * 0.33 >> 0; let lowHeight = height * 0.33 >> 0; if (isPowerOfTwo) { lowWidth = getPowerOfTwoUntil(lowWidth); lowHeight = getPowerOfTwoUntil(lowHeight); } suffix = `_${lowWidth}_${lowHeight}`; break; } const name260 = sourceProperty.name; if (!name260 || !suffix) { return textureParser(sourceProperty, scene, rootUrl); } const finalUrl = name260.split("/"); const filename = finalUrl.pop(); if (!filename) { return textureParser(sourceProperty, scene, rootUrl); } const extension = filename.split(".").pop(); const baseFilename = filename.replace(`.${extension}`, ""); const newFilename = `${baseFilename}${suffix}.${extension}`; finalUrl.push(newFilename); sourceProperty.name = finalUrl.join("/"); return textureParser(sourceProperty, scene, rootUrl); }; } __name(registerTextureParser, "registerTextureParser"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/loading/shadows.js init_sceneComponent(); var registered3 = false; function registerShadowGeneratorParser() { if (registered3) { return; } registered3 = true; const shadowsGeneratorParser = GetParser(SceneComponentConstants.NAME_SHADOWGENERATOR); AddParser("ShadowGeneratorEditorPlugin", (parsedData, scene, container, rootUrl) => { if (scene.loadingShadowsQuality !== "high") { parsedData.shadowGenerators?.forEach((shadowGenerator) => { switch (scene.loadingShadowsQuality) { case "medium": shadowGenerator.mapSize = shadowGenerator.mapSize * 0.5; break; case "low": shadowGenerator.mapSize = shadowGenerator.mapSize * 0.25; break; case "very-low": shadowGenerator.mapSize = shadowGenerator.mapSize * 0.125; break; } shadowGenerator.mapSize = Math.max(128, getPowerOfTwoUntil(shadowGenerator.mapSize)); }); } shadowsGeneratorParser?.(parsedData, scene, container, rootUrl); }); } __name(registerShadowGeneratorParser, "registerShadowGeneratorParser"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Materials/shaderMaterial.js init_decorators_serialization(); init_scene(); init_math_vector(); init_buffer(); init_texture(); init_typeStore(); init_effectFallbacks(); init_webRequest(); init_engineStore(); init_clipPlaneMaterialHelper(); init_materialHelper_functions(); var OnCreatedEffectParameters = { effect: null, subMesh: null }; var ShaderMaterial = class _ShaderMaterial extends PushMaterial { static { __name(this, "ShaderMaterial"); } /** * Instantiate a new shader material. * The ShaderMaterial object has the necessary methods to pass data from your scene to the Vertex and Fragment Shaders and returns a material that can be applied to any mesh. * This returned material effects how the mesh will look based on the code in the shaders. * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/shaders/shaderMaterial * @param name Define the name of the material in the scene * @param scene Define the scene the material belongs to * @param shaderPath Defines the route to the shader code. * @param options Define the options used to create the shader * @param storeEffectOnSubMeshes true to store effect on submeshes, false to store the effect directly in the material class. */ constructor(name260, scene, shaderPath, options = {}, storeEffectOnSubMeshes = true) { super(name260, scene, storeEffectOnSubMeshes); this._textures = {}; this._textureArrays = {}; this._externalTextures = {}; this._floats = {}; this._ints = {}; this._uints = {}; this._floatsArrays = {}; this._colors3 = {}; this._colors3Arrays = {}; this._colors4 = {}; this._colors4Arrays = {}; this._vectors2 = {}; this._vectors3 = {}; this._vectors4 = {}; this._quaternions = {}; this._quaternionsArrays = {}; this._matrices = {}; this._matrixArrays = {}; this._matrices3x3 = {}; this._matrices2x2 = {}; this._vectors2Arrays = {}; this._vectors3Arrays = {}; this._vectors4Arrays = {}; this._uniformBuffers = {}; this._textureSamplers = {}; this._storageBuffers = {}; this._cachedWorldViewMatrix = new Matrix(); this._cachedWorldViewProjectionMatrix = new Matrix(); this._multiview = false; this._materialHelperNeedsPreviousMatrices = false; this._shaderPath = shaderPath; this._options = { needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], externalTextures: [], samplerObjects: [], storageBuffers: [], defines: [], useClipPlane: false, ...options }; } /** * Gets the shader path used to define the shader code * It can be modified to trigger a new compilation */ get shaderPath() { return this._shaderPath; } /** * Sets the shader path used to define the shader code * It can be modified to trigger a new compilation */ set shaderPath(shaderPath) { this._shaderPath = shaderPath; } /** * Gets the options used to compile the shader. * They can be modified to trigger a new compilation */ get options() { return this._options; } /** * is multiview set to true? */ get isMultiview() { return this._multiview; } /** * Gets the current class name of the material e.g. "ShaderMaterial" * Mainly use in serialization. * @returns the class name */ getClassName() { return "ShaderMaterial"; } /** * Specifies if the material will require alpha blending * @returns a boolean specifying if alpha blending is needed */ needAlphaBlending() { return this.alpha < 1 || this._options.needAlphaBlending; } /** * Specifies if this material should be rendered in alpha test mode * @returns a boolean specifying if an alpha test is needed. */ needAlphaTesting() { return this._options.needAlphaTesting; } _checkUniform(uniformName) { if (this._options.uniforms.indexOf(uniformName) === -1) { this._options.uniforms.push(uniformName); } } /** * Set a texture in the shader. * @param name Define the name of the uniform samplers as defined in the shader * @param texture Define the texture to bind to this sampler * @returns the material itself allowing "fluent" like uniform updates */ setTexture(name260, texture) { if (this._options.samplers.indexOf(name260) === -1) { this._options.samplers.push(name260); } this._textures[name260] = texture; return this; } /** * Remove a texture from the material. * @param name Define the name of the texture to remove */ removeTexture(name260) { delete this._textures[name260]; } /** * Set a texture array in the shader. * @param name Define the name of the uniform sampler array as defined in the shader * @param textures Define the list of textures to bind to this sampler * @returns the material itself allowing "fluent" like uniform updates */ setTextureArray(name260, textures) { if (this._options.samplers.indexOf(name260) === -1) { this._options.samplers.push(name260); } this._checkUniform(name260); this._textureArrays[name260] = textures; return this; } /** * Set an internal texture in the shader. * @param name Define the name of the uniform samplers as defined in the shader * @param texture Define the texture to bind to this sampler * @returns the material itself allowing "fluent" like uniform updates */ setExternalTexture(name260, texture) { if (this._options.externalTextures.indexOf(name260) === -1) { this._options.externalTextures.push(name260); } this._externalTextures[name260] = texture; return this; } /** * Set a float in the shader. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setFloat(name260, value) { this._checkUniform(name260); this._floats[name260] = value; return this; } /** * Set a int in the shader. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setInt(name260, value) { this._checkUniform(name260); this._ints[name260] = value; return this; } /** * Set a unsigned int in the shader. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setUInt(name260, value) { this._checkUniform(name260); this._uints[name260] = value; return this; } /** * Set an array of floats in the shader. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setFloats(name260, value) { this._checkUniform(name260); this._floatsArrays[name260] = value; return this; } /** * Set a vec3 in the shader from a Color3. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setColor3(name260, value) { this._checkUniform(name260); this._colors3[name260] = value; return this; } /** * Set a vec3 array in the shader from a IColor3Like array. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setColor3Array(name260, value) { this._checkUniform(name260); this._colors3Arrays[name260] = value.reduce((arr, color) => { arr.push(color.r, color.g, color.b); return arr; }, []); return this; } /** * Set a vec4 in the shader from a Color4. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setColor4(name260, value) { this._checkUniform(name260); this._colors4[name260] = value; return this; } /** * Set a vec4 array in the shader from a IColor4Like array. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setColor4Array(name260, value) { this._checkUniform(name260); this._colors4Arrays[name260] = value.reduce((arr, color) => { arr.push(color.r, color.g, color.b, color.a); return arr; }, []); return this; } /** * Set a vec2 in the shader from a Vector2. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setVector2(name260, value) { this._checkUniform(name260); this._vectors2[name260] = value; return this; } /** * Set a vec3 in the shader from a Vector3. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setVector3(name260, value) { this._checkUniform(name260); this._vectors3[name260] = value; return this; } /** * Set a vec4 in the shader from a Vector4. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setVector4(name260, value) { this._checkUniform(name260); this._vectors4[name260] = value; return this; } /** * Set a vec4 in the shader from a Quaternion. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setQuaternion(name260, value) { this._checkUniform(name260); this._quaternions[name260] = value; return this; } /** * Set a vec4 array in the shader from a Quaternion array. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setQuaternionArray(name260, value) { this._checkUniform(name260); this._quaternionsArrays[name260] = value.reduce((arr, quaternion) => { quaternion.toArray(arr, arr.length); return arr; }, []); return this; } /** * Set a mat4 in the shader from a Matrix. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setMatrix(name260, value) { this._checkUniform(name260); this._matrices[name260] = value; return this; } /** * Set a float32Array in the shader from a matrix array. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setMatrices(name260, value) { this._checkUniform(name260); const float32Array = new Float32Array(value.length * 16); for (let index = 0; index < value.length; index++) { const matrix = value[index]; matrix.copyToArray(float32Array, index * 16); } this._matrixArrays[name260] = float32Array; return this; } /** * Set a mat3 in the shader from a Float32Array. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setMatrix3x3(name260, value) { this._checkUniform(name260); this._matrices3x3[name260] = value; return this; } /** * Set a mat2 in the shader from a Float32Array. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setMatrix2x2(name260, value) { this._checkUniform(name260); this._matrices2x2[name260] = value; return this; } /** * Set a vec2 array in the shader from a number array. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setArray2(name260, value) { this._checkUniform(name260); this._vectors2Arrays[name260] = value; return this; } /** * Set a vec3 array in the shader from a number array. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setArray3(name260, value) { this._checkUniform(name260); this._vectors3Arrays[name260] = value; return this; } /** * Set a vec4 array in the shader from a number array. * @param name Define the name of the uniform as defined in the shader * @param value Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setArray4(name260, value) { this._checkUniform(name260); this._vectors4Arrays[name260] = value; return this; } /** * Set a uniform buffer in the shader * @param name Define the name of the uniform as defined in the shader * @param buffer Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setUniformBuffer(name260, buffer) { if (this._options.uniformBuffers.indexOf(name260) === -1) { this._options.uniformBuffers.push(name260); } this._uniformBuffers[name260] = buffer; return this; } /** * Set a texture sampler in the shader * @param name Define the name of the uniform as defined in the shader * @param sampler Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setTextureSampler(name260, sampler) { if (this._options.samplerObjects.indexOf(name260) === -1) { this._options.samplerObjects.push(name260); } this._textureSamplers[name260] = sampler; return this; } /** * Set a storage buffer in the shader * @param name Define the name of the storage buffer as defined in the shader * @param buffer Define the value to give to the uniform * @returns the material itself allowing "fluent" like uniform updates */ setStorageBuffer(name260, buffer) { if (this._options.storageBuffers.indexOf(name260) === -1) { this._options.storageBuffers.push(name260); } this._storageBuffers[name260] = buffer; return this; } /** * Adds, removes, or replaces the specified shader define and value. * * setDefine("MY_DEFINE", true); // enables a boolean define * * setDefine("MY_DEFINE", "0.5"); // adds "#define MY_DEFINE 0.5" to the shader (or sets and replaces the value of any existing define with that name) * * setDefine("MY_DEFINE", false); // disables and removes the define * Note if the active defines do change, the shader will be recompiled and this can be expensive. * @param define the define name e.g., "OUTPUT_TO_SRGB" or "#define OUTPUT_TO_SRGB". If the define was passed into the constructor already, the version used should match that, and in either case, it should not include any appended value. * @param value either the value of the define (e.g. a numerical value) or for booleans, true if the define should be enabled or false if it should be disabled * @returns the material itself allowing "fluent" like uniform updates */ setDefine(define, value) { const defineName = define.trimEnd() + " "; const existingDefineIdx = this.options.defines.findIndex((x) => x === define || x.startsWith(defineName)); if (existingDefineIdx >= 0) { this.options.defines.splice(existingDefineIdx, 1); } if (typeof value !== "boolean" || value) { this.options.defines.push(defineName + value); } return this; } /** * Specifies that the submesh is ready to be used * @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 */ isReadyForSubMesh(mesh, subMesh, useInstances) { return this.isReady(mesh, useInstances, subMesh); } /** * Checks if the material is ready to render the requested mesh * @param mesh Define the mesh to render * @param useInstances Define whether or not the material is used with instances * @param subMesh defines which submesh to render * @returns true if ready, otherwise false */ isReady(mesh, useInstances, subMesh) { const storeEffectOnSubMeshes = subMesh && this._storeEffectOnSubMeshes; if (this.isFrozen) { const drawWrapper2 = storeEffectOnSubMeshes ? subMesh._drawWrapper : this._drawWrapper; if (drawWrapper2.effect && drawWrapper2._wasPreviouslyReady && drawWrapper2._wasPreviouslyUsingInstances === useInstances) { return true; } } const scene = this.getScene(); const engine = scene.getEngine(); const defines = []; const attribs = []; let fallbacks = null; let shaderName = this._shaderPath, uniforms = this._options.uniforms, uniformBuffers = this._options.uniformBuffers, samplers = this._options.samplers; if (engine.getCaps().multiview && scene.activeCamera && scene.activeCamera.outputRenderTarget && scene.activeCamera.outputRenderTarget.getViewCount() > 1) { this._multiview = true; defines.push("#define MULTIVIEW"); if (uniforms.indexOf("viewProjection") !== -1 && uniforms.indexOf("viewProjectionR") === -1) { uniforms.push("viewProjectionR"); } } for (let index = 0; index < this._options.defines.length; index++) { const defineToAdd = this._options.defines[index].indexOf("#define") === 0 ? this._options.defines[index] : `#define ${this._options.defines[index]}`; defines.push(defineToAdd); } for (let index = 0; index < this._options.attributes.length; index++) { attribs.push(this._options.attributes[index]); } if (mesh && mesh.isVerticesDataPresent(VertexBuffer.ColorKind)) { if (attribs.indexOf(VertexBuffer.ColorKind) === -1) { attribs.push(VertexBuffer.ColorKind); } defines.push("#define VERTEXCOLOR"); } if (useInstances) { defines.push("#define INSTANCES"); PushAttributesForInstances(attribs, this._materialHelperNeedsPreviousMatrices); if (mesh?.hasThinInstances) { defines.push("#define THIN_INSTANCES"); if (mesh && mesh.isVerticesDataPresent(VertexBuffer.ColorInstanceKind)) { attribs.push(VertexBuffer.ColorInstanceKind); defines.push("#define INSTANCESCOLOR"); } } } if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) { attribs.push(VertexBuffer.MatricesIndicesKind); attribs.push(VertexBuffer.MatricesWeightsKind); if (mesh.numBoneInfluencers > 4) { attribs.push(VertexBuffer.MatricesIndicesExtraKind); attribs.push(VertexBuffer.MatricesWeightsExtraKind); } const skeleton = mesh.skeleton; defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers); fallbacks = new EffectFallbacks(); fallbacks.addCPUSkinningFallback(0, mesh); if (skeleton.isUsingTextureForMatrices) { defines.push("#define BONETEXTURE"); if (uniforms.indexOf("boneTextureWidth") === -1) { uniforms.push("boneTextureWidth"); } if (this._options.samplers.indexOf("boneSampler") === -1) { this._options.samplers.push("boneSampler"); } } else { defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1)); if (uniforms.indexOf("mBones") === -1) { uniforms.push("mBones"); } } } else { defines.push("#define NUM_BONE_INFLUENCERS 0"); } let numInfluencers = 0; const manager = mesh ? mesh.morphTargetManager : null; if (manager) { const uv = defines.indexOf("#define UV1") !== -1; const uv2 = defines.indexOf("#define UV2") !== -1; const tangent = defines.indexOf("#define TANGENT") !== -1; const normal = defines.indexOf("#define NORMAL") !== -1; const color = defines.indexOf("#define VERTEXCOLOR") !== -1; numInfluencers = PrepareDefinesAndAttributesForMorphTargets( manager, defines, attribs, mesh, true, // usePositionMorph normal, // useNormalMorph tangent, // useTangentMorph uv, // useUVMorph uv2, // useUV2Morph color // useColorMorph ); if (manager.isUsingTextureForTargets) { if (uniforms.indexOf("morphTargetTextureIndices") === -1) { uniforms.push("morphTargetTextureIndices"); } if (this._options.samplers.indexOf("morphTargets") === -1) { this._options.samplers.push("morphTargets"); } } if (numInfluencers > 0) { uniforms = uniforms.slice(); uniforms.push("morphTargetInfluences"); uniforms.push("morphTargetCount"); uniforms.push("morphTargetTextureInfo"); uniforms.push("morphTargetTextureIndices"); } } else { defines.push("#define NUM_MORPH_INFLUENCERS 0"); } if (mesh) { const bvaManager = mesh.bakedVertexAnimationManager; if (bvaManager && bvaManager.isEnabled) { defines.push("#define BAKED_VERTEX_ANIMATION_TEXTURE"); if (uniforms.indexOf("bakedVertexAnimationSettings") === -1) { uniforms.push("bakedVertexAnimationSettings"); } if (uniforms.indexOf("bakedVertexAnimationTextureSizeInverted") === -1) { uniforms.push("bakedVertexAnimationTextureSizeInverted"); } if (uniforms.indexOf("bakedVertexAnimationTime") === -1) { uniforms.push("bakedVertexAnimationTime"); } if (this._options.samplers.indexOf("bakedVertexAnimationTexture") === -1) { this._options.samplers.push("bakedVertexAnimationTexture"); } } PrepareAttributesForBakedVertexAnimation(attribs, mesh, defines); } for (const name260 in this._textures) { if (!this._textures[name260].isReady()) { return false; } } if (mesh && this.needAlphaTestingForMesh(mesh)) { defines.push("#define ALPHATEST"); } if (this._options.useClipPlane !== false) { AddClipPlaneUniforms(uniforms); PrepareStringDefinesForClipPlanes(this, scene, defines); } if (scene.fogEnabled && mesh?.applyFog && scene.fogMode !== Scene.FOGMODE_NONE) { defines.push("#define FOG"); if (uniforms.indexOf("view") === -1) { uniforms.push("view"); } if (uniforms.indexOf("vFogInfos") === -1) { uniforms.push("vFogInfos"); } if (uniforms.indexOf("vFogColor") === -1) { uniforms.push("vFogColor"); } } if (this._useLogarithmicDepth) { defines.push("#define LOGARITHMICDEPTH"); if (uniforms.indexOf("logarithmicDepthConstant") === -1) { uniforms.push("logarithmicDepthConstant"); } } if (this.customShaderNameResolve) { uniforms = uniforms.slice(); uniformBuffers = uniformBuffers.slice(); samplers = samplers.slice(); shaderName = this.customShaderNameResolve(this.name, uniforms, uniformBuffers, samplers, defines, attribs); } const renderingMesh = subMesh ? subMesh.getRenderingMesh() : mesh; if (renderingMesh && this.useVertexPulling) { defines.push("#define USE_VERTEX_PULLING"); const indexBuffer = renderingMesh.geometry?.getIndexBuffer(); if (indexBuffer) { defines.push("#define VERTEX_PULLING_USE_INDEX_BUFFER"); if (indexBuffer.is32Bits) { defines.push("#define VERTEX_PULLING_INDEX_BUFFER_32BITS"); } } } const drawWrapper = storeEffectOnSubMeshes ? subMesh._getDrawWrapper(void 0, true) : this._drawWrapper; const previousEffect = drawWrapper?.effect ?? null; const previousDefines = drawWrapper?.defines ?? null; const join = defines.join("\n"); let effect = previousEffect; if (previousDefines !== join) { effect = engine.createEffect(shaderName, { attributes: attribs, uniformsNames: uniforms, uniformBuffersNames: uniformBuffers, samplers, defines: join, fallbacks, onCompiled: this.onCompiled, onError: this.onError, indexParameters: { maxSimultaneousMorphTargets: numInfluencers }, shaderLanguage: this._options.shaderLanguage, extraInitializationsAsync: this._options.extraInitializationsAsync }, engine); if (storeEffectOnSubMeshes) { subMesh.setEffect(effect, join, this._materialContext); } else if (drawWrapper) { drawWrapper.setEffect(effect, join); } if (this._onEffectCreatedObservable) { OnCreatedEffectParameters.effect = effect; OnCreatedEffectParameters.subMesh = subMesh ?? mesh?.subMeshes[0] ?? null; this._onEffectCreatedObservable.notifyObservers(OnCreatedEffectParameters); } } drawWrapper._wasPreviouslyUsingInstances = !!useInstances; if (!effect?.isReady()) { return false; } if (previousEffect !== effect) { scene.resetCachedMaterial(); } drawWrapper._wasPreviouslyReady = true; return true; } /** * Binds the world matrix to the material * @param world defines the world transformation matrix * @param effectOverride - If provided, use this effect instead of internal effect */ bindOnlyWorldMatrix(world, effectOverride) { const effect = effectOverride ?? this.getEffect(); if (!effect) { return; } const uniforms = this._options.uniforms; if (uniforms.indexOf("world") !== -1) { effect.setMatrix("world", world); } const scene = this.getScene(); if (uniforms.indexOf("worldView") !== -1) { world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix); effect.setMatrix("worldView", this._cachedWorldViewMatrix); } if (uniforms.indexOf("worldViewProjection") !== -1) { world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix); effect.setMatrix("worldViewProjection", this._cachedWorldViewProjectionMatrix); } if (uniforms.indexOf("view") !== -1) { effect.setMatrix("view", scene.getViewMatrix()); } } /** * 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 */ bindForSubMesh(world, mesh, subMesh) { this.bind(world, mesh, subMesh._drawWrapperOverride?.effect, subMesh); } /** * Binds the material to the mesh * @param world defines the world transformation matrix * @param mesh defines the mesh to bind the material to * @param effectOverride - If provided, use this effect instead of internal effect * @param subMesh defines the submesh to bind the material to */ bind(world, mesh, effectOverride, subMesh) { const storeEffectOnSubMeshes = subMesh && this._storeEffectOnSubMeshes; const effect = effectOverride ?? (storeEffectOnSubMeshes ? subMesh.effect : this.getEffect()); if (!effect) { return; } const scene = this.getScene(); this._activeEffect = effect; this.bindOnlyWorldMatrix(world, effectOverride); const uniformBuffers = this._options.uniformBuffers; let useSceneUBO = false; if (effect && uniformBuffers && uniformBuffers.length > 0 && scene.getEngine().supportsUniformBuffers) { for (let i = 0; i < uniformBuffers.length; ++i) { const bufferName = uniformBuffers[i]; switch (bufferName) { case "Mesh": if (mesh) { mesh.getMeshUniformBuffer().bindToEffect(effect, "Mesh"); mesh.transferToEffect(world); } break; case "Scene": BindSceneUniformBuffer(effect, scene.getSceneUniformBuffer()); scene.finalizeSceneUbo(); useSceneUBO = true; break; } } } const mustRebind = mesh && storeEffectOnSubMeshes ? this._mustRebind(scene, effect, subMesh, mesh.visibility) : scene.getCachedMaterial() !== this; if (effect && mustRebind) { if (!useSceneUBO && this._options.uniforms.indexOf("view") !== -1) { effect.setMatrix("view", scene.getViewMatrix()); } if (!useSceneUBO && this._options.uniforms.indexOf("projection") !== -1) { effect.setMatrix("projection", scene.getProjectionMatrix()); } if (!useSceneUBO && this._options.uniforms.indexOf("viewProjection") !== -1) { effect.setMatrix("viewProjection", scene.getTransformMatrix()); if (this._multiview) { effect.setMatrix("viewProjectionR", scene._transformMatrixR); } } if (scene.activeCamera && this._options.uniforms.indexOf("cameraPosition") !== -1) { effect.setVector3("cameraPosition", scene.activeCamera.globalPosition); } BindBonesParameters(mesh, effect); BindClipPlane(effect, this, scene); if (this._useLogarithmicDepth) { BindLogDepth(storeEffectOnSubMeshes ? subMesh.materialDefines : effect.defines, effect, scene); } if (mesh) { BindFogParameters(scene, mesh, effect); } let name260; for (name260 in this._textures) { effect.setTexture(name260, this._textures[name260]); } for (name260 in this._textureArrays) { effect.setTextureArray(name260, this._textureArrays[name260]); } for (name260 in this._ints) { effect.setInt(name260, this._ints[name260]); } for (name260 in this._uints) { effect.setUInt(name260, this._uints[name260]); } for (name260 in this._floats) { effect.setFloat(name260, this._floats[name260]); } for (name260 in this._floatsArrays) { effect.setArray(name260, this._floatsArrays[name260]); } for (name260 in this._colors3) { effect.setColor3(name260, this._colors3[name260]); } for (name260 in this._colors3Arrays) { effect.setArray3(name260, this._colors3Arrays[name260]); } for (name260 in this._colors4) { const color = this._colors4[name260]; effect.setFloat4(name260, color.r, color.g, color.b, color.a); } for (name260 in this._colors4Arrays) { effect.setArray4(name260, this._colors4Arrays[name260]); } for (name260 in this._vectors2) { effect.setVector2(name260, this._vectors2[name260]); } for (name260 in this._vectors3) { effect.setVector3(name260, this._vectors3[name260]); } for (name260 in this._vectors4) { effect.setVector4(name260, this._vectors4[name260]); } for (name260 in this._quaternions) { effect.setQuaternion(name260, this._quaternions[name260]); } for (name260 in this._matrices) { effect.setMatrix(name260, this._matrices[name260]); } for (name260 in this._matrixArrays) { effect.setMatrices(name260, this._matrixArrays[name260]); } for (name260 in this._matrices3x3) { effect.setMatrix3x3(name260, this._matrices3x3[name260]); } for (name260 in this._matrices2x2) { effect.setMatrix2x2(name260, this._matrices2x2[name260]); } for (name260 in this._vectors2Arrays) { effect.setArray2(name260, this._vectors2Arrays[name260]); } for (name260 in this._vectors3Arrays) { effect.setArray3(name260, this._vectors3Arrays[name260]); } for (name260 in this._vectors4Arrays) { effect.setArray4(name260, this._vectors4Arrays[name260]); } for (name260 in this._quaternionsArrays) { effect.setArray4(name260, this._quaternionsArrays[name260]); } for (name260 in this._uniformBuffers) { const buffer = this._uniformBuffers[name260].getBuffer(); if (buffer) { effect.bindUniformBuffer(buffer, name260); } } const engineWebGPU = scene.getEngine(); const setExternalTexture = engineWebGPU.setExternalTexture; if (setExternalTexture) { for (name260 in this._externalTextures) { setExternalTexture.call(engineWebGPU, name260, this._externalTextures[name260]); } } const setTextureSampler = engineWebGPU.setTextureSampler; if (setTextureSampler) { for (name260 in this._textureSamplers) { setTextureSampler.call(engineWebGPU, name260, this._textureSamplers[name260]); } } const setStorageBuffer = engineWebGPU.setStorageBuffer; if (setStorageBuffer) { for (name260 in this._storageBuffers) { setStorageBuffer.call(engineWebGPU, name260, this._storageBuffers[name260]); } } } if (effect && mesh && (mustRebind || !this.isFrozen)) { BindMorphTargetParameters(mesh, effect); if (mesh.morphTargetManager && mesh.morphTargetManager.isUsingTextureForTargets) { mesh.morphTargetManager._bind(effect); } const bvaManager = mesh.bakedVertexAnimationManager; if (bvaManager && bvaManager.isEnabled) { const drawWrapper = storeEffectOnSubMeshes ? subMesh._drawWrapper : this._drawWrapper; mesh.bakedVertexAnimationManager?.bind(effect, !!drawWrapper._wasPreviouslyUsingInstances); } } this._afterBind(mesh, effect, subMesh); } /** * Gets the active textures from the material * @returns an array of textures */ getActiveTextures() { const activeTextures = super.getActiveTextures(); for (const name260 in this._textures) { activeTextures.push(this._textures[name260]); } for (const name260 in this._textureArrays) { const array = this._textureArrays[name260]; for (let index = 0; index < array.length; index++) { activeTextures.push(array[index]); } } return activeTextures; } /** * 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 */ hasTexture(texture) { if (super.hasTexture(texture)) { return true; } for (const name260 in this._textures) { if (this._textures[name260] === texture) { return true; } } for (const name260 in this._textureArrays) { const array = this._textureArrays[name260]; for (let index = 0; index < array.length; index++) { if (array[index] === texture) { return true; } } } return false; } /** * Makes a duplicate of the material, and gives it a new name * @param name defines the new name for the duplicated material * @returns the cloned material */ clone(name260) { const result = SerializationHelper.Clone(() => new _ShaderMaterial(name260, this.getScene(), this._shaderPath, this._options, this._storeEffectOnSubMeshes), this); result.name = name260; result.id = name260; if (typeof result._shaderPath === "object") { result._shaderPath = { ...result._shaderPath }; } this._options = { ...this._options }; const keys = Object.keys(this._options); for (const propName of keys) { const propValue = this._options[propName]; if (Array.isArray(propValue)) { this._options[propName] = propValue.slice(0); } } this.stencil.copyTo(result.stencil); for (const key in this._textures) { result.setTexture(key, this._textures[key]); } for (const key in this._textureArrays) { result.setTextureArray(key, this._textureArrays[key]); } for (const key in this._externalTextures) { result.setExternalTexture(key, this._externalTextures[key]); } for (const key in this._ints) { result.setInt(key, this._ints[key]); } for (const key in this._uints) { result.setUInt(key, this._uints[key]); } for (const key in this._floats) { result.setFloat(key, this._floats[key]); } for (const key in this._floatsArrays) { result.setFloats(key, this._floatsArrays[key]); } for (const key in this._colors3) { result.setColor3(key, this._colors3[key]); } for (const key in this._colors3Arrays) { result._colors3Arrays[key] = this._colors3Arrays[key]; } for (const key in this._colors4) { result.setColor4(key, this._colors4[key]); } for (const key in this._colors4Arrays) { result._colors4Arrays[key] = this._colors4Arrays[key]; } for (const key in this._vectors2) { result.setVector2(key, this._vectors2[key]); } for (const key in this._vectors3) { result.setVector3(key, this._vectors3[key]); } for (const key in this._vectors4) { result.setVector4(key, this._vectors4[key]); } for (const key in this._quaternions) { result.setQuaternion(key, this._quaternions[key]); } for (const key in this._quaternionsArrays) { result._quaternionsArrays[key] = this._quaternionsArrays[key]; } for (const key in this._matrices) { result.setMatrix(key, this._matrices[key]); } for (const key in this._matrixArrays) { result._matrixArrays[key] = this._matrixArrays[key].slice(); } for (const key in this._matrices3x3) { result.setMatrix3x3(key, this._matrices3x3[key]); } for (const key in this._matrices2x2) { result.setMatrix2x2(key, this._matrices2x2[key]); } for (const key in this._vectors2Arrays) { result.setArray2(key, this._vectors2Arrays[key]); } for (const key in this._vectors3Arrays) { result.setArray3(key, this._vectors3Arrays[key]); } for (const key in this._vectors4Arrays) { result.setArray4(key, this._vectors4Arrays[key]); } for (const key in this._uniformBuffers) { result.setUniformBuffer(key, this._uniformBuffers[key]); } for (const key in this._textureSamplers) { result.setTextureSampler(key, this._textureSamplers[key]); } for (const key in this._storageBuffers) { result.setStorageBuffer(key, this._storageBuffers[key]); } return result; } /** * 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 */ dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh) { if (forceDisposeTextures) { let name260; for (name260 in this._textures) { this._textures[name260].dispose(); } for (name260 in this._textureArrays) { const array = this._textureArrays[name260]; for (let index = 0; index < array.length; index++) { array[index].dispose(); } } } this._textures = {}; super.dispose(forceDisposeEffect, forceDisposeTextures, notBoundToMesh); } /** * Serializes this material in a JSON representation * @returns the serialized material object */ serialize() { const serializationObject = SerializationHelper.Serialize(this); serializationObject.customType = "BABYLON.ShaderMaterial"; serializationObject.uniqueId = this.uniqueId; serializationObject.options = this._options; serializationObject.shaderPath = this._shaderPath; serializationObject.storeEffectOnSubMeshes = this._storeEffectOnSubMeshes; let name260; serializationObject.stencil = this.stencil.serialize(); serializationObject.textures = {}; for (name260 in this._textures) { serializationObject.textures[name260] = this._textures[name260].serialize(); } serializationObject.textureArrays = {}; for (name260 in this._textureArrays) { serializationObject.textureArrays[name260] = []; const array = this._textureArrays[name260]; for (let index = 0; index < array.length; index++) { serializationObject.textureArrays[name260].push(array[index].serialize()); } } serializationObject.ints = {}; for (name260 in this._ints) { serializationObject.ints[name260] = this._ints[name260]; } serializationObject.uints = {}; for (name260 in this._uints) { serializationObject.uints[name260] = this._uints[name260]; } serializationObject.floats = {}; for (name260 in this._floats) { serializationObject.floats[name260] = this._floats[name260]; } serializationObject.floatsArrays = {}; for (name260 in this._floatsArrays) { serializationObject.floatsArrays[name260] = this._floatsArrays[name260]; } serializationObject.colors3 = {}; for (name260 in this._colors3) { const color3 = this._colors3[name260]; serializationObject.colors3[name260] = [color3.r, color3.g, color3.b]; } serializationObject.colors3Arrays = {}; for (name260 in this._colors3Arrays) { serializationObject.colors3Arrays[name260] = this._colors3Arrays[name260]; } serializationObject.colors4 = {}; for (name260 in this._colors4) { const color4 = this._colors4[name260]; serializationObject.colors4[name260] = [color4.r, color4.g, color4.b, color4.a]; } serializationObject.colors4Arrays = {}; for (name260 in this._colors4Arrays) { serializationObject.colors4Arrays[name260] = this._colors4Arrays[name260]; } serializationObject.vectors2 = {}; for (name260 in this._vectors2) { const v2 = this._vectors2[name260]; serializationObject.vectors2[name260] = [v2.x, v2.y]; } serializationObject.vectors3 = {}; for (name260 in this._vectors3) { const v3 = this._vectors3[name260]; serializationObject.vectors3[name260] = [v3.x, v3.y, v3.z]; } serializationObject.vectors4 = {}; for (name260 in this._vectors4) { const v4 = this._vectors4[name260]; serializationObject.vectors4[name260] = [v4.x, v4.y, v4.z, v4.w]; } serializationObject.quaternions = {}; for (name260 in this._quaternions) { serializationObject.quaternions[name260] = this._quaternions[name260].asArray(); } serializationObject.matrices = {}; for (name260 in this._matrices) { serializationObject.matrices[name260] = this._matrices[name260].asArray(); } serializationObject.matrixArray = {}; for (name260 in this._matrixArrays) { serializationObject.matrixArray[name260] = this._matrixArrays[name260]; } serializationObject.matrices3x3 = {}; for (name260 in this._matrices3x3) { serializationObject.matrices3x3[name260] = this._matrices3x3[name260]; } serializationObject.matrices2x2 = {}; for (name260 in this._matrices2x2) { serializationObject.matrices2x2[name260] = this._matrices2x2[name260]; } serializationObject.vectors2Arrays = {}; for (name260 in this._vectors2Arrays) { serializationObject.vectors2Arrays[name260] = this._vectors2Arrays[name260]; } serializationObject.vectors3Arrays = {}; for (name260 in this._vectors3Arrays) { serializationObject.vectors3Arrays[name260] = this._vectors3Arrays[name260]; } serializationObject.vectors4Arrays = {}; for (name260 in this._vectors4Arrays) { serializationObject.vectors4Arrays[name260] = this._vectors4Arrays[name260]; } serializationObject.quaternionsArrays = {}; for (name260 in this._quaternionsArrays) { serializationObject.quaternionsArrays[name260] = this._quaternionsArrays[name260]; } return serializationObject; } /** * Creates a shader material from parsed shader 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 material */ static Parse(source, scene, rootUrl) { const material = SerializationHelper.Parse(() => new _ShaderMaterial(source.name, scene, source.shaderPath, source.options, source.storeEffectOnSubMeshes), source, scene, rootUrl); let name260; if (source.stencil) { material.stencil.parse(source.stencil, scene, rootUrl); } for (name260 in source.textures) { material.setTexture(name260, Texture.Parse(source.textures[name260], scene, rootUrl)); } for (name260 in source.textureArrays) { const array = source.textureArrays[name260]; const textureArray = []; for (let index = 0; index < array.length; index++) { textureArray.push(Texture.Parse(array[index], scene, rootUrl)); } material.setTextureArray(name260, textureArray); } for (name260 in source.ints) { material.setInt(name260, source.ints[name260]); } for (name260 in source.uints) { material.setUInt(name260, source.uints[name260]); } for (name260 in source.floats) { material.setFloat(name260, source.floats[name260]); } for (name260 in source.floatsArrays) { material.setFloats(name260, source.floatsArrays[name260]); } for (name260 in source.colors3) { const color = source.colors3[name260]; material.setColor3(name260, { r: color[0], g: color[1], b: color[2] }); } for (name260 in source.colors3Arrays) { const colors = source.colors3Arrays[name260].reduce((arr, num, i) => { if (i % 3 === 0) { arr.push([num]); } else { arr[arr.length - 1].push(num); } return arr; }, []).map((color) => ({ r: color[0], g: color[1], b: color[2] })); material.setColor3Array(name260, colors); } for (name260 in source.colors4) { const color = source.colors4[name260]; material.setColor4(name260, { r: color[0], g: color[1], b: color[2], a: color[3] }); } for (name260 in source.colors4Arrays) { const colors = source.colors4Arrays[name260].reduce((arr, num, i) => { if (i % 4 === 0) { arr.push([num]); } else { arr[arr.length - 1].push(num); } return arr; }, []).map((color) => ({ r: color[0], g: color[1], b: color[2], a: color[3] })); material.setColor4Array(name260, colors); } for (name260 in source.vectors2) { const vector = source.vectors2[name260]; material.setVector2(name260, { x: vector[0], y: vector[1] }); } for (name260 in source.vectors3) { const vector = source.vectors3[name260]; material.setVector3(name260, { x: vector[0], y: vector[1], z: vector[2] }); } for (name260 in source.vectors4) { const vector = source.vectors4[name260]; material.setVector4(name260, { x: vector[0], y: vector[1], z: vector[2], w: vector[3] }); } for (name260 in source.quaternions) { material.setQuaternion(name260, Quaternion.FromArray(source.quaternions[name260])); } for (name260 in source.matrices) { material.setMatrix(name260, Matrix.FromArray(source.matrices[name260])); } for (name260 in source.matrixArray) { material._matrixArrays[name260] = new Float32Array(source.matrixArray[name260]); } for (name260 in source.matrices3x3) { material.setMatrix3x3(name260, source.matrices3x3[name260]); } for (name260 in source.matrices2x2) { material.setMatrix2x2(name260, source.matrices2x2[name260]); } for (name260 in source.vectors2Arrays) { material.setArray2(name260, source.vectors2Arrays[name260]); } for (name260 in source.vectors3Arrays) { material.setArray3(name260, source.vectors3Arrays[name260]); } for (name260 in source.vectors4Arrays) { material.setArray4(name260, source.vectors4Arrays[name260]); } for (name260 in source.quaternionsArrays) { material.setArray4(name260, source.quaternionsArrays[name260]); } return material; } /** * Creates a new ShaderMaterial from a snippet saved in a remote file * @param name defines the name of the ShaderMaterial to create (can be null or empty to use the one from the json data) * @param url defines the url to load from * @param scene defines the hosting scene * @param rootUrl defines the root URL to use to load textures and relative dependencies * @returns a promise that will resolve to the new ShaderMaterial */ static async ParseFromFileAsync(name260, url, scene, rootUrl = "") { return await new Promise((resolve, reject) => { const request = new WebRequest(); request.addEventListener("readystatechange", () => { if (request.readyState == 4) { if (request.status == 200) { const serializationObject = JSON.parse(request.responseText); const output = this.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl); if (name260) { output.name = name260; } resolve(output); } else { reject("Unable to load the ShaderMaterial"); } } }); request.open("GET", url); request.send(); }); } /** * Creates a ShaderMaterial from a snippet saved by the Inspector * @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 * @returns a promise that will resolve to the new ShaderMaterial */ static async ParseFromSnippetAsync(snippetId, scene, rootUrl = "") { return await new Promise((resolve, reject) => { const request = new WebRequest(); request.addEventListener("readystatechange", () => { if (request.readyState == 4) { if (request.status == 200) { const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); const serializationObject = JSON.parse(snippet.shaderMaterial); const output = this.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl); output.snippetId = snippetId; resolve(output); } else { reject("Unable to load the snippet " + snippetId); } } }); request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); request.send(); }); } }; ShaderMaterial.SnippetUrl = `https://snippet.babylonjs.com`; ShaderMaterial.CreateFromSnippetAsync = ShaderMaterial.ParseFromSnippetAsync; RegisterClass("BABYLON.ShaderMaterial", ShaderMaterial); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/spriteMap.fragment.js init_shaderStore(); init_fogFragmentDeclaration2(); init_logDepthDeclaration2(); init_logDepthFragment2(); init_fogFragment2(); var name252 = "spriteMapPixelShader"; var shader252 = `#ifdef LOGARITHMICDEPTH #extension GL_EXT_frag_depth : enable #endif #if defined(WEBGL2) || defined(WEBGPU) || defined(NATIVE) #define TEXTUREFUNC(s,c,l) texture2DLodEXT(s,c,l) #else #define TEXTUREFUNC(s,c,b) texture2D(s,c,b) #endif precision highp float;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform float spriteCount;uniform sampler2D spriteSheet;uniform vec2 spriteMapSize;uniform vec2 outputSize;uniform vec2 stageSize;uniform sampler2D frameMap;uniform sampler2D tileMaps[LAYERS];uniform sampler2D animationMap;uniform vec3 colorMul; #include #include float mt;const float fdStep=1.0*0.25;const float aFrameSteps=MAX_ANIMATION_FRAMES==0.0 ? 0.0 : 1.0/MAX_ANIMATION_FRAMES;mat4 getFrameData(float frameID) {float fX=frameID/spriteCount;return mat4( TEXTUREFUNC(frameMap,vec2(fX,0.0),0.0), TEXTUREFUNC(frameMap,vec2(fX,fdStep*1.0),0.0), TEXTUREFUNC(frameMap,vec2(fX,fdStep*2.0),0.0), vec4(0.0) );} void main() {vec4 color=vec4(0.0);vec2 tileUV=fract(tUV);vec2 tileID=floor(tUV);vec2 sheetUnits=1.0/spriteMapSize;float spriteUnits=1.0/spriteCount;vec2 stageUnits=1.0/stageSize;for(int i=0; i0.0) {mt=mod(time*animationData.z,1.0);for(float f=0.0; fmt) {frameID=animationData.x;break;} animationData=TEXTUREFUNC(animationMap,vec2((frameID+0.5)/spriteCount,aFrameSteps*f),0.0);}} mat4 frameData=getFrameData(frameID+0.5);vec2 frameSize=(frameData[0].zw)/spriteMapSize;vec2 offset=frameData[0].xy*sheetUnits;vec2 ratio=frameData[2].xy/frameData[0].zw; #ifdef FR_CW if (frameData[2].z==1.0) {tileUV.xy=tileUV.yx;} else {tileUV.xy=fract(tUV).xy;} #ifdef FLIPU tileUV.y=1.0-tileUV.y; #endif #else if (frameData[2].z==1.0) { #ifdef FLIPU tileUV.y=1.0-tileUV.y; #endif tileUV.xy=tileUV.yx;} else {tileUV.xy=fract(tUV).xy; #ifdef FLIPU tileUV.y=1.0-tileUV.y; #endif } #endif vec4 nc=TEXTUREFUNC(spriteSheet,tileUV*frameSize+offset,0.0);if (i==0) {color=nc;} else {float alpha=min(color.a+nc.a,1.0);vec3 mixed=mix(color.xyz,nc.xyz,nc.a);color=vec4(mixed,alpha);}} color.xyz*=colorMul; #include #include gl_FragColor=color;}`; if (!ShaderStore.ShadersStore[name252]) { ShaderStore.ShadersStore[name252] = shader252; } var spriteMapPixelShader = { name: name252, shader: shader252 }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Shaders/spriteMap.vertex.js init_shaderStore(); init_fogVertexDeclaration2(); init_logDepthDeclaration2(); init_logDepthVertex2(); var name253 = "spriteMapVertexShader"; var shader253 = `precision highp float;attribute vec3 position;attribute vec3 normal;attribute vec2 uv;varying vec3 vPosition;varying vec2 vUV;varying vec2 tUV;uniform float time;uniform mat4 world;uniform mat4 view;uniform mat4 projection;uniform vec2 stageSize;uniform float stageScale; #include #include void main() {vec4 p=vec4( position,1. );vPosition=p.xyz;vUV=uv;tUV=uv*stageSize; vec3 viewPos=(view*world*p).xyz; gl_Position=projection*vec4(viewPos,1.0); #ifdef FOG vFogDistance=viewPos; #endif #include }`; if (!ShaderStore.ShadersStore[name253]) { ShaderStore.ShadersStore[name253] = shader253; } var spriteMapVertexShader = { name: name253, shader: shader253 }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Sprites/spriteMap.js init_math_vector(); init_texture(); init_effect(); var SpriteMapFrameRotationDirection; (function(SpriteMapFrameRotationDirection2) { SpriteMapFrameRotationDirection2[SpriteMapFrameRotationDirection2["CCW"] = 0] = "CCW"; SpriteMapFrameRotationDirection2[SpriteMapFrameRotationDirection2["CW"] = 1] = "CW"; })(SpriteMapFrameRotationDirection || (SpriteMapFrameRotationDirection = {})); var SpriteMap = class { static { __name(this, "SpriteMap"); } /** Returns the Number of Sprites in the System */ get spriteCount() { return this.sprites.length; } /** Returns the Position of Output Plane*/ get position() { return this._output.position; } /** Returns the Position of Output Plane*/ set position(v) { this._output.position = v; } /** Returns the Rotation of Output Plane*/ get rotation() { return this._output.rotation; } /** Returns the Rotation of Output Plane*/ set rotation(v) { this._output.rotation = v; } /** Sets the AnimationMap*/ get animationMap() { return this._animationMap; } /** Sets the AnimationMap*/ set animationMap(v) { const buffer = v._texture._bufferView; const am = this._createTileAnimationBuffer(buffer); this._animationMap.dispose(); this._animationMap = am; this._material.setTexture("animationMap", this._animationMap); } /** Gets or sets a boolean indicating if the sprite map must consider scene fog when rendering */ get fogEnabled() { return this._material.fogEnabled; } set fogEnabled(value) { this._material.fogEnabled = value; } /** Gets or sets a boolean indicating if the sprite map must use logarithmic depth when rendering */ get useLogarithmicDepth() { return this._material.useLogarithmicDepth; } set useLogarithmicDepth(value) { this._material.useLogarithmicDepth = value; } /** * Creates a new SpriteMap * @param name defines the SpriteMaps Name * @param atlasJSON is the JSON file that controls the Sprites Frames and Meta * @param spriteSheet is the Texture that the Sprites are on. * @param options a basic deployment configuration * @param scene The Scene that the map is deployed on */ constructor(name260, atlasJSON, spriteSheet, options, scene) { this.name = name260; this.sprites = []; this.atlasJSON = atlasJSON; this.sprites = this.atlasJSON["frames"]; this.spriteSheet = spriteSheet; this.options = options; options.stageSize = options.stageSize || new Vector2(1, 1); options.outputSize = options.outputSize || options.stageSize; options.outputPosition = options.outputPosition || Vector3.Zero(); options.outputRotation = options.outputRotation || Vector3.Zero(); options.layerCount = options.layerCount || 1; options.maxAnimationFrames = options.maxAnimationFrames || 0; options.baseTile = options.baseTile || 0; options.flipU = options.flipU || false; options.colorMultiply = options.colorMultiply || new Vector3(1, 1, 1); this._scene = scene; this._frameMap = this._createFrameBuffer(); this._tileMaps = []; for (let i = 0; i < options.layerCount; i++) { this._tileMaps.push(this._createTileBuffer(null, i)); } this._animationMap = this._createTileAnimationBuffer(null); const defines = []; defines.push("#define LAYERS " + options.layerCount); if (options?.frameRotationDirection === SpriteMapFrameRotationDirection.CW) { defines.push("#define FR_CW"); } if (options.flipU) { defines.push("#define FLIPU"); } defines.push(`#define MAX_ANIMATION_FRAMES ${options.maxAnimationFrames}.0`); const shaderString = Effect.ShadersStore["spriteMapPixelShader"]; let layerSampleString; if (!scene.getEngine()._features.supportSwitchCaseInShader) { layerSampleString = ""; for (let i = 0; i < options.layerCount; i++) { layerSampleString += `if (${i} == i) { frameID = texture2D(tileMaps[${i}], (tileID + 0.5) / stageSize, 0.).x; }`; } } else { layerSampleString = "switch(i) {"; for (let i = 0; i < options.layerCount; i++) { layerSampleString += "case " + i + " : frameID = texture(tileMaps[" + i + "], (tileID + 0.5) / stageSize, 0.).x;"; layerSampleString += "break;"; } layerSampleString += "}"; } Effect.ShadersStore["spriteMap" + this.name + "PixelShader"] = shaderString.replace("#define LAYER_ID_SWITCH", layerSampleString); this._material = new ShaderMaterial("spriteMap:" + this.name, this._scene, { vertex: "spriteMap", fragment: "spriteMap" + this.name }, { defines, attributes: ["position", "normal", "uv"], uniforms: [ "world", "view", "projection", "time", "stageSize", "outputSize", "spriteMapSize", "spriteCount", "time", "colorMul", "mousePosition", "curTile", "flipU" ], samplers: ["spriteSheet", "frameMap", "tileMaps", "animationMap"], needAlphaBlending: true }); this._time = 0; this._material.setFloat("spriteCount", this.spriteCount); this._material.setVector2("stageSize", options.stageSize); this._material.setVector2("outputSize", options.outputSize); this._material.setTexture("spriteSheet", this.spriteSheet); this._material.setVector2("spriteMapSize", new Vector2(1, 1)); this._material.setVector3("colorMul", options.colorMultiply); let tickSave = 0; const bindSpriteTexture = /* @__PURE__ */ __name(() => { if (this.spriteSheet && this.spriteSheet.isReady()) { if (this.spriteSheet._texture) { this._material.setVector2("spriteMapSize", new Vector2(this.spriteSheet._texture.baseWidth || 1, this.spriteSheet._texture.baseHeight || 1)); return; } } if (tickSave < 100) { setTimeout(() => { tickSave++; bindSpriteTexture(); }, 100); } }, "bindSpriteTexture"); bindSpriteTexture(); this._material.setVector3("colorMul", options.colorMultiply); this._material.setTexture("frameMap", this._frameMap); this._material.setTextureArray("tileMaps", this._tileMaps); this._material.setTexture("animationMap", this._animationMap); this._material.setFloat("time", this._time); this._output = CreatePlane(name260 + ":output", { size: 1, updatable: true }, scene); this._output.scaling.x = options.outputSize.x; this._output.scaling.y = options.outputSize.y; this.position = options.outputPosition; this.rotation = options.outputRotation; const obfunction = /* @__PURE__ */ __name(() => { this._time += this._scene.getEngine().getDeltaTime(); this._material.setFloat("time", this._time); }, "obfunction"); this._scene.onBeforeRenderObservable.add(obfunction); this._output.material = this._material; } /** * Returns the index of the frame for a given filename * @param name filename of the frame * @returns index of the frame */ getTileIdxByName(name260) { const idx = this.atlasJSON.frames.findIndex((f) => f.filename === name260); return idx; } /** * Returns tileID location * @returns Vector2 the cell position ID */ // eslint-disable-next-line @typescript-eslint/naming-convention getTileID() { const p = this.getMousePosition(); p.multiplyInPlace(this.options.stageSize || Vector2.Zero()); p.x = Math.floor(p.x); p.y = Math.floor(p.y); return p; } /** * Gets the UV location of the mouse over the SpriteMap. * @returns Vector2 the UV position of the mouse interaction */ getMousePosition() { const out = this._output; const pickinfo = this._scene.pick(this._scene.pointerX, this._scene.pointerY, (mesh) => { if (mesh !== out) { return false; } return true; }); if (!pickinfo || !pickinfo.hit || !pickinfo.getTextureCoordinates) { return new Vector2(-1, -1); } const coords = pickinfo.getTextureCoordinates(); if (coords) { return coords; } return new Vector2(-1, -1); } /** * Creates the "frame" texture Buffer * ------------------------------------- * Structure of frames * "filename": "Falling-Water-2.png", * "frame": {"x":69,"y":103,"w":24,"h":32}, * "rotated": true, * "trimmed": true, * "spriteSourceSize": {"x":4,"y":0,"w":24,"h":32}, * "sourceSize": {"w":32,"h":32} * @returns RawTexture of the frameMap */ _createFrameBuffer() { const data = []; for (let i = 0; i < this.spriteCount; i++) { data.push(0, 0, 0, 0); data.push(0, 0, 0, 0); data.push(0, 0, 0, 0); data.push(0, 0, 0, 0); } for (let i = 0; i < this.spriteCount; i++) { const f = this.sprites[i]["frame"]; const sss = this.sprites[i]["spriteSourceSize"]; const ss = this.sprites[i]["sourceSize"]; const r = this.sprites[i]["rotated"] ? 1 : 0; const t2 = this.sprites[i]["trimmed"] ? 1 : 0; data[i * 4] = f.x; data[i * 4 + 1] = f.y; data[i * 4 + 2] = f.w; data[i * 4 + 3] = f.h; data[i * 4 + this.spriteCount * 4] = sss.x; data[i * 4 + 1 + this.spriteCount * 4] = sss.y; data[i * 4 + 3 + this.spriteCount * 4] = sss.h; data[i * 4 + this.spriteCount * 8] = ss.w; data[i * 4 + 1 + this.spriteCount * 8] = ss.h; data[i * 4 + 2 + this.spriteCount * 8] = r; data[i * 4 + 3 + this.spriteCount * 8] = t2; } const floatArray = new Float32Array(data); const t = RawTexture.CreateRGBATexture(floatArray, this.spriteCount, 4, this._scene, false, false, Texture.NEAREST_NEAREST, 1); return t; } /** * Creates the tileMap texture Buffer * @param buffer normally and array of numbers, or a false to generate from scratch * @param _layer indicates what layer for a logic trigger dealing with the baseTile. The system uses this * @returns RawTexture of the tileMap */ _createTileBuffer(buffer, _layer = 0) { let data = []; const _ty = this.options.stageSize.y || 0; const _tx = this.options.stageSize.x || 0; if (!buffer) { let bt = this.options.baseTile; if (_layer != 0) { bt = 0; } for (let y = 0; y < _ty; y++) { for (let x = 0; x < _tx * 4; x += 4) { data.push(bt, 0, 0, 0); } } } else { data = buffer; } const floatArray = new Float32Array(data); const t = RawTexture.CreateRGBATexture(floatArray, _tx, _ty, this._scene, false, false, Texture.NEAREST_NEAREST, 1); return t; } /** * Modifies the data of the tileMaps * @param _layer is the ID of the layer you want to edit on the SpriteMap * @param pos is the iVector2 Coordinates of the Tile * @param tile The SpriteIndex of the new Tile */ changeTiles(_layer = 0, pos, tile = 0) { const buffer = this._tileMaps[_layer]._texture._bufferView; if (buffer === null) { return; } let p = []; if (pos instanceof Vector2) { p.push(pos); } else { p = pos; } const _tx = this.options.stageSize.x || 0; for (let i = 0; i < p.length; i++) { const _p = p[i]; _p.x = Math.floor(_p.x); _p.y = Math.floor(_p.y); const id = _p.x * 4 + _p.y * (_tx * 4); buffer[id] = tile; } const t = this._createTileBuffer(buffer); this._tileMaps[_layer].dispose(); this._tileMaps[_layer] = t; this._material.setTextureArray("tileMap", this._tileMaps); } /** * Creates the animationMap texture Buffer * @param buffer normally and array of numbers, or a false to generate from scratch * @returns RawTexture of the animationMap */ _createTileAnimationBuffer(buffer) { const data = []; let floatArray; if (!buffer) { for (let i = 0; i < this.spriteCount; i++) { data.push(0, 0, 0, 0); let count = 1; while (count < (this.options.maxAnimationFrames || 4)) { data.push(0, 0, 0, 0); count++; } } floatArray = new Float32Array(data); } else { floatArray = buffer; } const t = RawTexture.CreateRGBATexture(floatArray, this.spriteCount, this.options.maxAnimationFrames || 4, this._scene, false, false, Texture.NEAREST_NEAREST, 1); return t; } /** * Modifies the data of the animationMap * @param cellID is the Index of the Sprite * @param _frame is the target Animation frame * @param toCell is the Target Index of the next frame of the animation * @param time is a value between 0-1 that is the trigger for when the frame should change tiles * @param speed is a global scalar of the time variable on the map. */ addAnimationToTile(cellID = 0, _frame = 0, toCell = 0, time = 0, speed = 1) { const buffer = this._animationMap._texture._bufferView; const id = cellID * 4 + this.spriteCount * 4 * _frame; if (!buffer) { return; } buffer[id] = toCell; buffer[id + 1] = time; buffer[id + 2] = speed; const t = this._createTileAnimationBuffer(buffer); this._animationMap.dispose(); this._animationMap = t; this._material.setTexture("animationMap", this._animationMap); } /** * Exports the .tilemaps file */ saveTileMaps() { let maps = ""; for (let i = 0; i < this._tileMaps.length; i++) { if (i > 0) { maps += "\n\r"; } maps += this._tileMaps[i]._texture._bufferView.toString(); } const hiddenElement = document.createElement("a"); hiddenElement.href = "data:octet/stream;charset=utf-8," + encodeURI(maps); hiddenElement.target = "_blank"; hiddenElement.download = this.name + ".tilemaps"; hiddenElement.click(); hiddenElement.remove(); } /** * Imports the .tilemaps file * @param url of the .tilemaps file */ loadTileMaps(url) { const xhr = new XMLHttpRequest(); xhr.open("GET", url); const _lc = this.options.layerCount || 0; xhr.onload = () => { const data = xhr.response.split("\n\r"); for (let i = 0; i < _lc; i++) { const d = data[i].split(",").map(Number); const t = this._createTileBuffer(d); this._tileMaps[i].dispose(); this._tileMaps[i] = t; } this._material.setTextureArray("tileMap", this._tileMaps); }; xhr.send(); } /** * Release associated resources */ dispose() { this._output.dispose(); this._material.dispose(); this._animationMap.dispose(); for (const tm of this._tileMaps) { tm.dispose(); } this._frameMap.dispose(); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/tools/sprite.js function normalizeAtlasJson(data) { if (!Array.isArray(data.frames)) { const frames = []; for (const key of Object.keys(data.frames)) { frames.push({ filename: key, ...data.frames[key] }); } data.frames = frames; } } __name(normalizeAtlasJson, "normalizeAtlasJson"); function playSpriteAnimationFromName(sprite, animationName, onAnimationEnd) { const spriteAnimations = sprite.metadata?.spriteAnimations ?? []; const animation = spriteAnimations.find((a) => a.name === animationName); if (!animation) { return console.error(`Animation with name "${animationName}" not found on sprite.`); } sprite.playAnimation(animation.from, animation.to, animation.loop, animation.delay, onAnimationEnd); } __name(playSpriteAnimationFromName, "playSpriteAnimationFromName"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/loading/sprite-map.js init_tools(); init_engine(); init_webRequest(); init_texture(); init_math_vector(); var registered4 = false; function registerSpriteMapParser() { if (registered4) { return; } registered4 = true; AddParser("SpriteMapNode", (parsedData, scene, container, rootUrl) => { parsedData.transformNodes?.forEach((transformNode) => { if (!transformNode.isSpriteMap) { return; } const instance = container.transformNodes?.find((t) => t.id === transformNode.id); if (!instance) { return; } instance.isSpriteMap = transformNode.isSpriteMap; const atlasJsonAbsolutePath = `${rootUrl}${transformNode.atlasJsonRelativePath}`; scene.addPendingData(atlasJsonAbsolutePath); const atlasRequest = new WebRequest(); atlasRequest.open("GET", atlasJsonAbsolutePath); atlasRequest.send(); atlasRequest.addEventListener("load", () => { scene.removePendingData(atlasJsonAbsolutePath); const atlasJson = JSON.parse(atlasRequest.responseText); normalizeAtlasJson(atlasJson); const imagePath = `${Tools.GetFolderPath(atlasJsonAbsolutePath)}${atlasJson.meta.image}`; const spritesheet = new Texture(imagePath, scene, false, false, Texture.NEAREST_NEAREST, null, null, null, false, Engine.TEXTUREFORMAT_RGBA); const spriteMap = new SpriteMap(instance.name, atlasJson, spritesheet, { layerCount: transformNode.options.layerCount, stageSize: Vector2.FromArray(transformNode.options.stageSize ?? [10, 1]), outputSize: Vector2.FromArray(transformNode.options.outputSize ?? [100, 100]), colorMultiply: Vector3.FromArray(transformNode.options.colorMultiply ?? [1, 1, 1]), flipU: true }, scene); transformNode.tiles.forEach((tile) => { for (let x = 0, lenX = tile.repeatCount.x + 1; x < lenX; ++x) { for (let y = 0, lenY = tile.repeatCount.y + 1; y < lenY; ++y) { const offsetX = x * (tile.repeatOffset.x + 1); const offsetY = y * (tile.repeatOffset.y + 1); spriteMap.changeTiles(tile.layer, new Vector2(tile.position.x + offsetX, (spriteMap.options.stageSize?.y ?? 0) - 1 - tile.position.y - offsetY), tile.tile); } } }); const outputPlane = spriteMap["_output"]; outputPlane.parent = instance; instance.spriteMap = spriteMap; }); }); }); } __name(registerSpriteMapParser, "registerSpriteMapParser"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Sprites/thinSprite.js var ThinSprite = class { static { __name(this, "ThinSprite"); } /** * Returns a boolean indicating if the animation is started */ get animationStarted() { return this._animationStarted; } /** Gets the initial key for the animation (setting it will restart the animation) */ get fromIndex() { return this._fromIndex; } /** Gets or sets the end key for the animation (setting it will restart the animation) */ get toIndex() { return this._toIndex; } /** Gets or sets a boolean indicating if the animation is looping (setting it will restart the animation) */ get loopAnimation() { return this._loopAnimation; } /** Gets or sets the delay between cell changes (setting it will restart the animation) */ get delay() { return Math.max(this._delay, 1); } /** * Creates a new Thin Sprite */ constructor() { this.width = 1; this.height = 1; this.angle = 0; this.invertU = false; this.invertV = false; this.isVisible = true; this._animationStarted = false; this._loopAnimation = false; this._fromIndex = 0; this._toIndex = 0; this._delay = 0; this._direction = 1; this._time = 0; this._onBaseAnimationEnd = null; this.position = { x: 1, y: 1, z: 1 }; this.color = { r: 1, g: 1, b: 1, a: 1 }; } /** * Starts an animation * @param from defines the initial key * @param to defines the end key * @param loop defines if the animation must loop * @param delay defines the start delay (in ms) * @param onAnimationEnd defines a callback for when the animation ends */ playAnimation(from, to, loop, delay, onAnimationEnd) { this._fromIndex = from; this._toIndex = to; this._loopAnimation = loop; this._delay = delay || 1; this._animationStarted = true; this._onBaseAnimationEnd = onAnimationEnd; if (from < to) { this._direction = 1; } else { this._direction = -1; this._toIndex = from; this._fromIndex = to; } this.cellIndex = from; this._time = 0; } /** Stops current animation (if any) */ stopAnimation() { this._animationStarted = false; } /** * @internal */ _animate(deltaTime) { if (!this._animationStarted) { return; } this._time += deltaTime; if (this._time > this._delay) { this._time = this._time % this._delay; this.cellIndex += this._direction; if (this._direction > 0 && this.cellIndex > this._toIndex || this._direction < 0 && this.cellIndex < this._fromIndex) { if (this._loopAnimation) { this.cellIndex = this._direction > 0 ? this._fromIndex : this._toIndex; } else { this.cellIndex = this._toIndex; this._animationStarted = false; if (this._onBaseAnimationEnd) { this._onBaseAnimationEnd(); } } } } } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Sprites/sprite.js init_math_vector(); init_math_color(); init_observable(); var Sprite = class _Sprite extends ThinSprite { static { __name(this, "Sprite"); } /** * Gets or sets the sprite size */ get size() { return this.width; } set size(value) { this.width = value; this.height = value; } /** * Gets the manager of this sprite */ get manager() { return this._manager; } /** * Creates a new Sprite * @param name defines the name * @param manager defines the manager */ constructor(name260, manager) { super(); this.name = name260; this.animations = new Array(); this.isPickable = false; this.useAlphaForPicking = false; this.onDisposeObservable = new Observable(); this._onAnimationEnd = null; this._endAnimation = () => { if (this._onAnimationEnd) { this._onAnimationEnd(); } if (this.disposeWhenFinishedAnimating) { this.dispose(); } }; this.color = new Color4(1, 1, 1, 1); this.position = Vector3.Zero(); this._manager = manager; this._manager.sprites.push(this); this.uniqueId = this._manager.scene.getUniqueId(); } /** * Returns the string "Sprite" * @returns "Sprite" */ getClassName() { return "Sprite"; } /** Gets or sets the initial key for the animation (setting it will restart the animation) */ get fromIndex() { return this._fromIndex; } set fromIndex(value) { this.playAnimation(value, this._toIndex, this._loopAnimation, this._delay, this._onAnimationEnd); } /** Gets or sets the end key for the animation (setting it will restart the animation) */ get toIndex() { return this._toIndex; } set toIndex(value) { this.playAnimation(this._fromIndex, value, this._loopAnimation, this._delay, this._onAnimationEnd); } /** Gets or sets a boolean indicating if the animation is looping (setting it will restart the animation) */ get loopAnimation() { return this._loopAnimation; } set loopAnimation(value) { this.playAnimation(this._fromIndex, this._toIndex, value, this._delay, this._onAnimationEnd); } /** Gets or sets the delay between cell changes (setting it will restart the animation) */ get delay() { return Math.max(this._delay, 1); } set delay(value) { this.playAnimation(this._fromIndex, this._toIndex, this._loopAnimation, value, this._onAnimationEnd); } /** * Starts an animation * @param from defines the initial key * @param to defines the end key * @param loop defines if the animation must loop * @param delay defines the start delay (in ms) * @param onAnimationEnd defines a callback to call when animation ends */ playAnimation(from, to, loop, delay, onAnimationEnd = null) { this._onAnimationEnd = onAnimationEnd; super.playAnimation(from, to, loop, delay, this._endAnimation); } /** Release associated resources */ dispose() { for (let i = 0; i < this._manager.sprites.length; i++) { if (this._manager.sprites[i] == this) { this._manager.sprites.splice(i, 1); } } this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); } /** * Serializes the sprite to a JSON object * @returns the JSON object */ serialize() { const serializationObject = {}; serializationObject.name = this.name; serializationObject.position = this.position.asArray(); serializationObject.color = this.color.asArray(); serializationObject.width = this.width; serializationObject.height = this.height; serializationObject.angle = this.angle; serializationObject.cellIndex = this.cellIndex; serializationObject.cellRef = this.cellRef; serializationObject.invertU = this.invertU; serializationObject.invertV = this.invertV; serializationObject.disposeWhenFinishedAnimating = this.disposeWhenFinishedAnimating; serializationObject.isPickable = this.isPickable; serializationObject.isVisible = this.isVisible; serializationObject.useAlphaForPicking = this.useAlphaForPicking; serializationObject.animationStarted = this.animationStarted; serializationObject.fromIndex = this.fromIndex; serializationObject.toIndex = this.toIndex; serializationObject.loopAnimation = this.loopAnimation; serializationObject.delay = this.delay; return serializationObject; } /** * Parses a JSON object to create a new sprite * @param parsedSprite The JSON object to parse * @param manager defines the hosting manager * @returns the new sprite */ static Parse(parsedSprite, manager) { const sprite = new _Sprite(parsedSprite.name, manager); sprite.position = Vector3.FromArray(parsedSprite.position); sprite.color = Color4.FromArray(parsedSprite.color); sprite.width = parsedSprite.width; sprite.height = parsedSprite.height; sprite.angle = parsedSprite.angle; sprite.cellIndex = parsedSprite.cellIndex; sprite.cellRef = parsedSprite.cellRef; sprite.invertU = parsedSprite.invertU; sprite.invertV = parsedSprite.invertV; sprite.disposeWhenFinishedAnimating = parsedSprite.disposeWhenFinishedAnimating; sprite.isPickable = parsedSprite.isPickable; sprite.isVisible = parsedSprite.isVisible; sprite.useAlphaForPicking = parsedSprite.useAlphaForPicking; sprite._fromIndex = parsedSprite.fromIndex; sprite._toIndex = parsedSprite.toIndex; sprite._loopAnimation = parsedSprite.loopAnimation; sprite._delay = parsedSprite.delay; if (parsedSprite.animationStarted) { sprite.playAnimation(sprite.fromIndex, sprite.toIndex, sprite.loopAnimation, sprite.delay); } return sprite; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Culling/ray.core.js init_math_constants(); init_math_vector(); init_arrayTools(); init_pickingInfo(); init_engineStore(); init_import_helper(); var PickingCustomization = { internalPickerForMesh: void 0 }; var Ray = class _Ray { static { __name(this, "Ray"); } /** * Creates a new ray * @param origin origin point * @param direction direction * @param length length of the ray * @param epsilon The epsilon value to use when calculating the ray/triangle intersection (default: Epsilon from math constants) */ constructor(origin, direction, length = Number.MAX_VALUE, epsilon = Epsilon) { this.origin = origin; this.direction = direction; this.length = length; this.epsilon = epsilon; } // Methods /** * Clone the current ray * @returns a new ray */ clone() { return new _Ray(this.origin.clone(), this.direction.clone(), this.length); } /** * Checks if the ray intersects a box * This does not account for the ray length 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 */ intersectsBoxMinMax(minimum, maximum, intersectionTreshold = 0) { const newMinimum = _Ray._TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold); const newMaximum = _Ray._TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold); let d = 0; let maxValue = Number.MAX_VALUE; let inv; let min; let max; let temp; if (Math.abs(this.direction.x) < 1e-7) { if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) { return false; } } else { inv = 1 / 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) < 1e-7) { if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) { return false; } } else { inv = 1 / 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) < 1e-7) { if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) { return false; } } else { inv = 1 / 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 length 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 */ intersectsBox(box, 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 */ intersectsSphere(sphere, intersectionTreshold = 0) { const x = sphere.center.x - this.origin.x; const y = sphere.center.y - this.origin.y; const z = sphere.center.z - this.origin.z; const pyth = x * x + y * y + z * z; const radius = sphere.radius + intersectionTreshold; const rr = radius * radius; if (pyth <= rr) { return true; } const dot = x * this.direction.x + y * this.direction.y + z * this.direction.z; if (dot < 0) { return false; } const 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 */ intersectsTriangle(vertex0, vertex1, vertex2) { const edge1 = _Ray._TmpVector3[0]; const edge2 = _Ray._TmpVector3[1]; const pvec = _Ray._TmpVector3[2]; const tvec = _Ray._TmpVector3[3]; const qvec = _Ray._TmpVector3[4]; vertex1.subtractToRef(vertex0, edge1); vertex2.subtractToRef(vertex0, edge2); Vector3.CrossToRef(this.direction, edge2, pvec); const det = Vector3.Dot(edge1, pvec); if (det === 0) { return null; } const invdet = 1 / det; this.origin.subtractToRef(vertex0, tvec); const bv = Vector3.Dot(tvec, pvec) * invdet; if (bv < -this.epsilon || bv > 1 + this.epsilon) { return null; } Vector3.CrossToRef(tvec, edge1, qvec); const bw = Vector3.Dot(this.direction, qvec) * invdet; if (bw < -this.epsilon || bv + bw > 1 + this.epsilon) { return null; } const distance = Vector3.Dot(edge2, qvec) * invdet; if (distance > this.length) { return null; } return new 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 */ intersectsPlane(plane) { let distance; const result1 = Vector3.Dot(plane.normal, this.direction); if (Math.abs(result1) < 999999997475243e-21) { return null; } else { const result2 = Vector3.Dot(plane.normal, this.origin); distance = (-plane.d - result2) / result1; if (distance < 0) { if (distance < -999999997475243e-21) { 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. */ intersectsAxis(axis, offset = 0) { switch (axis) { case "y": { const t = (this.origin.y - offset) / this.direction.y; if (t > 0) { return null; } return new Vector3(this.origin.x + this.direction.x * -t, offset, this.origin.z + this.direction.z * -t); } case "x": { const t = (this.origin.x - offset) / this.direction.x; if (t > 0) { return null; } return new Vector3(offset, this.origin.y + this.direction.y * -t, this.origin.z + this.direction.z * -t); } case "z": { const t = (this.origin.z - offset) / this.direction.z; if (t > 0) { return null; } return new 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. The ray is defined in WORLD space. A mesh triangle can be picked both from its front and back sides, * irrespective of orientation. * @param mesh the mesh to check * @param fastCheck defines if the first intersection will be used (and not the closest) * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected * @param onlyBoundingInfo defines a boolean indicating if picking should only happen using bounding info (false by default) * @param worldToUse defines the world matrix to use to get the world coordinate of the intersection point * @param skipBoundingInfo a boolean indicating if we should skip the bounding info check * @returns picking info of the intersection */ intersectsMesh(mesh, fastCheck, trianglePredicate, onlyBoundingInfo = false, worldToUse, skipBoundingInfo = false) { const tm = 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, trianglePredicate, onlyBoundingInfo, worldToUse, skipBoundingInfo); } /** * 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 */ intersectsMeshes(meshes, fastCheck, results) { if (results) { results.length = 0; } else { results = []; } for (let i = 0; i < meshes.length; i++) { const pickInfo = this.intersectsMesh(meshes[i], fastCheck); if (pickInfo.hit) { results.push(pickInfo); } } results.sort(this._comparePickingInfo); return results; } _comparePickingInfo(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 within 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 * @returns the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection */ intersectionSegment(sega, segb, threshold) { const o = this.origin; const u = TmpVectors.Vector3[0]; const rsegb = TmpVectors.Vector3[1]; const v = TmpVectors.Vector3[2]; const w = TmpVectors.Vector3[3]; segb.subtractToRef(sega, u); this.direction.scaleToRef(_Ray._Rayl, v); o.addToRef(v, rsegb); sega.subtractToRef(o, w); const a = Vector3.Dot(u, u); const b = Vector3.Dot(u, v); const c = Vector3.Dot(v, v); const d = Vector3.Dot(u, w); const e = Vector3.Dot(v, w); const discriminant = a * c - b * b; let sN, sD = discriminant; let tN, tD = discriminant; if (discriminant < _Ray._Smallnum) { sN = 0; sD = 1; tN = e; tD = c; } else { sN = b * e - c * d; tN = a * e - b * d; if (sN < 0) { sN = 0; tN = e; tD = c; } else if (sN > sD) { sN = sD; tN = e + b; tD = c; } } if (tN < 0) { tN = 0; if (-d < 0) { sN = 0; } else if (-d > a) { sN = sD; } else { sN = -d; sD = a; } } else if (tN > tD) { tN = tD; if (-d + b < 0) { sN = 0; } else if (-d + b > a) { sN = sD; } else { sN = -d + b; sD = a; } } const sc = Math.abs(sN) < _Ray._Smallnum ? 0 : sN / sD; const tc = Math.abs(tN) < _Ray._Smallnum ? 0 : tN / tD; const qtc = TmpVectors.Vector3[4]; v.scaleToRef(tc, qtc); const qsc = TmpVectors.Vector3[5]; u.scaleToRef(sc, qsc); qsc.addInPlace(w); const dP = TmpVectors.Vector3[6]; qsc.subtractToRef(qtc, dP); const isIntersected = tc > 0 && tc <= this.length && dP.lengthSquared() < threshold * threshold; 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 * @param enableDistantPicking defines if picking should handle large values for mesh position/scaling (false by default) * @returns this ray updated */ update(x, y, viewportWidth, viewportHeight, world, view, projection, enableDistantPicking = false) { if (enableDistantPicking) { if (!_Ray._RayDistant) { _Ray._RayDistant = _Ray.Zero(); } _Ray._RayDistant.unprojectRayToRef(x, y, viewportWidth, viewportHeight, Matrix.IdentityReadOnly, view, projection); const tm = TmpVectors.Matrix[0]; world.invertToRef(tm); _Ray.TransformToRef(_Ray._RayDistant, tm, this); } else { 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 */ static Zero() { return new _Ray(Vector3.Zero(), 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 */ static CreateNew(x, y, viewportWidth, viewportHeight, world, view, projection) { const 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 */ static CreateNewFromTo(origin, end, world = Matrix.IdentityReadOnly) { const result = new _Ray(new Vector3(0, 0, 0), new Vector3(0, 0, 0)); return _Ray.CreateFromToToRef(origin, end, result, world); } /** * Function will update a 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 result the object to store the result * @param world a matrix to transform the ray to. Default is the identity matrix. * @returns the ref ray */ static CreateFromToToRef(origin, end, result, world = Matrix.IdentityReadOnly) { result.origin.copyFrom(origin); const direction = end.subtractToRef(origin, result.direction); const length = Math.sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); result.length = length; result.direction.normalize(); return _Ray.TransformToRef(result, world, result); } /** * Transforms a ray by a matrix * @param ray ray to transform * @param matrix matrix to apply * @returns the resulting new ray */ static Transform(ray, matrix) { const result = new _Ray(new Vector3(0, 0, 0), new 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 * @returns the updated result ray */ static TransformToRef(ray, matrix, result) { Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin); Vector3.TransformNormalToRef(ray.direction, matrix, result.direction); result.length = ray.length; result.epsilon = ray.epsilon; const dir = result.direction; const len = dir.length(); if (!(len === 0 || len === 1)) { const num = 1 / len; dir.x *= num; dir.y *= num; dir.z *= num; result.length *= len; } return result; } /** * 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 */ unprojectRayToRef(sourceX, sourceY, viewportWidth, viewportHeight, world, view, projection) { const matrix = TmpVectors.Matrix[0]; world.multiplyToRef(view, matrix); matrix.multiplyToRef(projection, matrix); matrix.invert(); const engine = EngineStore.LastCreatedEngine; const nearScreenSource = TmpVectors.Vector3[0]; nearScreenSource.x = sourceX / viewportWidth * 2 - 1; nearScreenSource.y = -(sourceY / viewportHeight * 2 - 1); nearScreenSource.z = engine?.useReverseDepthBuffer ? 1 : engine?.isNDCHalfZRange ? 0 : -1; const farScreenSource = TmpVectors.Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1 - 1e-8); const nearVec3 = TmpVectors.Vector3[2]; const farVec3 = TmpVectors.Vector3[3]; Vector3.TransformCoordinatesToRef(nearScreenSource, matrix, nearVec3); Vector3.TransformCoordinatesToRef(farScreenSource, matrix, farVec3); this.origin.copyFrom(nearVec3); farVec3.subtractToRef(nearVec3, this.direction); this.direction.normalize(); } }; Ray._TmpVector3 = BuildArray(6, Vector3.Zero); Ray._RayDistant = Ray.Zero(); Ray._Smallnum = 1e-8; Ray._Rayl = 1e9; function CreatePickingRay(scene, x, y, world, camera, cameraViewSpace = false) { const result = Ray.Zero(); CreatePickingRayToRef(scene, x, y, world, result, camera, cameraViewSpace); return result; } __name(CreatePickingRay, "CreatePickingRay"); function CreatePickingRayToRef(scene, x, y, world, result, camera, cameraViewSpace = false, enableDistantPicking = false) { const engine = scene.getEngine(); if (!camera && !(camera = scene.activeCamera)) { return scene; } const cameraViewport = camera.viewport; const renderHeight = engine.getRenderHeight(); const { x: vx, y: vy, width, height } = cameraViewport.toGlobal(engine.getRenderWidth(), renderHeight); const levelInv = 1 / engine.getHardwareScalingLevel(); x = x * levelInv - vx; y = y * levelInv - (renderHeight - vy - height); result.update(x, y, width, height, world ? world : Matrix.IdentityReadOnly, cameraViewSpace ? Matrix.IdentityReadOnly : camera.getViewMatrix(), camera.getProjectionMatrix(), enableDistantPicking); return scene; } __name(CreatePickingRayToRef, "CreatePickingRayToRef"); function CreatePickingRayInCameraSpace(scene, x, y, camera) { const result = Ray.Zero(); CreatePickingRayInCameraSpaceToRef(scene, x, y, result, camera); return result; } __name(CreatePickingRayInCameraSpace, "CreatePickingRayInCameraSpace"); function CreatePickingRayInCameraSpaceToRef(scene, x, y, result, camera) { if (!PickingInfo) { return scene; } const engine = scene.getEngine(); if (!camera && !(camera = scene.activeCamera)) { throw new Error("Active camera not set"); } const cameraViewport = camera.viewport; const renderHeight = engine.getRenderHeight(); const { x: vx, y: vy, width, height } = cameraViewport.toGlobal(engine.getRenderWidth(), renderHeight); const identity = Matrix.Identity(); const levelInv = 1 / engine.getHardwareScalingLevel(); x = x * levelInv - vx; y = y * levelInv - (renderHeight - vy - height); result.update(x, y, width, height, identity, identity, camera.getProjectionMatrix()); return scene; } __name(CreatePickingRayInCameraSpaceToRef, "CreatePickingRayInCameraSpaceToRef"); function InternalPickForMesh(pickingInfo, rayFunction, mesh, world, fastCheck, onlyBoundingInfo, trianglePredicate, skipBoundingInfo) { const ray = rayFunction(world, mesh.enableDistantPicking); const result = mesh.intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo, world, skipBoundingInfo); if (!result || !result.hit) { return null; } if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) { return null; } return result; } __name(InternalPickForMesh, "InternalPickForMesh"); function InternalPick(scene, rayFunction, predicate, fastCheck, onlyBoundingInfo, trianglePredicate) { let pickingInfo = null; const computeWorldMatrixForCamera = !!(scene.activeCameras && scene.activeCameras.length > 1 && scene.cameraToUseForPointers !== scene.activeCamera); const currentCamera = scene.cameraToUseForPointers || scene.activeCamera; const picker = PickingCustomization.internalPickerForMesh || InternalPickForMesh; for (let meshIndex = 0; meshIndex < scene.meshes.length; meshIndex++) { const mesh = scene.meshes[meshIndex]; if (predicate) { if (!predicate(mesh, -1)) { continue; } } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) { continue; } const forceCompute = computeWorldMatrixForCamera && mesh.isWorldMatrixCameraDependent(); const world = mesh.computeWorldMatrix(forceCompute, currentCamera); if (mesh.hasThinInstances && mesh.thinInstanceEnablePicking) { const result = picker(pickingInfo, rayFunction, mesh, world, true, true, trianglePredicate); if (result) { if (onlyBoundingInfo) { return result; } const tmpMatrix = TmpVectors.Matrix[1]; const thinMatrices = mesh.thinInstanceGetWorldMatrices(); for (let index = 0; index < thinMatrices.length; index++) { if (predicate && !predicate(mesh, index)) { continue; } const thinMatrix = thinMatrices[index]; thinMatrix.multiplyToRef(world, tmpMatrix); const result2 = picker(pickingInfo, rayFunction, mesh, tmpMatrix, fastCheck, onlyBoundingInfo, trianglePredicate, true); if (result2) { pickingInfo = result2; pickingInfo.thinInstanceIndex = index; if (fastCheck) { return pickingInfo; } } } } } else { const result = picker(pickingInfo, rayFunction, mesh, world, fastCheck, onlyBoundingInfo, trianglePredicate); if (result) { pickingInfo = result; if (fastCheck) { return pickingInfo; } } } } return pickingInfo || new PickingInfo(); } __name(InternalPick, "InternalPick"); function InternalMultiPick(scene, rayFunction, predicate, trianglePredicate) { if (!PickingInfo) { return null; } const pickingInfos = []; const computeWorldMatrixForCamera = !!(scene.activeCameras && scene.activeCameras.length > 1 && scene.cameraToUseForPointers !== scene.activeCamera); const currentCamera = scene.cameraToUseForPointers || scene.activeCamera; const picker = PickingCustomization.internalPickerForMesh || InternalPickForMesh; for (let meshIndex = 0; meshIndex < scene.meshes.length; meshIndex++) { const mesh = scene.meshes[meshIndex]; if (predicate) { if (!predicate(mesh, -1)) { continue; } } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) { continue; } const forceCompute = computeWorldMatrixForCamera && mesh.isWorldMatrixCameraDependent(); const world = mesh.computeWorldMatrix(forceCompute, currentCamera); if (mesh.hasThinInstances && mesh.thinInstanceEnablePicking) { const result = picker(null, rayFunction, mesh, world, true, true, trianglePredicate); if (result) { const tmpMatrix = TmpVectors.Matrix[1]; const thinMatrices = mesh.thinInstanceGetWorldMatrices(); for (let index = 0; index < thinMatrices.length; index++) { if (predicate && !predicate(mesh, index)) { continue; } const thinMatrix = thinMatrices[index]; thinMatrix.multiplyToRef(world, tmpMatrix); const result2 = picker(null, rayFunction, mesh, tmpMatrix, false, false, trianglePredicate, true); if (result2) { result2.thinInstanceIndex = index; pickingInfos.push(result2); } } } } else { const result = picker(null, rayFunction, mesh, world, false, false, trianglePredicate); if (result) { pickingInfos.push(result); } } } return pickingInfos; } __name(InternalMultiPick, "InternalMultiPick"); function PickWithBoundingInfo(scene, x, y, predicate, fastCheck, camera) { if (!PickingInfo) { return null; } const result = InternalPick(scene, (world) => { if (!scene._tempPickingRay) { scene._tempPickingRay = Ray.Zero(); } CreatePickingRayToRef(scene, x, y, world, scene._tempPickingRay, camera || null); return scene._tempPickingRay; }, predicate, fastCheck, true); if (result) { result.ray = CreatePickingRay(scene, x, y, Matrix.Identity(), camera || null); } return result; } __name(PickWithBoundingInfo, "PickWithBoundingInfo"); function Pick(scene, x, y, predicate, fastCheck, camera, trianglePredicate, _enableDistantPicking = false) { const result = InternalPick(scene, (world, enableDistantPicking) => { if (!scene._tempPickingRay) { scene._tempPickingRay = Ray.Zero(); } CreatePickingRayToRef(scene, x, y, world, scene._tempPickingRay, camera || null, false, enableDistantPicking); return scene._tempPickingRay; }, predicate, fastCheck, false, trianglePredicate); if (result) { result.ray = CreatePickingRay(scene, x, y, Matrix.Identity(), camera || null); } return result; } __name(Pick, "Pick"); function PickWithRay(scene, ray, predicate, fastCheck, trianglePredicate) { const result = InternalPick(scene, (world) => { if (!scene._pickWithRayInverseMatrix) { scene._pickWithRayInverseMatrix = Matrix.Identity(); } world.invertToRef(scene._pickWithRayInverseMatrix); if (!scene._cachedRayForTransform) { scene._cachedRayForTransform = Ray.Zero(); } Ray.TransformToRef(ray, scene._pickWithRayInverseMatrix, scene._cachedRayForTransform); return scene._cachedRayForTransform; }, predicate, fastCheck, false, trianglePredicate); if (result) { result.ray = ray; } return result; } __name(PickWithRay, "PickWithRay"); function MultiPick(scene, x, y, predicate, camera, trianglePredicate) { return InternalMultiPick(scene, (world) => CreatePickingRay(scene, x, y, world, camera || null), predicate, trianglePredicate); } __name(MultiPick, "MultiPick"); function MultiPickWithRay(scene, ray, predicate, trianglePredicate) { return InternalMultiPick(scene, (world) => { if (!scene._pickWithRayInverseMatrix) { scene._pickWithRayInverseMatrix = Matrix.Identity(); } world.invertToRef(scene._pickWithRayInverseMatrix); if (!scene._cachedRayForTransform) { scene._cachedRayForTransform = Ray.Zero(); } Ray.TransformToRef(ray, scene._pickWithRayInverseMatrix, scene._cachedRayForTransform); return scene._cachedRayForTransform; }, predicate, trianglePredicate); } __name(MultiPickWithRay, "MultiPickWithRay"); function GetForwardRay(camera, length = 100, transform, origin) { return GetForwardRayToRef(camera, new Ray(Vector3.Zero(), Vector3.Zero(), length), length, transform, origin); } __name(GetForwardRay, "GetForwardRay"); function GetForwardRayToRef(camera, refRay, length = 100, transform, origin) { if (!transform) { transform = camera.getWorldMatrix(); } refRay.length = length; if (origin) { refRay.origin.copyFrom(origin); } else { refRay.origin.copyFrom(camera.position); } const forward = TmpVectors.Vector3[2]; forward.set(0, 0, camera._scene.useRightHandedSystem ? -1 : 1); const worldForward = TmpVectors.Vector3[3]; Vector3.TransformNormalToRef(forward, transform, worldForward); Vector3.NormalizeToRef(worldForward, refRay.direction); return refRay; } __name(GetForwardRayToRef, "GetForwardRayToRef"); function AddRayExtensions(sceneClass, cameraClass) { if (cameraClass) { cameraClass.prototype.getForwardRay = function(length = 100, transform, origin) { return GetForwardRayToRef(this, new Ray(Vector3.Zero(), Vector3.Zero(), length), length, transform, origin); }; cameraClass.prototype.getForwardRayToRef = function(refRay, length = 100, transform, origin) { return GetForwardRayToRef(this, refRay, length, transform, origin); }; } if (!sceneClass) { return; } _ImportHelper._IsPickingAvailable = true; sceneClass.prototype.createPickingRay = function(x, y, world, camera, cameraViewSpace = false) { return CreatePickingRay(this, x, y, world, camera, cameraViewSpace); }; } __name(AddRayExtensions, "AddRayExtensions"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Sprites/spriteSceneComponent.js init_observable(); init_scene(); init_pickingInfo(); init_sceneComponent(); init_actionEvent(); Object.defineProperty(Scene.prototype, "onNewSpriteManagerAddedObservable", { get: /* @__PURE__ */ __name(function() { if (!this.isDisposed && !this._onNewSpriteManagerAddedObservable) { const onNewSpriteManagerAddedObservable = this._onNewSpriteManagerAddedObservable = new Observable(); this.onDisposeObservable.addOnce(() => onNewSpriteManagerAddedObservable.clear()); } return this._onNewSpriteManagerAddedObservable; }, "get"), enumerable: true, configurable: true }); Object.defineProperty(Scene.prototype, "onSpriteManagerRemovedObservable", { get: /* @__PURE__ */ __name(function() { if (!this.isDisposed && !this._onSpriteManagerRemovedObservable) { const onSpriteManagerRemovedObservable = this._onSpriteManagerRemovedObservable = new Observable(); this.onDisposeObservable.addOnce(() => onSpriteManagerRemovedObservable.clear()); } return this._onSpriteManagerRemovedObservable; }, "get"), enumerable: true, configurable: true }); Scene.prototype._internalPickSprites = function(ray, predicate, fastCheck, camera) { if (!PickingInfo) { return null; } let pickingInfo = null; if (!camera) { if (!this.activeCamera) { return null; } camera = this.activeCamera; } if (this.spriteManagers && this.spriteManagers.length > 0) { for (let spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) { const spriteManager = this.spriteManagers[spriteIndex]; if (!spriteManager.isPickable) { continue; } const result = spriteManager.intersects(ray, camera, predicate, fastCheck); if (!result || !result.hit) { continue; } if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) { continue; } pickingInfo = result; if (fastCheck) { break; } } } return pickingInfo || new PickingInfo(); }; Scene.prototype._internalMultiPickSprites = function(ray, predicate, camera) { if (!PickingInfo) { return null; } let pickingInfos = []; if (!camera) { if (!this.activeCamera) { return null; } camera = this.activeCamera; } if (this.spriteManagers && this.spriteManagers.length > 0) { for (let spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) { const spriteManager = this.spriteManagers[spriteIndex]; if (!spriteManager.isPickable) { continue; } const results = spriteManager.multiIntersects(ray, camera, predicate); if (results !== null) { pickingInfos = pickingInfos.concat(results); } } } return pickingInfos; }; Scene.prototype.pickSprite = function(x, y, predicate, fastCheck, camera) { if (!this._tempSpritePickingRay) { return null; } CreatePickingRayInCameraSpaceToRef(this, x, y, this._tempSpritePickingRay, camera); const result = this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera); if (result) { result.ray = CreatePickingRayInCameraSpace(this, x, y, camera); } return result; }; Scene.prototype.pickSpriteWithRay = function(ray, predicate, fastCheck, camera) { if (!this._tempSpritePickingRay) { return null; } if (!camera) { if (!this.activeCamera) { return null; } camera = this.activeCamera; } Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay); const result = this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera); if (result) { result.ray = ray; } return result; }; Scene.prototype.multiPickSprite = function(x, y, predicate, camera) { CreatePickingRayInCameraSpaceToRef(this, x, y, this._tempSpritePickingRay, camera); return this._internalMultiPickSprites(this._tempSpritePickingRay, predicate, camera); }; Scene.prototype.multiPickSpriteWithRay = function(ray, predicate, camera) { if (!this._tempSpritePickingRay) { return null; } if (!camera) { if (!this.activeCamera) { return null; } camera = this.activeCamera; } Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay); return this._internalMultiPickSprites(this._tempSpritePickingRay, predicate, camera); }; Scene.prototype.setPointerOverSprite = function(sprite) { if (this._pointerOverSprite === sprite) { return; } if (this._pointerOverSprite && this._pointerOverSprite.actionManager) { this._pointerOverSprite.actionManager.processTrigger(10, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this)); } this._pointerOverSprite = sprite; if (this._pointerOverSprite && this._pointerOverSprite.actionManager) { this._pointerOverSprite.actionManager.processTrigger(9, ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this)); } }; Scene.prototype.getPointerOverSprite = function() { return this._pointerOverSprite; }; var SpriteSceneComponent = class { static { __name(this, "SpriteSceneComponent"); } /** * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ constructor(scene) { this.name = SceneComponentConstants.NAME_SPRITE; this.scene = scene; this.scene.spriteManagers = []; this.scene._tempSpritePickingRay = Ray ? Ray.Zero() : null; this.scene.onBeforeSpritesRenderingObservable = new Observable(); this.scene.onAfterSpritesRenderingObservable = new Observable(); this._spritePredicate = (sprite) => { if (!sprite.actionManager) { return false; } return sprite.isPickable && sprite.actionManager.hasPointerTriggers; }; } /** * Registers the component in a given scene */ register() { this.scene._pointerMoveStage.registerStep(SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove); this.scene._pointerDownStage.registerStep(SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown); this.scene._pointerUpStage.registerStep(SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp); } /** * Rebuilds the elements related to this component in case of * context lost for instance. */ rebuild() { } /** * Disposes the component and the associated resources. */ dispose() { this.scene.onBeforeSpritesRenderingObservable.clear(); this.scene.onAfterSpritesRenderingObservable.clear(); const spriteManagers = this.scene.spriteManagers; if (!spriteManagers) { return; } while (spriteManagers.length) { spriteManagers[0].dispose(); } } _pickSpriteButKeepRay(originalPointerInfo, x, y, fastCheck, camera) { const result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera); if (result) { result.ray = originalPointerInfo ? originalPointerInfo.ray : null; } return result; } _pointerMove(unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, element) { const scene = this.scene; if (isMeshPicked) { scene.setPointerOverSprite(null); } else { pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || void 0); if (pickResult && pickResult.hit && pickResult.pickedSprite) { scene.setPointerOverSprite(pickResult.pickedSprite); if (!scene.doNotHandleCursors && element) { if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) { element.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor; } else { element.style.cursor = scene.hoverCursor; } } } else { scene.setPointerOverSprite(null); } } return pickResult; } _pointerDown(unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) { const scene = this.scene; scene._pickedDownSprite = null; if (scene.spriteManagers && scene.spriteManagers.length > 0) { pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || void 0); if (pickResult && pickResult.hit && pickResult.pickedSprite) { if (pickResult.pickedSprite.actionManager) { scene._pickedDownSprite = pickResult.pickedSprite; switch (evt.button) { case 0: pickResult.pickedSprite.actionManager.processTrigger(2, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt)); break; case 1: pickResult.pickedSprite.actionManager.processTrigger(4, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt)); break; case 2: pickResult.pickedSprite.actionManager.processTrigger(3, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt)); break; } if (pickResult.pickedSprite.actionManager) { pickResult.pickedSprite.actionManager.processTrigger(5, ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt)); } } } } return pickResult; } _pointerUp(unTranslatedPointerX, unTranslatedPointerY, pickResult, evt, doubleClick) { const scene = this.scene; if (scene.spriteManagers && scene.spriteManagers.length > 0) { const spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || void 0); if (spritePickResult) { if (spritePickResult.hit && spritePickResult.pickedSprite) { if (spritePickResult.pickedSprite.actionManager) { spritePickResult.pickedSprite.actionManager.processTrigger(7, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt)); if (spritePickResult.pickedSprite.actionManager) { if (!this.scene._inputManager._isPointerSwiping()) { spritePickResult.pickedSprite.actionManager.processTrigger(1, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt)); } if (doubleClick) { spritePickResult.pickedSprite.actionManager.processTrigger(6, ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt)); } } } } if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) { scene._pickedDownSprite.actionManager.processTrigger(16, ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt)); } } } return pickResult; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Sprites/spriteRenderer.js init_buffer(); init_drawWrapper(); init_logger(); init_materialHelper_functions_pure(); var SpriteRenderer = class _SpriteRenderer { static { __name(this, "SpriteRenderer"); } /** * Gets or sets a boolean indicating if the manager must consider scene fog when rendering */ get fogEnabled() { return this._fogEnabled; } set fogEnabled(value) { if (this._fogEnabled === value) { return; } this._fogEnabled = value; this._createEffects(); } /** * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes) * You can try switching to logarithmic depth. * @see https://doc.babylonjs.com/features/featuresDeepDive/materials/advanced/logarithmicDepthBuffer */ get useLogarithmicDepth() { return this._useLogarithmicDepth; } set useLogarithmicDepth(value) { const fragmentDepthSupported = !!this._scene?.getEngine().getCaps().fragmentDepthSupported; if (value && !fragmentDepthSupported) { Logger.Warn("Logarithmic depth has been requested for a sprite renderer on a device that doesn't support it."); } this._useLogarithmicDepth = value && fragmentDepthSupported; this._createEffects(); } /** * Gets the capacity of the manager */ get capacity() { return this._capacity; } /** * Gets or sets a boolean indicating if the renderer must render sprites with pixel perfect rendering * Note that pixel perfect mode is not supported in WebGL 1 */ get pixelPerfect() { return this._pixelPerfect; } set pixelPerfect(value) { if (this._pixelPerfect === value) { return; } this._pixelPerfect = value; this._createEffects(); } /** * Gets the shader language used in this renderer. */ get shaderLanguage() { return this._shaderLanguage; } /** * Creates a new sprite renderer * @param engine defines the engine the renderer works with * @param capacity defines the maximum allowed number of sprites * @param epsilon defines the epsilon value to align texture (0.01 by default) * @param scene defines the hosting scene * @param rendererOptions options for the sprite renderer */ constructor(engine, capacity, epsilon = 0.01, scene = null, rendererOptions) { this.blendMode = 2; this.autoResetAlpha = true; this.disableDepthWrite = false; this._fogEnabled = true; this._pixelPerfect = false; this._shaderLanguage = 0; this._useVAO = false; this._useInstancing = false; this._vertexBuffers = {}; this._isDisposed = false; this._shadersLoaded = false; this._pixelPerfect = rendererOptions?.pixelPerfect ?? false; this._capacity = capacity; this._epsilon = epsilon; this._engine = engine; this._useInstancing = engine.getCaps().instancedArrays && engine._features.supportSpriteInstancing; this._useVAO = engine.getCaps().vertexArrayObject && !engine.disableVertexArrayObjects; this._scene = scene; if (!this._useInstancing) { this._buildIndexBuffer(); } this._vertexBufferSize = this._useInstancing ? 16 : 18; this._vertexData = new Float32Array(capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4)); this._buffer = new Buffer2(engine, this._vertexData, true, this._vertexBufferSize); const positions = this._buffer.createVertexBuffer(VertexBuffer.PositionKind, 0, 4, this._vertexBufferSize, this._useInstancing); const options = this._buffer.createVertexBuffer("options", 4, 2, this._vertexBufferSize, this._useInstancing); let offset = 6; let offsets; if (this._useInstancing) { const spriteData = new Float32Array([ this._epsilon, this._epsilon, 1 - this._epsilon, this._epsilon, this._epsilon, 1 - this._epsilon, 1 - this._epsilon, 1 - this._epsilon ]); this._spriteBuffer = new Buffer2(engine, spriteData, false, 2); offsets = this._spriteBuffer.createVertexBuffer("offsets", 0, 2); } else { offsets = this._buffer.createVertexBuffer("offsets", offset, 2, this._vertexBufferSize, this._useInstancing); offset += 2; } const inverts = this._buffer.createVertexBuffer("inverts", offset, 2, this._vertexBufferSize, this._useInstancing); const cellInfo = this._buffer.createVertexBuffer("cellInfo", offset + 2, 4, this._vertexBufferSize, this._useInstancing); const colors = this._buffer.createVertexBuffer(VertexBuffer.ColorKind, offset + 6, 4, this._vertexBufferSize, this._useInstancing); this._vertexBuffers[VertexBuffer.PositionKind] = positions; this._vertexBuffers["options"] = options; this._vertexBuffers["offsets"] = offsets; this._vertexBuffers["inverts"] = inverts; this._vertexBuffers["cellInfo"] = cellInfo; this._vertexBuffers[VertexBuffer.ColorKind] = colors; this._initShaderSourceAsync(); } async _initShaderSourceAsync() { const engine = this._engine; if (engine.isWebGPU && !_SpriteRenderer.ForceGLSL) { this._shaderLanguage = 1; await Promise.all([Promise.resolve().then(() => (init_sprites_vertex(), sprites_vertex_exports)), Promise.resolve().then(() => (init_sprites_fragment(), sprites_fragment_exports))]); } else { await Promise.all([Promise.resolve().then(() => (init_sprites_vertex2(), sprites_vertex_exports2)), Promise.resolve().then(() => (init_sprites_fragment2(), sprites_fragment_exports2))]); } this._shadersLoaded = true; this._createEffects(); } _createEffects() { if (this._isDisposed || !this._shadersLoaded) { return; } this._drawWrapperBase?.dispose(); this._drawWrapperDepth?.dispose(); this._drawWrapperBase = new DrawWrapper(this._engine); this._drawWrapperDepth = new DrawWrapper(this._engine, false); if (this._drawWrapperBase.drawContext) { this._drawWrapperBase.drawContext.useInstancing = this._useInstancing; } if (this._drawWrapperDepth.drawContext) { this._drawWrapperDepth.drawContext.useInstancing = this._useInstancing; } let defines = ""; if (this._pixelPerfect) { defines += "#define PIXEL_PERFECT\n"; } if (this._scene && this._scene.fogEnabled && this._scene.fogMode !== 0 && this._fogEnabled) { defines += "#define FOG\n"; } if (this._useLogarithmicDepth) { defines += "#define LOGARITHMICDEPTH\n"; } this._drawWrapperBase.effect = this._engine.createEffect("sprites", [VertexBuffer.PositionKind, "options", "offsets", "inverts", "cellInfo", VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor", "logarithmicDepthConstant"], ["diffuseSampler"], defines, void 0, void 0, void 0, void 0, this._shaderLanguage); this._drawWrapperDepth.effect = this._drawWrapperBase.effect; this._drawWrapperBase.effect._refCount++; this._drawWrapperDepth.materialContext = this._drawWrapperBase.materialContext; } /** * Render all child sprites * @param sprites defines the list of sprites to render * @param deltaTime defines the time since last frame * @param viewMatrix defines the viewMatrix to use to render the sprites * @param projectionMatrix defines the projectionMatrix to use to render the sprites * @param customSpriteUpdate defines a custom function to update the sprites data before they render */ render(sprites, deltaTime, viewMatrix, projectionMatrix, customSpriteUpdate = null) { if (!this._shadersLoaded || !this.texture || !this.texture.isReady() || !sprites.length) { return; } const drawWrapper = this._drawWrapperBase; const drawWrapperDepth = this._drawWrapperDepth; const shouldRenderFog = this.fogEnabled && this._scene && this._scene.fogEnabled && this._scene.fogMode !== 0; const effect = drawWrapper.effect; if (!effect.isReady()) { return; } const engine = this._engine; const useRightHandedSystem = !!(this._scene && this._scene.useRightHandedSystem); const max = Math.min(this._capacity, sprites.length); let offset = 0; let noSprite = true; for (let index = 0; index < max; index++) { const sprite = sprites[index]; if (!sprite || !sprite.isVisible) { continue; } noSprite = false; sprite._animate(deltaTime); const baseSize = this.texture.getBaseSize(); this._appendSpriteVertex(offset++, sprite, 0, 0, baseSize, useRightHandedSystem, customSpriteUpdate); if (!this._useInstancing) { this._appendSpriteVertex(offset++, sprite, 1, 0, baseSize, useRightHandedSystem, customSpriteUpdate); this._appendSpriteVertex(offset++, sprite, 1, 1, baseSize, useRightHandedSystem, customSpriteUpdate); this._appendSpriteVertex(offset++, sprite, 0, 1, baseSize, useRightHandedSystem, customSpriteUpdate); } } if (noSprite) { return; } this._buffer.update(this._vertexData); const culling = !!engine.depthCullingState.cull; const zOffset = engine.depthCullingState.zOffset; const zOffsetUnits = engine.depthCullingState.zOffsetUnits; engine.setState(culling, zOffset, false, false, void 0, void 0, zOffsetUnits); engine.enableEffect(drawWrapper); effect.setTexture("diffuseSampler", this.texture); effect.setMatrix("view", viewMatrix); effect.setMatrix("projection", projectionMatrix); if (shouldRenderFog) { const scene = this._scene; effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity); effect.setColor3("vFogColor", scene.fogColor); } if (this.useLogarithmicDepth && this._scene) { BindLogDepth(drawWrapper.defines, effect, this._scene); } if (this._useVAO) { if (!this._vertexArrayObject) { this._vertexArrayObject = engine.recordVertexArrayObject(this._vertexBuffers, this._indexBuffer, effect); } engine.bindVertexArrayObject(this._vertexArrayObject, this._indexBuffer); } else { engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect); } engine.depthCullingState.depthFunc = engine.useReverseDepthBuffer ? 518 : 515; if (!this.disableDepthWrite) { effect.setBool("alphaTest", true); engine.setColorWrite(false); engine.enableEffect(drawWrapperDepth); if (this._useInstancing) { engine.drawArraysType(7, 0, 4, offset); } else { engine.drawElementsType(0, 0, offset / 4 * 6); } engine.enableEffect(drawWrapper); engine.setColorWrite(true); effect.setBool("alphaTest", false); } engine.setAlphaMode(this.blendMode); if (this._useInstancing) { engine.drawArraysType(7, 0, 4, offset); } else { engine.drawElementsType(0, 0, offset / 4 * 6); } if (this.autoResetAlpha) { engine.setAlphaMode(0); } if (useRightHandedSystem) { this._scene.getEngine().setState(culling, zOffset, false, true, void 0, void 0, zOffsetUnits); } engine.unbindInstanceAttributes(); } _appendSpriteVertex(index, sprite, offsetX, offsetY, baseSize, useRightHandedSystem, customSpriteUpdate) { let arrayOffset = index * this._vertexBufferSize; if (offsetX === 0) { offsetX = this._epsilon; } else if (offsetX === 1) { offsetX = 1 - this._epsilon; } if (offsetY === 0) { offsetY = this._epsilon; } else if (offsetY === 1) { offsetY = 1 - this._epsilon; } if (customSpriteUpdate) { customSpriteUpdate(sprite, baseSize); } else { if (!sprite.cellIndex) { sprite.cellIndex = 0; } const rowSize = baseSize.width / this.cellWidth; const offset = sprite.cellIndex / rowSize >> 0; sprite._xOffset = (sprite.cellIndex - offset * rowSize) * this.cellWidth / baseSize.width; sprite._yOffset = offset * this.cellHeight / baseSize.height; sprite._xSize = this.cellWidth; sprite._ySize = this.cellHeight; } this._vertexData[arrayOffset] = sprite.position.x; this._vertexData[arrayOffset + 1] = sprite.position.y; this._vertexData[arrayOffset + 2] = sprite.position.z; this._vertexData[arrayOffset + 3] = sprite.angle; this._vertexData[arrayOffset + 4] = sprite.width; this._vertexData[arrayOffset + 5] = sprite.height; if (!this._useInstancing) { this._vertexData[arrayOffset + 6] = offsetX; this._vertexData[arrayOffset + 7] = offsetY; } else { arrayOffset -= 2; } if (useRightHandedSystem) { this._vertexData[arrayOffset + 8] = sprite.invertU ? 0 : 1; } else { this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0; } this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0; this._vertexData[arrayOffset + 10] = sprite._xOffset; this._vertexData[arrayOffset + 11] = sprite._yOffset; this._vertexData[arrayOffset + 12] = sprite._xSize / baseSize.width; this._vertexData[arrayOffset + 13] = sprite._ySize / baseSize.height; this._vertexData[arrayOffset + 14] = sprite.color.r; this._vertexData[arrayOffset + 15] = sprite.color.g; this._vertexData[arrayOffset + 16] = sprite.color.b; this._vertexData[arrayOffset + 17] = sprite.color.a; } _buildIndexBuffer() { const indices = []; let index = 0; for (let count = 0; count < this._capacity; count++) { indices.push(index); indices.push(index + 1); indices.push(index + 2); indices.push(index); indices.push(index + 2); indices.push(index + 3); index += 4; } this._indexBuffer = this._engine.createIndexBuffer(indices); } /** * Rebuilds the renderer (after a context lost, for eg) */ rebuild() { if (this._indexBuffer) { this._buildIndexBuffer(); } if (this._useVAO) { this._vertexArrayObject = void 0; } this._buffer._rebuild(); for (const key in this._vertexBuffers) { const vertexBuffer = this._vertexBuffers[key]; vertexBuffer._rebuild(); } this._spriteBuffer?._rebuild(); } /** * Release associated resources */ dispose() { if (this._buffer) { this._buffer.dispose(); this._buffer = null; } if (this._spriteBuffer) { this._spriteBuffer.dispose(); this._spriteBuffer = null; } if (this._indexBuffer) { this._engine._releaseBuffer(this._indexBuffer); this._indexBuffer = null; } if (this._vertexArrayObject) { this._engine.releaseVertexArrayObject(this._vertexArrayObject); this._vertexArrayObject = null; } if (this.texture) { this.texture.dispose(); this.texture = null; } this._drawWrapperBase?.dispose(); this._drawWrapperDepth?.dispose(); this._isDisposed = true; } }; SpriteRenderer.ForceGLSL = false; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Sprites/spriteManager.js init_observable(); init_math_vector(); init_pickingInfo(); init_texture(); init_sceneComponent(); init_logger(); init_tools(); init_webRequest(); init_engineStore(); var SpriteManager = class _SpriteManager { static { __name(this, "SpriteManager"); } /** * Callback called when the manager is disposed */ set onDispose(callback) { if (this._onDisposeObserver) { this.onDisposeObservable.remove(this._onDisposeObserver); } this._onDisposeObserver = this.onDisposeObservable.add(callback); } /** * Gets the array of sprites */ get children() { return this.sprites; } /** * Gets the hosting scene */ get scene() { return this._scene; } /** * Gets the capacity of the manager */ get capacity() { return this._spriteRenderer.capacity; } /** * Gets or sets the spritesheet texture */ get texture() { return this._spriteRenderer.texture; } set texture(value) { value.wrapU = Texture.CLAMP_ADDRESSMODE; value.wrapV = Texture.CLAMP_ADDRESSMODE; this._spriteRenderer.texture = value; this._textureContent = null; } /** Defines the default width of a cell in the spritesheet */ get cellWidth() { return this._spriteRenderer.cellWidth; } set cellWidth(value) { this._spriteRenderer.cellWidth = value; } /** Defines the default height of a cell in the spritesheet */ get cellHeight() { return this._spriteRenderer.cellHeight; } set cellHeight(value) { this._spriteRenderer.cellHeight = value; } /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */ get fogEnabled() { return this._spriteRenderer.fogEnabled; } set fogEnabled(value) { this._spriteRenderer.fogEnabled = value; } /** Gets or sets a boolean indicating if the manager must use logarithmic depth when rendering */ get useLogarithmicDepth() { return this._spriteRenderer.useLogarithmicDepth; } set useLogarithmicDepth(value) { this._spriteRenderer.useLogarithmicDepth = value; } /** * Blend mode use to render the particle, it can be any of * the static undefined properties provided in this class. * Default value is 2 */ get blendMode() { return this._spriteRenderer.blendMode; } set blendMode(blendMode) { this._spriteRenderer.blendMode = blendMode; } /** Disables writing to the depth buffer when rendering the sprites. * It can be handy to disable depth writing when using textures without alpha channel * and setting some specific blend modes. */ get disableDepthWrite() { return this._disableDepthWrite; } set disableDepthWrite(value) { this._disableDepthWrite = value; this._spriteRenderer.disableDepthWrite = value; } /** * Gets or sets a boolean indicating if the renderer must render sprites with pixel perfect rendering * In this mode, sprites are rendered as "pixel art", which means that they appear as pixelated but remain stable when moving or when rotated or scaled. * Note that for this mode to work as expected, the sprite texture must use the BILINEAR sampling mode, not NEAREST! */ get pixelPerfect() { return this._spriteRenderer.pixelPerfect; } set pixelPerfect(value) { this._spriteRenderer.pixelPerfect = value; if (value && this.texture.samplingMode !== 3) { this.texture.updateSamplingMode(3); } } /** * Gets the sprite renderer associated with this manager */ get spriteRenderer() { return this._spriteRenderer; } /** * Creates a new sprite manager * @param name defines the manager's name * @param imgUrl defines the sprite sheet url * @param capacity defines the maximum allowed number of sprites * @param cellSize defines the size of a sprite cell * @param scene defines the hosting scene * @param epsilon defines the epsilon value to align texture (0.01 by default) * @param samplingMode defines the sampling mode to use with spritesheet * @param fromPacked set to false; do not alter * @param spriteJSON null otherwise a JSON object defining sprite sheet data; do not alter * @param options options used to create the SpriteManager instance */ constructor(name260, imgUrl, capacity, cellSize, scene, epsilon = 0.01, samplingMode = Texture.TRILINEAR_SAMPLINGMODE, fromPacked = false, spriteJSON = null, options) { this.name = name260; this.sprites = []; this.renderingGroupId = 0; this.layerMask = 268435455; this.isPickable = false; this.metadata = null; this._wasDispatched = false; this.onDisposeObservable = new Observable(); this._disableDepthWrite = false; this._packedAndReady = false; this._customUpdate = (sprite, baseSize) => { if (!sprite.cellRef) { sprite.cellIndex = 0; } const num = sprite.cellIndex; if (typeof num === "number" && isFinite(num) && Math.floor(num) === num) { sprite.cellRef = this._spriteMap[sprite.cellIndex]; } sprite._xOffset = this._cellData[sprite.cellRef].frame.x / baseSize.width; sprite._yOffset = this._cellData[sprite.cellRef].frame.y / baseSize.height; sprite._xSize = this._cellData[sprite.cellRef].frame.w; sprite._ySize = this._cellData[sprite.cellRef].frame.h; }; if (!scene) { scene = EngineStore.LastCreatedScene; } if (!scene._getComponent(SceneComponentConstants.NAME_SPRITE)) { scene._addComponent(new SpriteSceneComponent(scene)); } this._fromPacked = fromPacked; this._scene = scene; const engine = this._scene.getEngine(); this._spriteRenderer = new SpriteRenderer(engine, capacity, epsilon, scene, options?.spriteRendererOptions); if (cellSize.width && cellSize.height) { this.cellWidth = cellSize.width; this.cellHeight = cellSize.height; } else if (cellSize !== void 0) { this.cellWidth = cellSize; this.cellHeight = cellSize; } else { this._spriteRenderer = null; return; } this._scene.spriteManagers && this._scene.spriteManagers.push(this); this.uniqueId = this.scene.getUniqueId(); if (imgUrl) { this.texture = new Texture(imgUrl, scene, true, false, samplingMode); } if (this._fromPacked) { this._makePacked(imgUrl, spriteJSON); } this._scene._onNewSpriteManagerAddedObservable?.notifyObservers(this); } /** * Returns the string "SpriteManager" * @returns "SpriteManager" */ getClassName() { return "SpriteManager"; } _makePacked(imgUrl, spriteJSON) { if (spriteJSON !== null) { try { let celldata; if (typeof spriteJSON === "string") { celldata = JSON.parse(spriteJSON); } else { celldata = spriteJSON; } if (celldata.frames.length) { const frametemp = {}; for (let i = 0; i < celldata.frames.length; i++) { const _f = celldata.frames[i]; if (typeof Object.keys(_f)[0] !== "string") { throw new Error("Invalid JSON Format. Check the frame values and make sure the name is the first parameter."); } const name260 = _f[Object.keys(_f)[0]]; frametemp[name260] = _f; } celldata.frames = frametemp; } const spritemap = Reflect.ownKeys(celldata.frames); this._spriteMap = spritemap; this._packedAndReady = true; this._cellData = celldata.frames; } catch (e) { this._fromPacked = false; this._packedAndReady = false; throw new Error("Invalid JSON from string. Spritesheet managed with constant cell size."); } } else { const re = /\./g; let li; do { li = re.lastIndex; re.test(imgUrl); } while (re.lastIndex > 0); const jsonUrl = imgUrl.substring(0, li - 1) + ".json"; const onerror = /* @__PURE__ */ __name(() => { Logger.Error("JSON ERROR: Unable to load JSON file."); this._fromPacked = false; this._packedAndReady = false; }, "onerror"); const onload = /* @__PURE__ */ __name((data) => { try { const celldata = JSON.parse(data); const spritemap = Reflect.ownKeys(celldata.frames); this._spriteMap = spritemap; this._packedAndReady = true; this._cellData = celldata.frames; } catch (e) { this._fromPacked = false; this._packedAndReady = false; throw new Error("Invalid JSON format. Please check documentation for format specifications."); } }, "onload"); Tools.LoadFile(jsonUrl, onload, void 0, void 0, false, onerror); } } _checkTextureAlpha(sprite, ray, distance, min, max) { if (!sprite.useAlphaForPicking || !this.texture?.isReady()) { return true; } const textureSize = this.texture.getSize(); if (!this._textureContent) { this._textureContent = new Uint8Array(textureSize.width * textureSize.height * 4); this.texture.readPixels(0, 0, this._textureContent); } const contactPoint = TmpVectors.Vector3[0]; contactPoint.copyFrom(ray.direction); contactPoint.normalize(); contactPoint.scaleInPlace(distance); contactPoint.addInPlace(ray.origin); const contactPointU = (contactPoint.x - min.x) / (max.x - min.x); const contactPointV = 1 - (contactPoint.y - min.y) / (max.y - min.y); const u = sprite._xOffset * textureSize.width + contactPointU * sprite._xSize | 0; const v = sprite._yOffset * textureSize.height + contactPointV * sprite._ySize | 0; const alpha = this._textureContent[(u + v * textureSize.width) * 4 + 3]; return alpha > 0.5; } /** * Intersects the sprites with a ray * @param ray defines the ray to intersect with * @param camera defines the current active camera * @param predicate defines a predicate used to select candidate sprites * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer) * @returns null if no hit or a PickingInfo */ intersects(ray, camera, predicate, fastCheck) { const count = Math.min(this.capacity, this.sprites.length); const min = Vector3.Zero(); const max = Vector3.Zero(); let distance = Number.MAX_VALUE; let currentSprite = null; const pickedPoint = TmpVectors.Vector3[0]; const cameraSpacePosition = TmpVectors.Vector3[1]; const cameraView = camera.getViewMatrix(); let activeRay = ray; let pickedRay = ray; for (let index = 0; index < count; index++) { const sprite = this.sprites[index]; if (!sprite) { continue; } if (predicate) { if (!predicate(sprite)) { continue; } } else if (!sprite.isPickable) { continue; } Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition); if (sprite.angle) { Matrix.TranslationToRef(-cameraSpacePosition.x, -cameraSpacePosition.y, 0, TmpVectors.Matrix[1]); Matrix.TranslationToRef(cameraSpacePosition.x, cameraSpacePosition.y, 0, TmpVectors.Matrix[2]); Matrix.RotationZToRef(-sprite.angle, TmpVectors.Matrix[3]); TmpVectors.Matrix[1].multiplyToRef(TmpVectors.Matrix[3], TmpVectors.Matrix[4]); TmpVectors.Matrix[4].multiplyToRef(TmpVectors.Matrix[2], TmpVectors.Matrix[0]); activeRay = ray.clone(); Vector3.TransformCoordinatesToRef(ray.origin, TmpVectors.Matrix[0], activeRay.origin); Vector3.TransformNormalToRef(ray.direction, TmpVectors.Matrix[0], activeRay.direction); } else { activeRay = ray; } min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z); max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z); if (activeRay.intersectsBoxMinMax(min, max)) { const currentDistance = Vector3.Distance(cameraSpacePosition, activeRay.origin); if (distance > currentDistance) { if (!this._checkTextureAlpha(sprite, activeRay, currentDistance, min, max)) { continue; } pickedRay = activeRay; distance = currentDistance; currentSprite = sprite; if (fastCheck) { break; } } } } if (currentSprite) { const result = new PickingInfo(); cameraView.invertToRef(TmpVectors.Matrix[0]); result.hit = true; result.pickedSprite = currentSprite; result.distance = distance; const direction = TmpVectors.Vector3[2]; direction.copyFrom(pickedRay.direction); direction.normalize(); direction.scaleInPlace(distance); pickedRay.origin.addToRef(direction, pickedPoint); result.pickedPoint = Vector3.TransformCoordinates(pickedPoint, TmpVectors.Matrix[0]); return result; } return null; } /** * Intersects the sprites with a ray * @param ray defines the ray to intersect with * @param camera defines the current active camera * @param predicate defines a predicate used to select candidate sprites * @returns null if no hit or a PickingInfo array */ multiIntersects(ray, camera, predicate) { const count = Math.min(this.capacity, this.sprites.length); const min = Vector3.Zero(); const max = Vector3.Zero(); let distance; const results = []; const pickedPoint = TmpVectors.Vector3[0].copyFromFloats(0, 0, 0); const cameraSpacePosition = TmpVectors.Vector3[1].copyFromFloats(0, 0, 0); const cameraView = camera.getViewMatrix(); for (let index = 0; index < count; index++) { const sprite = this.sprites[index]; if (!sprite) { continue; } if (predicate) { if (!predicate(sprite)) { continue; } } else if (!sprite.isPickable) { continue; } Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition); min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z); max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z); if (ray.intersectsBoxMinMax(min, max)) { distance = Vector3.Distance(cameraSpacePosition, ray.origin); if (!this._checkTextureAlpha(sprite, ray, distance, min, max)) { continue; } const result = new PickingInfo(); results.push(result); cameraView.invertToRef(TmpVectors.Matrix[0]); result.hit = true; result.pickedSprite = sprite; result.distance = distance; const direction = TmpVectors.Vector3[2]; direction.copyFrom(ray.direction); direction.normalize(); direction.scaleInPlace(distance); ray.origin.addToRef(direction, pickedPoint); result.pickedPoint = Vector3.TransformCoordinates(pickedPoint, TmpVectors.Matrix[0]); } } return results; } /** * Render all child sprites */ render() { if (this._fromPacked && (!this._packedAndReady || !this._spriteMap || !this._cellData)) { return; } const engine = this._scene.getEngine(); const deltaTime = engine.getDeltaTime(); if (this._packedAndReady) { this._spriteRenderer.render(this.sprites, deltaTime, this._scene.getViewMatrix(), this._scene.getProjectionMatrix(), this._customUpdate); } else { this._spriteRenderer.render(this.sprites, deltaTime, this._scene.getViewMatrix(), this._scene.getProjectionMatrix()); } } /** * Rebuilds the manager (after a context lost, for eg) */ rebuild() { this._spriteRenderer?.rebuild(); } /** * Release associated resources */ dispose() { if (this._spriteRenderer) { this._spriteRenderer.dispose(); this._spriteRenderer = null; } this._textureContent = null; if (this._scene.spriteManagers) { const index = this._scene.spriteManagers.indexOf(this); this._scene.spriteManagers.splice(index, 1); this._scene._onSpriteManagerRemovedObservable?.notifyObservers(this); } this.onDisposeObservable.notifyObservers(this); this.onDisposeObservable.clear(); this.metadata = null; } /** * Serializes the sprite manager to a JSON object * @param serializeTexture defines if the texture must be serialized as well * @returns the JSON object */ serialize(serializeTexture = false) { const serializationObject = {}; serializationObject.name = this.name; serializationObject.capacity = this.capacity; serializationObject.cellWidth = this.cellWidth; serializationObject.cellHeight = this.cellHeight; serializationObject.fogEnabled = this.fogEnabled; serializationObject.blendMode = this.blendMode; serializationObject.disableDepthWrite = this.disableDepthWrite; serializationObject.pixelPerfect = this.pixelPerfect; serializationObject.useLogarithmicDepth = this.useLogarithmicDepth; if (this.texture) { if (serializeTexture) { serializationObject.texture = this.texture.serialize(); } else { serializationObject.textureUrl = this.texture.name; serializationObject.invertY = this.texture._invertY; } } serializationObject.sprites = []; for (const sprite of this.sprites) { serializationObject.sprites.push(sprite.serialize()); } serializationObject.metadata = this.metadata; return serializationObject; } /** * Parses a JSON object to create a new sprite manager. * @param parsedManager The JSON object to parse * @param scene The scene to create the sprite manager * @param rootUrl The root url to use to load external dependencies like texture * @returns the new sprite manager */ static Parse(parsedManager, scene, rootUrl) { const manager = new _SpriteManager(parsedManager.name, "", parsedManager.capacity, { width: parsedManager.cellWidth, height: parsedManager.cellHeight }, scene); if (parsedManager.fogEnabled !== void 0) { manager.fogEnabled = parsedManager.fogEnabled; } if (parsedManager.blendMode !== void 0) { manager.blendMode = parsedManager.blendMode; } if (parsedManager.disableDepthWrite !== void 0) { manager.disableDepthWrite = parsedManager.disableDepthWrite; } if (parsedManager.pixelPerfect !== void 0) { manager.pixelPerfect = parsedManager.pixelPerfect; } if (parsedManager.useLogarithmicDepth !== void 0) { manager.useLogarithmicDepth = parsedManager.useLogarithmicDepth; } if (parsedManager.metadata !== void 0) { manager.metadata = parsedManager.metadata; } if (parsedManager.texture) { manager.texture = Texture.Parse(parsedManager.texture, scene, rootUrl); } else if (parsedManager.textureName) { manager.texture = new Texture(rootUrl + parsedManager.textureUrl, scene, false, parsedManager.invertY !== void 0 ? parsedManager.invertY : true); } for (const parsedSprite of parsedManager.sprites) { Sprite.Parse(parsedSprite, manager); } return manager; } /** * Creates a sprite manager from a snippet saved in a remote file * @param name defines the name of the sprite manager to create (can be null or empty to use the one from the json data) * @param url defines the url to load from * @param scene defines the hosting scene * @param rootUrl defines the root URL to use to load textures and relative dependencies * @returns a promise that will resolve to the new sprite manager */ static async ParseFromFileAsync(name260, url, scene, rootUrl = "") { return await new Promise((resolve, reject) => { const request = new WebRequest(); request.addEventListener("readystatechange", () => { if (request.readyState == 4) { if (request.status == 200) { const serializationObject = JSON.parse(request.responseText); const output = _SpriteManager.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl); if (name260) { output.name = name260; } resolve(output); } else { reject("Unable to load the sprite manager"); } } }); request.open("GET", url); request.send(); }); } /** * Creates a sprite manager from a snippet saved by the sprite editor * @param snippetId defines the snippet to load (can be set to _BLANK to create a default one) * @param scene defines the hosting scene * @param rootUrl defines the root URL to use to load textures and relative dependencies * @returns a promise that will resolve to the new sprite manager */ // eslint-disable-next-line @typescript-eslint/promise-function-async, no-restricted-syntax static ParseFromSnippetAsync(snippetId, scene, rootUrl = "") { if (snippetId === "_BLANK") { return Promise.resolve(new _SpriteManager("Default sprite manager", "//playground.babylonjs.com/textures/player.png", 500, 64, scene)); } return new Promise((resolve, reject) => { const request = new WebRequest(); request.addEventListener("readystatechange", () => { if (request.readyState == 4) { if (request.status == 200) { const snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); const serializationObject = JSON.parse(snippet.spriteManager); const output = _SpriteManager.Parse(serializationObject, scene || EngineStore.LastCreatedScene, rootUrl); output.snippetId = snippetId; resolve(output); } else { reject("Unable to load the snippet " + snippetId); } } }); request.open("GET", this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); request.send(); }); } }; SpriteManager.SnippetUrl = `https://snippet.babylonjs.com`; SpriteManager.CreateFromSnippetAsync = SpriteManager.ParseFromSnippetAsync; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/loading/sprite-manager.js init_tools(); init_webRequest(); function parseSerializedSpriteManager(spriteManager, parsedSpriteManager) { if (parsedSpriteManager?.fogEnabled !== void 0) { spriteManager.fogEnabled = parsedSpriteManager?.fogEnabled; } if (parsedSpriteManager?.blendMode !== void 0) { spriteManager.blendMode = parsedSpriteManager?.blendMode; } if (parsedSpriteManager?.disableDepthWrite !== void 0) { spriteManager.disableDepthWrite = parsedSpriteManager?.disableDepthWrite; } if (parsedSpriteManager?.pixelPerfect !== void 0) { spriteManager.pixelPerfect = parsedSpriteManager?.pixelPerfect; } if (parsedSpriteManager?.useLogarithmicDepth !== void 0) { spriteManager.useLogarithmicDepth = parsedSpriteManager?.useLogarithmicDepth; } if (parsedSpriteManager?.metadata !== void 0) { spriteManager.metadata = parsedSpriteManager?.metadata; } for (const parsedSprite of parsedSpriteManager?.sprites ?? []) { const sprite = Sprite.Parse(parsedSprite, spriteManager); sprite.uniqueId = parsedSprite.uniqueId; sprite.metadata = parsedSprite.metadata; } } __name(parseSerializedSpriteManager, "parseSerializedSpriteManager"); var registered5 = false; function registerSpriteManagerParser() { if (registered5) { return; } registered5 = true; AddParser("SpriteManagerNode", (parsedData, scene, container, rootUrl) => { parsedData.transformNodes?.forEach((transformNode) => { if (!transformNode.isSpriteManager) { return; } const instance = container.transformNodes?.find((t) => t.id === transformNode.id); if (!instance) { return; } instance.isSpriteManager = transformNode.isSpriteManager; if (transformNode.atlasJsonRelativePath) { const atlasJsonAbsolutePath = `${rootUrl}${transformNode.atlasJsonRelativePath}`; scene.addPendingData(atlasJsonAbsolutePath); const atlasRequest = new WebRequest(); atlasRequest.open("GET", atlasJsonAbsolutePath); atlasRequest.send(); atlasRequest.addEventListener("load", () => { scene.removePendingData(atlasJsonAbsolutePath); const atlasJson = JSON.parse(atlasRequest.responseText); const imagePath = `${Tools.GetFolderPath(atlasJsonAbsolutePath)}${atlasJson.meta.image}`; const spriteManager = new SpriteManager(instance.name, imagePath, 1e3, 64, scene, void 0, void 0, true, atlasJson); instance.spriteManager = spriteManager; if (transformNode.spriteManager) { parseSerializedSpriteManager(spriteManager, transformNode.spriteManager); } }); } else if (transformNode.spriteManager?.textureUrl) { const imagePath = `${rootUrl}${transformNode.spriteManager.textureUrl}`; const spriteManager = new SpriteManager(instance.name, imagePath, 1e3, { width: transformNode.spriteManager.cellWidth, height: transformNode.spriteManager.cellHeight }, scene, void 0, void 0, false); instance.spriteManager = spriteManager; if (transformNode.spriteManager) { parseSerializedSpriteManager(spriteManager, transformNode.spriteManager); } } }); }); } __name(registerSpriteManagerParser, "registerSpriteManagerParser"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/loading/loader.js init_math_vector(); async function loadScene(rootUrl, sceneFilename, scene, scriptsMap, options) { scene.loadingQuality = options?.quality ?? "high"; scene.loadingTexturesQuality = options?.texturesQuality ?? scene.loadingQuality; scene.loadingShadowsQuality = options?.shadowsQuality ?? scene.loadingQuality; registerAudioParser(); registerTextureParser(); registerShadowGeneratorParser(); registerSpriteMapParser(); registerSpriteManagerParser(); await AppendSceneAsync(`${rootUrl}${sceneFilename}`, scene, { pluginExtension: ".babylon", onProgress: /* @__PURE__ */ __name((event) => { const progress = Math.min(event.loaded / event.total * 0.5); options?.onProgress?.(progress); }, "onProgress") }); if (SceneLoaderFlags.ForceFullSceneLoadingForIncremental) { scene.meshes.forEach((m) => isMesh(m) && m._checkDelayState()); } const waitingItemsCount = scene.getWaitingItemsCount(); while (!scene.isDisposed && (!scene.isReady() || scene.getWaitingItemsCount() > 0)) { await new Promise((resolve) => setTimeout(resolve, 150)); const loadedItemsCount = waitingItemsCount - scene.getWaitingItemsCount(); if (loadedItemsCount === waitingItemsCount) { scene.textures.forEach((texture) => { if (texture.delayLoadState === Constants.DELAYLOADSTATE_NONE) { texture.delayLoadState = Constants.DELAYLOADSTATE_LOADED; } }); } options?.onProgress?.(0.5 + loadedItemsCount / waitingItemsCount * 0.5); } if (!options?.skipAssetsPreload) { await _preloadScriptsAssets(rootUrl, scene); } options?.onProgress?.(1); configureShadowMapRenderListPredicate(scene); configureShadowMapRefreshRate(scene); if (scene.metadata?.rendering) { applyRenderingConfigurations(scene, scene.metadata.rendering); if (scene.activeCamera) { applyRenderingConfigurationForCamera(scene.activeCamera, rootUrl); } } if (scene.metadata?.physicsGravity) { scene.getPhysicsEngine()?.setGravity(Vector3.FromArray(scene.metadata?.physicsGravity)); } _applyScriptsForObject(scene, scene, scriptsMap, rootUrl); scene.transformNodes.forEach((transformNode) => { _applyScriptsForObject(scene, transformNode, scriptsMap, rootUrl); }); scene.meshes.forEach((mesh) => { configurePhysicsAggregate(mesh); _applyScriptsForObject(scene, mesh, scriptsMap, rootUrl); }); scene.lights.forEach((light) => { _applyScriptsForObject(scene, light, scriptsMap, rootUrl); }); scene.cameras.forEach((camera) => { _applyScriptsForObject(scene, camera, scriptsMap, rootUrl); }); scene.spriteManagers?.forEach((spriteManager) => { spriteManager.sprites.forEach((sprite) => { _applyScriptsForObject(scene, sprite, scriptsMap, rootUrl); }); }); } __name(loadScene, "loadScene"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/loading/material.js init_tools(); async function loadMaterialFromFile(rootUrl, relativePath, scene) { const response = await fetch(rootUrl + relativePath); const data = await response.json(); const ctor = Tools.Instantiate(data.customType); const material = ctor.Parse(data, scene, rootUrl); material.id = data.id; material.uniqueId = data.uniqueId; return material; } __name(loadMaterialFromFile, "loadMaterialFromFile"); function forceCompileAllSceneMaterials(scene) { return Promise.all(scene.materials.map(async (material) => { const meshes = material.getBindedMeshes(); await Promise.all(meshes.map(async (mesh) => { if (isInstancedMesh(mesh)) { return; } await material.forceCompilationAsync(mesh, { clipPlane: !!scene.clipPlane, useInstances: mesh.hasInstances }); })); })); } __name(forceCompileAllSceneMaterials, "forceCompileAllSceneMaterials"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/tools/animation.js function getAnimationTypeForObject(effectiveProperty) { if (!isNaN(parseFloat(effectiveProperty)) && isFinite(effectiveProperty)) { return Animation.ANIMATIONTYPE_FLOAT; } switch (effectiveProperty?.getClassName?.()) { case "Vector2": return Animation.ANIMATIONTYPE_VECTOR2; case "Vector3": return Animation.ANIMATIONTYPE_VECTOR3; case "Quaternion": return Animation.ANIMATIONTYPE_QUATERNION; case "Color3": return Animation.ANIMATIONTYPE_COLOR3; case "Color4": return Animation.ANIMATIONTYPE_COLOR4; case "Size": return Animation.ANIMATIONTYPE_SIZE; case "Matrix": return Animation.ANIMATIONTYPE_MATRIX; } return null; } __name(getAnimationTypeForObject, "getAnimationTypeForObject"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/decorators/inspector.js function visibleAsBoolean(label, configuration) { return function(target, propertyKey) { const ctor = target.constructor; ctor._VisibleInInspector ??= []; ctor._VisibleInInspector.push({ label, propertyKey, configuration: { ...configuration, type: "boolean" } }); }; } __name(visibleAsBoolean, "visibleAsBoolean"); function visibleAsString(label, configuration) { return function(target, propertyKey) { const ctor = target.constructor; ctor._VisibleInInspector ??= []; ctor._VisibleInInspector.push({ label, propertyKey, configuration: { ...configuration, type: "string" } }); }; } __name(visibleAsString, "visibleAsString"); function visibleAsNumber(label, configuration) { return function(target, propertyKey) { const ctor = target.constructor; ctor._VisibleInInspector ??= []; ctor._VisibleInInspector.push({ label, propertyKey, configuration: { ...configuration, type: "number" } }); }; } __name(visibleAsNumber, "visibleAsNumber"); function visibleAsVector2(label, configuration) { return function(target, propertyKey) { const ctor = target.constructor; ctor._VisibleInInspector ??= []; ctor._VisibleInInspector.push({ label, propertyKey, configuration: { ...configuration, type: "vector2" } }); }; } __name(visibleAsVector2, "visibleAsVector2"); function visibleAsVector3(label, configuration) { return function(target, propertyKey) { const ctor = target.constructor; ctor._VisibleInInspector ??= []; ctor._VisibleInInspector.push({ label, propertyKey, configuration: { ...configuration, type: "vector3" } }); }; } __name(visibleAsVector3, "visibleAsVector3"); function visibleAsColor3(label, configuration) { return function(target, propertyKey) { const ctor = target.constructor; ctor._VisibleInInspector ??= []; ctor._VisibleInInspector.push({ label, propertyKey, configuration: { ...configuration, type: "color3" } }); }; } __name(visibleAsColor3, "visibleAsColor3"); function visibleAsColor4(label, configuration) { return function(target, propertyKey) { const ctor = target.constructor; ctor._VisibleInInspector ??= []; ctor._VisibleInInspector.push({ label, propertyKey, configuration: { ...configuration, type: "color4" } }); }; } __name(visibleAsColor4, "visibleAsColor4"); function visibleAsEntity(entityType, label, configuration) { return function(target, propertyKey) { const ctor = target.constructor; ctor._VisibleInInspector ??= []; ctor._VisibleInInspector.push({ label, propertyKey, configuration: { ...configuration, entityType, type: "entity" } }); }; } __name(visibleAsEntity, "visibleAsEntity"); function visibleAsTexture(label, configuration) { return function(target, propertyKey) { const ctor = target.constructor; ctor._VisibleInInspector ??= []; ctor._VisibleInInspector.push({ label, propertyKey, configuration: { ...configuration, type: "texture" } }); }; } __name(visibleAsTexture, "visibleAsTexture"); function visibleAsKeyMap(label, configuration) { return function(target, propertyKey) { const ctor = target.constructor; ctor._VisibleInInspector ??= []; ctor._VisibleInInspector.push({ label, propertyKey, configuration: { ...configuration, type: "keymap" } }); }; } __name(visibleAsKeyMap, "visibleAsKeyMap"); function visibleAsAsset(assetType, label, configuration) { return function(target, propertyKey) { const ctor = target.constructor; ctor._VisibleInInspector ??= []; ctor._VisibleInInspector.push({ label, propertyKey, configuration: { ...configuration, assetType, type: "asset" } }); }; } __name(visibleAsAsset, "visibleAsAsset"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/cinematic/tools.js function cloneKey(dataType, key) { let value; switch (dataType) { case Animation.ANIMATIONTYPE_FLOAT: value = key.value; break; default: value = key.value.clone(); break; } return { value, frame: key.frame, interpolation: key.interpolation, inTangent: dataType === Animation.ANIMATIONTYPE_FLOAT ? key.inTangent : key.inTangent?.clone(), outTangent: dataType === Animation.ANIMATIONTYPE_FLOAT ? key.outTangent : key.outTangent?.clone() }; } __name(cloneKey, "cloneKey"); function getPropertyValue(object, property) { const parts = property.split("."); let value = object; for (let i = 0; i < parts.length; ++i) { value = value[parts[i]]; } return value; } __name(getPropertyValue, "getPropertyValue"); function registerAfterAnimationCallback(cinematic, scene, callback) { let sceneRenderObserver = null; cinematic.onAnimationGroupPlayObservable.add(() => { sceneRenderObserver = scene.onAfterAnimationsObservable.add(() => { callback(); }); }); cinematic.onAnimationGroupPauseObservable.add(() => { if (sceneRenderObserver) { scene.onAfterAnimationsObservable.remove(sceneRenderObserver); sceneRenderObserver = null; } }); cinematic.onAnimationGroupEndObservable.add(() => { if (sceneRenderObserver) { scene.onAfterAnimationsObservable.remove(sceneRenderObserver); sceneRenderObserver = null; } }); } __name(registerAfterAnimationCallback, "registerAfterAnimationCallback"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/cinematic/parse.js init_math_color(); init_math_vector(); function parseCinematic(data, scene) { return { name: data.name, framesPerSecond: data.framesPerSecond, outputFramesPerSecond: data.outputFramesPerSecond, tracks: data.tracks.map((track) => { let node = null; let animationType = null; if (track.node) { node = scene.getNodeById(track.node); if (!node) { node = scene.particleSystems?.find((ps) => ps.id === track.node) ?? null; } } else if (track.defaultRenderingPipeline) { node = getDefaultRenderingPipeline(); } if (track.propertyPath) { const value = getPropertyValue(node, track.propertyPath); animationType = getAnimationTypeForObject(value); } let sound = null; if (track.sound) { sound = getSoundById(track.sound, scene); } return { node, sound, propertyPath: track.propertyPath, defaultRenderingPipeline: track.defaultRenderingPipeline, animationGroup: track.animationGroup ? scene.getAnimationGroupByName(track.animationGroup) : null, animationGroups: track.animationGroups, sounds: track.sounds, soundVolume: parseKeyFrameAnimations(track.soundVolume ?? [], Animation.ANIMATIONTYPE_FLOAT), keyFrameEvents: track.keyFrameEvents?.map((event) => { const result = { ...event }; switch (event.data?.type) { case "set-enabled": result.data = { type: "set-enabled", value: event.data.value, node: scene.getNodeById(event.data.node) }; break; case "apply-impulse": result.data = { type: "apply-impulse", radius: event.data.radius, mesh: scene.getMeshById(event.data.mesh), force: Vector3.FromArray(event.data.force), contactPoint: Vector3.FromArray(event.data.contactPoint) }; break; } return result; }), keyFrameAnimations: node && animationType !== null && parseKeyFrameAnimations(track.keyFrameAnimations ?? [], animationType) }; }) }; } __name(parseCinematic, "parseCinematic"); function parseCinematicKeyValue(value, type) { if (value === null) { return null; } if (value === void 0) { return void 0; } switch (type) { case Animation.ANIMATIONTYPE_FLOAT: return value; case Animation.ANIMATIONTYPE_VECTOR2: return Vector2.FromArray(value); case Animation.ANIMATIONTYPE_VECTOR3: return Vector3.FromArray(value); case Animation.ANIMATIONTYPE_QUATERNION: return Quaternion.FromArray(value); case Animation.ANIMATIONTYPE_COLOR3: return Color3.FromArray(value); case Animation.ANIMATIONTYPE_COLOR4: return Color4.FromArray(value); case Animation.ANIMATIONTYPE_MATRIX: return Matrix.FromArray(value); } } __name(parseCinematicKeyValue, "parseCinematicKeyValue"); function parseKeyFrameAnimations(keyFrameAnimations, animationType) { return keyFrameAnimations?.map((keyFrame) => { const animationKey = keyFrame.type === "key" ? keyFrame : null; if (animationKey) { return { ...animationKey, value: parseCinematicKeyValue(animationKey.value, animationType), inTangent: parseCinematicKeyValue(animationKey.inTangent, animationType), outTangent: parseCinematicKeyValue(animationKey.outTangent, animationType) }; } const animationKeyCut = keyFrame.type === "cut" ? keyFrame : null; if (animationKeyCut) { return { ...animationKeyCut, key1: { ...animationKeyCut.key1, value: parseCinematicKeyValue(animationKeyCut.key1.value, animationType), inTangent: parseCinematicKeyValue(animationKeyCut.key1.inTangent, animationType), outTangent: parseCinematicKeyValue(animationKeyCut.key1.outTangent, animationType) }, key2: { ...animationKeyCut.key2, value: parseCinematicKeyValue(animationKeyCut.key2.value, animationType), inTangent: parseCinematicKeyValue(animationKeyCut.key2.inTangent, animationType), outTangent: parseCinematicKeyValue(animationKeyCut.key2.outTangent, animationType) } }; } throw new Error(`Unknown key frame type: ${keyFrame.type}`); }); } __name(parseKeyFrameAnimations, "parseKeyFrameAnimations"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Animations/animationEvent.js var AnimationEvent = class _AnimationEvent { static { __name(this, "AnimationEvent"); } /** * 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 */ constructor(frame, action, onlyOnce) { this.frame = frame; this.action = action; this.onlyOnce = onlyOnce; this.isDone = false; } /** @internal */ _clone() { return new _AnimationEvent(this.frame, this.action, this.onlyOnce); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/cinematic/events/event.js function handleApplyEvent(cinematic, eventData) { cinematic.onEventObservable.notifyObservers(eventData.eventName); } __name(handleApplyEvent, "handleApplyEvent"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/cinematic/events/set-enabled.js function handleSetEnabledEvent(config) { config.node?.setEnabled(config.value); } __name(handleSetEnabledEvent, "handleSetEnabledEvent"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/cinematic/events/apply-impulse.js init_math_vector(); var zeroVector = Vector3.Zero(); function handleApplyImpulseEvent(scene, config) { let meshes = config.mesh ? [config.mesh] : scene.meshes.filter((m) => m.physicsAggregate); if (config.radius) { meshes = meshes.filter((mesh) => { const centerWorld = mesh.getBoundingInfo().boundingBox.centerWorld; return Vector3.Distance(centerWorld, config.contactPoint) <= config.radius; }); } meshes.forEach((mesh) => { if (mesh.physicsAggregate?.body) { const direction = config.contactPoint.subtract(mesh.getBoundingInfo().boundingBox.centerWorld); direction.multiplyInPlace(config.force); mesh.physicsAggregate.body.setLinearVelocity(zeroVector); mesh.physicsAggregate.body.setAngularVelocity(zeroVector); mesh.physicsAggregate.body.applyImpulse(direction.negateInPlace(), config.contactPoint); } }); } __name(handleApplyImpulseEvent, "handleApplyImpulseEvent"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/@babylonjs/core/Animations/animationGroup.js init_observable(); init_engineStore(); init_tags(); init_uniqueIdGenerator(); var TargetedAnimation = class { static { __name(this, "TargetedAnimation"); } /** * Returns the string "TargetedAnimation" * @returns "TargetedAnimation" */ getClassName() { return "TargetedAnimation"; } /** * Creates a new targeted animation * @param parent The animation group to which the animation belongs */ constructor(parent) { this.parent = parent; this.uniqueId = UniqueIdGenerator.UniqueId; } /** * Serialize the object * @returns the JSON object representing the current entity */ serialize() { const serializationObject = {}; serializationObject.animation = this.animation.serialize(); serializationObject.targetId = this.target.id; return serializationObject; } }; var AnimationGroup = class _AnimationGroup { static { __name(this, "AnimationGroup"); } /** * Gets or sets the mask associated with this animation group. This mask is used to filter which objects should be animated. */ get mask() { return this._mask; } set mask(value) { if (this._mask === value) { return; } this._mask = value; this.syncWithMask(true); } /** * Makes sure that the animations are either played or stopped according to the animation group mask. * Note however that the call won't have any effect if the animation group has not been started yet. * @param forceUpdate If true, forces to loop over the animatables even if no mask is defined (used internally, you shouldn't need to use it). Default: false. */ syncWithMask(forceUpdate = false) { if (!this.mask && !forceUpdate) { this._numActiveAnimatables = this._targetedAnimations.length; return; } this._numActiveAnimatables = 0; for (let i = 0; i < this._animatables.length; ++i) { const animatable = this._animatables[i]; if (!this.mask || this.mask.disabled || this.mask.retainsTarget(animatable.target.name)) { this._numActiveAnimatables++; if (animatable.paused) { animatable.restart(); } } else { if (!animatable.paused) { animatable.pause(); } } } } /** * Removes all animations for the targets not retained by the animation group mask. * Use this function if you know you won't need those animations anymore and if you want to free memory. */ removeUnmaskedAnimations() { if (!this.mask || this.mask.disabled) { return; } for (let i = 0; i < this._animatables.length; ++i) { const animatable = this._animatables[i]; if (!this.mask.retainsTarget(animatable.target.name)) { animatable.stop(); this._animatables.splice(i, 1); --i; } } for (let index = 0; index < this._targetedAnimations.length; index++) { const targetedAnimation = this._targetedAnimations[index]; if (!this.mask.retainsTarget(targetedAnimation.target.name)) { this._targetedAnimations.splice(index, 1); --index; } } } /** * Gets or sets the first frame */ get from() { return this._from; } set from(value) { if (this._from === value) { return; } this._from = value; for (let index = 0; index < this._animatables.length; index++) { const animatable = this._animatables[index]; animatable.fromFrame = this._from; } } /** * Gets or sets the last frame */ get to() { return this._to; } set to(value) { if (this._to === value) { return; } this._to = value; for (let index = 0; index < this._animatables.length; index++) { const animatable = this._animatables[index]; animatable.toFrame = this._to; } } /** * Define if the animations are started */ get isStarted() { return this._isStarted; } /** * Gets a value indicating that the current group is playing */ get isPlaying() { return this._isStarted && !this._isPaused; } /** * Gets or sets the speed ratio to use for all animations */ get speedRatio() { return this._speedRatio; } /** * Gets or sets the speed ratio to use for all animations */ set speedRatio(value) { if (this._speedRatio === value) { return; } this._speedRatio = value; for (let index = 0; index < this._animatables.length; index++) { const animatable = this._animatables[index]; animatable.speedRatio = this._speedRatio; } } /** * Gets or sets if all animations should loop or not */ get loopAnimation() { return this._loopAnimation; } set loopAnimation(value) { if (this._loopAnimation === value) { return; } this._loopAnimation = value; for (let index = 0; index < this._animatables.length; index++) { const animatable = this._animatables[index]; animatable.loopAnimation = this._loopAnimation; } } /** * Gets or sets if all animations should be evaluated additively */ get isAdditive() { return this._isAdditive; } set isAdditive(value) { if (this._isAdditive === value) { return; } this._isAdditive = value; for (let index = 0; index < this._animatables.length; index++) { const animatable = this._animatables[index]; animatable.isAdditive = this._isAdditive; } } /** * Gets or sets the weight to apply to all animations of the group */ get weight() { return this._weight; } set weight(value) { if (this._weight === value) { return; } this._weight = value; this.setWeightForAllAnimatables(this._weight); } /** * Gets the targeted animations for this animation group */ get targetedAnimations() { return this._targetedAnimations; } /** * returning the list of animatables controlled by this animation group. */ get animatables() { return this._animatables; } /** * Gets the list of target animations */ get children() { return this._targetedAnimations; } /** * Gets or sets the order of play of the animation group (default: 0) */ get playOrder() { return this._playOrder; } set playOrder(value) { if (this._playOrder === value) { return; } this._playOrder = value; if (this._animatables.length > 0) { for (let i = 0; i < this._animatables.length; i++) { this._animatables[i].playOrder = this._playOrder; } this._scene.sortActiveAnimatables(); } } /** * Allows the animations of the animation group to blend with current running animations * Note that a null value means that each animation will use their own existing blending configuration (Animation.enableBlending) */ get enableBlending() { return this._enableBlending; } set enableBlending(value) { if (this._enableBlending === value) { return; } this._enableBlending = value; if (value !== null) { for (let i = 0; i < this._targetedAnimations.length; ++i) { this._targetedAnimations[i].animation.enableBlending = value; } } } /** * Gets or sets the animation blending speed * Note that a null value means that each animation will use their own existing blending configuration (Animation.blendingSpeed) */ get blendingSpeed() { return this._blendingSpeed; } set blendingSpeed(value) { if (this._blendingSpeed === value) { return; } this._blendingSpeed = value; if (value !== null) { for (let i = 0; i < this._targetedAnimations.length; ++i) { this._targetedAnimations[i].animation.blendingSpeed = value; } } } /** * Gets the length (in seconds) of the animation group * This function assumes that all animations are played at the same framePerSecond speed! * Note: you can only call this method after you've added at least one targeted animation! * @param from Starting frame range (default is AnimationGroup.from) * @param to Ending frame range (default is AnimationGroup.to) * @returns The length in seconds */ getLength(from, to) { from = from ?? this._from; to = to ?? this._to; const fps = this.targetedAnimations[0].animation.framePerSecond * this._speedRatio; return (to - from) / fps; } /** * Merge the array of animation groups into a new animation group * @param animationGroups List of animation groups to merge * @param disposeSource If true, animation groups will be disposed after being merged (default: true) * @param normalize If true, animation groups will be normalized before being merged, so that all animations have the same "from" and "to" frame (default: false) * @param weight Weight for the new animation group. If not provided, it will inherit the weight from the first animation group of the array * @returns The new animation group or null if no animation groups were passed */ static MergeAnimationGroups(animationGroups, disposeSource = true, normalize = false, weight) { if (animationGroups.length === 0) { return null; } weight = weight ?? animationGroups[0].weight; let beginFrame = Number.MAX_VALUE; let endFrame = -Number.MAX_VALUE; if (normalize) { for (const animationGroup of animationGroups) { if (animationGroup.from < beginFrame) { beginFrame = animationGroup.from; } if (animationGroup.to > endFrame) { endFrame = animationGroup.to; } } } const mergedAnimationGroup = new _AnimationGroup(animationGroups[0].name + "_merged", animationGroups[0]._scene, weight); for (const animationGroup of animationGroups) { if (normalize) { animationGroup.normalize(beginFrame, endFrame); } for (const targetedAnimation of animationGroup.targetedAnimations) { mergedAnimationGroup.addTargetedAnimation(targetedAnimation.animation, targetedAnimation.target); } if (disposeSource) { animationGroup.dispose(); } } return mergedAnimationGroup; } /** * Gets the scene the animation group belongs to * @returns The scene the animation group belongs to */ getScene() { return this._scene; } /** * Instantiates a new Animation Group. * This helps managing several animations at once. * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/groupAnimations * @param name Defines the name of the group * @param scene Defines the scene the group belongs to * @param weight Defines the weight to use for animations in the group (-1.0 by default, meaning "no weight") * @param playOrder Defines the order of play of the animation group (default is 0) */ constructor(name260, scene = null, weight = -1, playOrder = 0) { this.name = name260; 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._weight = -1; this._playOrder = 0; this._enableBlending = null; this._blendingSpeed = null; this._numActiveAnimatables = 0; this._shouldStart = true; this._parentContainer = null; this.onAnimationEndObservable = new Observable(); this.onAnimationLoopObservable = new Observable(); this.onAnimationGroupLoopObservable = new Observable(); this.onAnimationGroupEndObservable = new Observable(); this.onAnimationGroupPauseObservable = new Observable(); this.onAnimationGroupPlayObservable = new Observable(); this.metadata = null; this._mask = null; this._animationLoopFlags = []; this._scene = scene || EngineStore.LastCreatedScene; this._weight = weight; this._playOrder = playOrder; this.uniqueId = this._scene.getUniqueId(); this._scene.addAnimationGroup(this); } /** * 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 */ addTargetedAnimation(animation, target) { const targetedAnimation = new TargetedAnimation(this); targetedAnimation.animation = animation; targetedAnimation.target = target; const 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; } if (this._enableBlending !== null) { animation.enableBlending = this._enableBlending; } if (this._blendingSpeed !== null) { animation.blendingSpeed = this._blendingSpeed; } this._targetedAnimations.push(targetedAnimation); this._shouldStart = true; return targetedAnimation; } /** * Remove an animation from the group * @param animation defines the animation we want to remove */ removeTargetedAnimation(animation) { for (let index = this._targetedAnimations.length - 1; index > -1; index--) { const targetedAnimation = this._targetedAnimations[index]; if (targetedAnimation.animation === animation) { this._targetedAnimations.splice(index, 1); } } } /** * 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 */ normalize(beginFrame = null, endFrame = null) { if (beginFrame == null) { beginFrame = this._from; } if (endFrame == null) { endFrame = this._to; } for (let index = 0; index < this._targetedAnimations.length; index++) { const targetedAnimation = this._targetedAnimations[index]; const keys = targetedAnimation.animation.getKeys(); const startKey = keys[0]; const endKey = keys[keys.length - 1]; if (startKey.frame > beginFrame) { const newKey = { frame: beginFrame, value: startKey.value, inTangent: startKey.inTangent, outTangent: startKey.outTangent, interpolation: startKey.interpolation }; keys.splice(0, 0, newKey); } if (endKey.frame < endFrame) { const newKey = { frame: endFrame, value: endKey.value, inTangent: endKey.inTangent, outTangent: endKey.outTangent, interpolation: endKey.interpolation }; keys.push(newKey); } } this._from = beginFrame; this._to = endFrame; return this; } _processLoop(animatable, targetedAnimation, index) { animatable.onAnimationLoop = () => { this.onAnimationLoopObservable.notifyObservers(targetedAnimation); if (this._animationLoopFlags[index]) { return; } this._animationLoopFlags[index] = true; this._animationLoopCount++; if (this._animationLoopCount === this._numActiveAnimatables) { this.onAnimationGroupLoopObservable.notifyObservers(this); this._animationLoopCount = 0; this._animationLoopFlags.length = 0; } }; } /** * 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 */ start(loop = false, speedRatio = 1, from, to, isAdditive) { if (this._isStarted || this._targetedAnimations.length === 0) { return this; } this._loopAnimation = loop; this._shouldStart = false; this._animationLoopCount = 0; this._animationLoopFlags.length = 0; for (let index = 0; index < this._targetedAnimations.length; index++) { const targetedAnimation = this._targetedAnimations[index]; const animatable = this._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== void 0 ? from : this._from, to !== void 0 ? to : this._to, loop, speedRatio, void 0, void 0, isAdditive !== void 0 ? isAdditive : this._isAdditive); animatable.weight = this._weight; animatable.playOrder = this._playOrder; animatable.onAnimationEnd = () => { this.onAnimationEndObservable.notifyObservers(targetedAnimation); this._checkAnimationGroupEnded(animatable); }; this._processLoop(animatable, targetedAnimation, index); this._animatables.push(animatable); } this.syncWithMask(); this._scene.sortActiveAnimatables(); this._speedRatio = speedRatio; this._isStarted = true; this._isPaused = false; this.onAnimationGroupPlayObservable.notifyObservers(this); return this; } /** * Pause all animations * @returns the animation group */ pause() { if (!this._isStarted) { return this; } this._isPaused = true; for (let index = 0; index < this._animatables.length; index++) { const 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 */ play(loop) { if (this.isStarted && this._animatables.length && !this._shouldStart) { if (loop !== void 0) { this.loopAnimation = loop; } this.restart(); } else { this.stop(); this.start(loop, this._speedRatio); } return this; } /** * Reset all animations to initial state * @returns the animation group */ reset() { if (!this._isStarted) { this.play(); this.goToFrame(0); this.stop(true); return this; } for (let index = 0; index < this._animatables.length; index++) { const animatable = this._animatables[index]; animatable.reset(); } return this; } /** * Restart animations from after pausing it * @returns the animation group */ restart() { if (!this._isStarted) { return this; } for (let index = 0; index < this._animatables.length; index++) { const animatable = this._animatables[index]; animatable.restart(); } this.syncWithMask(); this._isPaused = false; this.onAnimationGroupPlayObservable.notifyObservers(this); return this; } /** * Stop all animations * @param skipOnAnimationEnd defines if the system should not raise onAnimationEnd. Default is false * @returns the animation group */ stop(skipOnAnimationEnd = false) { if (!this._isStarted) { return this; } const list = this._animatables.slice(); for (let index = 0; index < list.length; index++) { list[index].stop(void 0, void 0, true, skipOnAnimationEnd); } let curIndex = 0; for (let index = 0; index < this._scene._activeAnimatables.length; index++) { const animatable = this._scene._activeAnimatables[index]; if (animatable._runtimeAnimations.length > 0) { this._scene._activeAnimatables[curIndex++] = animatable; } else if (skipOnAnimationEnd) { this._checkAnimationGroupEnded(animatable, skipOnAnimationEnd); } } this._scene._activeAnimatables.length = curIndex; this._isStarted = false; return this; } /** * Set animation weight for all animatables * * @since 6.12.4 * You can pass the weight to the AnimationGroup constructor, or use the weight property to set it after the group has been created, * making it easier to define the overall animation weight than calling setWeightForAllAnimatables() after the animation group has been started * @param weight defines the weight to use * @returns the animationGroup * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-weights */ setWeightForAllAnimatables(weight) { for (let index = 0; index < this._animatables.length; index++) { const 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 (null to stop synchronizing) * @returns the animationGroup * @see https://doc.babylonjs.com/features/featuresDeepDive/animation/advanced_animations#animation-weights */ syncAllAnimationsWith(root) { for (let index = 0; index < this._animatables.length; index++) { const animatable = this._animatables[index]; animatable.syncWith(root); } return this; } /** * Goes to a specific frame in this animation group. Note that the animation group must be in playing or paused status * @param frame the frame number to go to * @param useWeight defines whether the animation weight should be applied to the image to be jumped to (false by default) * @returns the animationGroup */ goToFrame(frame, useWeight = false) { if (!this._isStarted) { return this; } for (let index = 0; index < this._animatables.length; index++) { const animatable = this._animatables[index]; animatable.goToFrame(frame, useWeight); } return this; } /** * Helper to get the current frame. This will return 0 if the AnimationGroup is not running, and it might return wrong results if multiple animations are running in different frames. * @returns current animation frame. */ getCurrentFrame() { return this.animatables[0]?.masterFrame || 0; } /** * Dispose all associated resources */ dispose() { if (this.isStarted) { this.stop(); } this._targetedAnimations.length = 0; this._animatables.length = 0; const index = this._scene.animationGroups.indexOf(this); if (index > -1) { this._scene.animationGroups.splice(index, 1); } if (this._parentContainer) { const index2 = this._parentContainer.animationGroups.indexOf(this); if (index2 > -1) { this._parentContainer.animationGroups.splice(index2, 1); } this._parentContainer = null; } this.onAnimationEndObservable.clear(); this.onAnimationGroupEndObservable.clear(); this.onAnimationGroupPauseObservable.clear(); this.onAnimationGroupPlayObservable.clear(); this.onAnimationLoopObservable.clear(); this.onAnimationGroupLoopObservable.clear(); } _checkAnimationGroupEnded(animatable, skipOnAnimationEnd = false) { const idx = this._animatables.indexOf(animatable); if (idx > -1) { this._animatables.splice(idx, 1); } if (this._animatables.length === this._targetedAnimations.length - this._numActiveAnimatables) { this._isStarted = false; if (!skipOnAnimationEnd) { this.onAnimationGroupEndObservable.notifyObservers(this); } this._animatables.length = 0; } } /** * 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 * @param cloneAnimations defines if the animations should be cloned or referenced * @returns the new animation group */ clone(newName, targetConverter, cloneAnimations = false) { const newGroup = new _AnimationGroup(newName || this.name, this._scene, this._weight, this._playOrder); newGroup._from = this.from; newGroup._to = this.to; newGroup._speedRatio = this.speedRatio; newGroup._loopAnimation = this.loopAnimation; newGroup._isAdditive = this.isAdditive; newGroup._enableBlending = this.enableBlending; newGroup._blendingSpeed = this.blendingSpeed; newGroup.metadata = this.metadata; newGroup.mask = this.mask; for (const targetAnimation of this._targetedAnimations) { newGroup.addTargetedAnimation(cloneAnimations ? targetAnimation.animation.clone() : targetAnimation.animation, targetConverter ? targetConverter(targetAnimation.target) : targetAnimation.target); } return newGroup; } /** * Serializes the animationGroup to an object * @returns Serialized object */ serialize() { const serializationObject = {}; serializationObject.name = this.name; serializationObject.from = this.from; serializationObject.to = this.to; serializationObject.speedRatio = this.speedRatio; serializationObject.loopAnimation = this.loopAnimation; serializationObject.isAdditive = this.isAdditive; serializationObject.weight = this.weight; serializationObject.playOrder = this.playOrder; serializationObject.enableBlending = this.enableBlending; serializationObject.blendingSpeed = this.blendingSpeed; serializationObject.targetedAnimations = []; for (let targetedAnimationIndex = 0; targetedAnimationIndex < this.targetedAnimations.length; targetedAnimationIndex++) { const targetedAnimation = this.targetedAnimations[targetedAnimationIndex]; serializationObject.targetedAnimations[targetedAnimationIndex] = targetedAnimation.serialize(); } if (Tags && Tags.HasTags(this)) { serializationObject.tags = Tags.GetTags(this); } if (this.metadata) { serializationObject.metadata = this.metadata; } 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 * @param nodeMap a map of node.id to node in this scene, to accelerate node lookup * @returns a new AnimationGroup */ static Parse(parsedAnimationGroup, scene, nodeMap) { const animationGroup = new _AnimationGroup(parsedAnimationGroup.name, scene, parsedAnimationGroup.weight, parsedAnimationGroup.playOrder); for (let i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) { const targetedAnimation = parsedAnimationGroup.targetedAnimations[i]; const animation = Animation.Parse(targetedAnimation.animation); const id = targetedAnimation.targetId; if (targetedAnimation.animation.property === "influence") { const morphTarget = scene.getMorphTargetById(id); if (morphTarget) { animationGroup.addTargetedAnimation(animation, morphTarget); } } else { const targetNode = nodeMap ? nodeMap.get(id) : scene.getNodeById(id); if (targetNode != null) { animationGroup.addTargetedAnimation(animation, targetNode); } } } if (Tags) { Tags.AddTagsTo(animationGroup, parsedAnimationGroup.tags); } if (parsedAnimationGroup.from !== null && parsedAnimationGroup.to !== null) { animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to); } if (parsedAnimationGroup.speedRatio !== void 0) { animationGroup._speedRatio = parsedAnimationGroup.speedRatio; } if (parsedAnimationGroup.loopAnimation !== void 0) { animationGroup._loopAnimation = parsedAnimationGroup.loopAnimation; } if (parsedAnimationGroup.isAdditive !== void 0) { animationGroup._isAdditive = parsedAnimationGroup.isAdditive; } if (parsedAnimationGroup.weight !== void 0) { animationGroup._weight = parsedAnimationGroup.weight; } if (parsedAnimationGroup.playOrder !== void 0) { animationGroup._playOrder = parsedAnimationGroup.playOrder; } if (parsedAnimationGroup.enableBlending !== void 0) { animationGroup._enableBlending = parsedAnimationGroup.enableBlending; } if (parsedAnimationGroup.blendingSpeed !== void 0) { animationGroup._blendingSpeed = parsedAnimationGroup.blendingSpeed; } if (parsedAnimationGroup.metadata !== void 0) { animationGroup.metadata = parsedAnimationGroup.metadata; } return animationGroup; } /** @internal */ static MakeAnimationAdditive(sourceAnimationGroup, referenceFrameOrOptions, range, cloneOriginal = false, clonedName) { let options; if (typeof referenceFrameOrOptions === "object") { options = referenceFrameOrOptions; } else { options = { referenceFrame: referenceFrameOrOptions, range, cloneOriginalAnimationGroup: cloneOriginal, clonedAnimationName: clonedName }; } let animationGroup = sourceAnimationGroup; if (options.cloneOriginalAnimationGroup) { animationGroup = sourceAnimationGroup.clone(options.clonedAnimationGroupName || animationGroup.name); } const targetedAnimations = animationGroup.targetedAnimations; for (let index = 0; index < targetedAnimations.length; index++) { const targetedAnimation = targetedAnimations[index]; targetedAnimation.animation = Animation.MakeAnimationAdditive(targetedAnimation.animation, options); } animationGroup.isAdditive = true; if (options.clipKeys) { let from = Number.MAX_VALUE; let to = -Number.MAX_VALUE; const targetedAnimations2 = animationGroup.targetedAnimations; for (let index = 0; index < targetedAnimations2.length; index++) { const targetedAnimation = targetedAnimations2[index]; const animation = targetedAnimation.animation; const keys = animation.getKeys(); if (from > keys[0].frame) { from = keys[0].frame; } if (to < keys[keys.length - 1].frame) { to = keys[keys.length - 1].frame; } } animationGroup._from = from; animationGroup._to = to; } return animationGroup; } /** * Creates a new animation, keeping only the keys that are inside a given key range * @param sourceAnimationGroup defines the animation group on which to operate * @param fromKey defines the lower bound of the range * @param toKey defines the upper bound of the range * @param name defines the name of the new animation group. If not provided, use the same name as animationGroup * @param dontCloneAnimations defines whether or not the animations should be cloned before clipping the keys. Default is false, so animations will be cloned * @returns a new animation group stripped from all the keys outside the given range */ static ClipKeys(sourceAnimationGroup, fromKey, toKey, name260, dontCloneAnimations) { const animationGroup = sourceAnimationGroup.clone(name260 || sourceAnimationGroup.name); return _AnimationGroup.ClipKeysInPlace(animationGroup, fromKey, toKey, dontCloneAnimations); } /** * Updates an existing animation, keeping only the keys that are inside a given key range * @param animationGroup defines the animation group on which to operate * @param fromKey defines the lower bound of the range * @param toKey defines the upper bound of the range * @param dontCloneAnimations defines whether or not the animations should be cloned before clipping the keys. Default is false, so animations will be cloned * @returns the animationGroup stripped from all the keys outside the given range */ static ClipKeysInPlace(animationGroup, fromKey, toKey, dontCloneAnimations) { return _AnimationGroup.ClipInPlace(animationGroup, fromKey, toKey, dontCloneAnimations, false); } /** * Creates a new animation, keeping only the frames that are inside a given frame range * @param sourceAnimationGroup defines the animation group on which to operate * @param fromFrame defines the lower bound of the range * @param toFrame defines the upper bound of the range * @param name defines the name of the new animation group. If not provided, use the same name as animationGroup * @param dontCloneAnimations defines whether or not the animations should be cloned before clipping the frames. Default is false, so animations will be cloned * @returns a new animation group stripped from all the frames outside the given range */ static ClipFrames(sourceAnimationGroup, fromFrame, toFrame, name260, dontCloneAnimations) { const animationGroup = sourceAnimationGroup.clone(name260 || sourceAnimationGroup.name); return _AnimationGroup.ClipFramesInPlace(animationGroup, fromFrame, toFrame, dontCloneAnimations); } /** * Updates an existing animation, keeping only the frames that are inside a given frame range * @param animationGroup defines the animation group on which to operate * @param fromFrame defines the lower bound of the range * @param toFrame defines the upper bound of the range * @param dontCloneAnimations defines whether or not the animations should be cloned before clipping the frames. Default is false, so animations will be cloned * @returns the animationGroup stripped from all the frames outside the given range */ static ClipFramesInPlace(animationGroup, fromFrame, toFrame, dontCloneAnimations) { return _AnimationGroup.ClipInPlace(animationGroup, fromFrame, toFrame, dontCloneAnimations, true); } /** * Updates an existing animation, keeping only the keys that are inside a given key or frame range * @param animationGroup defines the animation group on which to operate * @param start defines the lower bound of the range * @param end defines the upper bound of the range * @param dontCloneAnimations defines whether or not the animations should be cloned before clipping the keys. Default is false, so animations will be cloned * @param useFrame defines if the range is defined by frame numbers or key indices (default is false which means use key indices) * @returns the animationGroup stripped from all the keys outside the given range */ static ClipInPlace(animationGroup, start, end, dontCloneAnimations, useFrame = false) { let from = Number.MAX_VALUE; let to = -Number.MAX_VALUE; const targetedAnimations = animationGroup.targetedAnimations; for (let index = 0; index < targetedAnimations.length; index++) { const targetedAnimation = targetedAnimations[index]; const animation = dontCloneAnimations ? targetedAnimation.animation : targetedAnimation.animation.clone(); if (useFrame) { animation.createKeyForFrame(start); animation.createKeyForFrame(end); } const keys = animation.getKeys(); const newKeys = []; let startFrame = Number.MAX_VALUE; for (let k = 0; k < keys.length; k++) { const key = keys[k]; if (!useFrame && k >= start && k <= end || useFrame && key.frame >= start && key.frame <= end) { const newKey = { frame: key.frame, value: key.value.clone ? key.value.clone() : key.value, inTangent: key.inTangent, outTangent: key.outTangent, interpolation: key.interpolation, lockedTangent: key.lockedTangent }; if (startFrame === Number.MAX_VALUE) { startFrame = newKey.frame; } newKey.frame -= startFrame; newKeys.push(newKey); } } if (newKeys.length === 0) { targetedAnimations.splice(index, 1); index--; continue; } if (from > newKeys[0].frame) { from = newKeys[0].frame; } if (to < newKeys[newKeys.length - 1].frame) { to = newKeys[newKeys.length - 1].frame; } animation.setKeys(newKeys, true); targetedAnimation.animation = animation; } animationGroup._from = from; animationGroup._to = to; return animationGroup; } /** * Returns the string "AnimationGroup" * @returns "AnimationGroup" */ getClassName() { return "AnimationGroup"; } /** * Creates a detailed 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 */ toString(fullDetails) { let 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; } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/cinematic/cinematic.js init_observable(); var Cinematic = class extends AnimationGroup { static { __name(this, "Cinematic"); } /** * Defines the observable used to notify observers when an event is raised during the cinematic playback. */ onEventObservable = new Observable(); /** * Registers and calls the given callback on the provided event name is emitted during the cinematic playback. * @param eventName defines the name of the event to listen to * @param callback defines the callback to call when the event is raised */ onEvent(eventName, callback) { this.onEventObservable.add((event) => { if (eventName === event) { callback(); } }); } }; // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/cinematic/guards.js function isCinematicKey(key) { return key.type === "key"; } __name(isCinematicKey, "isCinematicKey"); function isCinematicKeyCut(key) { return key.type === "cut"; } __name(isCinematicKeyCut, "isCinematicKeyCut"); function isCinematicKeyEvent(key) { return key.type === "event"; } __name(isCinematicKeyEvent, "isCinematicKeyEvent"); function isCinematicGroup(key) { return key.type === "group"; } __name(isCinematicGroup, "isCinematicGroup"); function isCinematicSound(key) { return key.type === "sound"; } __name(isCinematicSound, "isCinematicSound"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/node_modules/babylonjs-editor-tools/build/src/cinematic/generate.js function generateCinematicAnimationGroup(cinematic, scene, options) { const result = new Cinematic(cinematic.name, scene); cinematic.tracks.forEach((track) => { const animationGroup = track.animationGroup; if (animationGroup && track.animationGroups?.length) { const effectiveAnimationGroup = animationGroup.clone(`${animationGroup.name}-cinematic-temp`); const index = scene.animationGroups.indexOf(effectiveAnimationGroup); if (index !== -1) { scene.animationGroups.splice(index, 1); } result.onAnimationEndObservable.add(() => { animationGroup.stop(); effectiveAnimationGroup.stop(); }); const minFrame = track.animationGroups.reduce((prev, curr) => Math.min(prev, curr.frame), Number.MAX_VALUE) ?? 0; const maxFrame = track.animationGroups.reduce((prev, curr) => Math.max(prev, curr.frame + curr.endFrame), 0) ?? 0; const dummyObject = { frame: minFrame }; const animationGroupsAnimation = new Animation(effectiveAnimationGroup.name, "frame", 60, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE, false); animationGroupsAnimation.setKeys([ { frame: minFrame, value: 0 }, { frame: maxFrame, value: maxFrame } ]); track.animationGroups.forEach((configuration) => { animationGroupsAnimation.addEvent(new AnimationEvent(configuration.frame, () => { const repeatCount = configuration.repeatCount ?? 0; effectiveAnimationGroup.to = configuration.endFrame; effectiveAnimationGroup.speedRatio = configuration.speed; effectiveAnimationGroup.stop(); effectiveAnimationGroup.play(repeatCount > 0); effectiveAnimationGroup.goToFrame(configuration.startFrame); if (repeatCount) { let currentRepeatCount = 0; effectiveAnimationGroup.onAnimationGroupLoopObservable.add(() => { ++currentRepeatCount; if (currentRepeatCount > repeatCount) { effectiveAnimationGroup.stop(); } }); } })); }); result.addTargetedAnimation(animationGroupsAnimation, dummyObject); if ((track.animationGroupWeight?.length ?? 0) >= 2) { const dummyObject2 = { weight: 0 }; const weightAnimation = new Animation(`${effectiveAnimationGroup.name}-weights`, "weight", 60, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE, false); const weightKeys = []; track.animationGroupWeight.forEach((keyFrame) => { if (isCinematicKeyCut(keyFrame)) { weightKeys.push(keyFrame.key1); weightKeys.push(keyFrame.key2); } else { weightKeys.push(keyFrame); } }); weightAnimation.setKeys(weightKeys); result.addTargetedAnimation(weightAnimation, dummyObject2); registerAfterAnimationCallback(result, scene, () => { effectiveAnimationGroup.weight = dummyObject2.weight; }); } } const sound = track.sound; const soundBuffer = sound?.getAudioBuffer(); if (!options?.ignoreSounds && sound && soundBuffer && track.sounds?.length) { const dummyObject = { dummy: 0, volume: 0 }; const soundAnimation = new Animation(sound.name, "dummy", 60, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE, false); let maxFrame = 0; track.sounds?.forEach((configuration) => { const duration = configuration.endFrame - configuration.startFrame; maxFrame = Math.max(maxFrame, configuration.frame + duration); soundAnimation.addEvent(new AnimationEvent(configuration.frame, (currentFrame) => { const frameDiff = currentFrame - configuration.frame; const offset = (frameDiff + configuration.startFrame) / cinematic.framesPerSecond; sound.play(0, offset); }, false)); soundAnimation.addEvent(new AnimationEvent(configuration.frame + duration, () => { sound.stop(); })); }); soundAnimation.setKeys([ { frame: 0, value: 0 }, { frame: maxFrame, value: maxFrame } ]); result.addTargetedAnimation(soundAnimation, dummyObject); if ((track.soundVolume?.length ?? 0) >= 2) { const volumeAnimation = new Animation(sound.name, "volume", 60, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE, false); const volumeKeys = []; track.soundVolume.forEach((keyFrame) => { if (isCinematicKeyCut(keyFrame)) { volumeKeys.push(keyFrame.key1); volumeKeys.push(keyFrame.key2); } else { volumeKeys.push(keyFrame); } }); volumeAnimation.setKeys(volumeKeys); result.addTargetedAnimation(volumeAnimation, dummyObject); registerAfterAnimationCallback(result, scene, () => { sound.setVolume(dummyObject.volume); }); } } if (track.keyFrameEvents) { const dummyObject = { dummy: 0 }; const eventsAnimation = new Animation("events", "dummy", 60, Animation.ANIMATIONTYPE_FLOAT, Animation.ANIMATIONLOOPMODE_CYCLE, false); let maxFrame = 0; track.keyFrameEvents?.forEach((configuration) => { maxFrame = Math.max(maxFrame, configuration.frame); eventsAnimation.addEvent(new AnimationEvent(configuration.frame, () => { switch (configuration.data?.type) { case "event": handleApplyEvent(result, configuration.data); break; case "set-enabled": handleSetEnabledEvent(configuration.data); break; case "apply-impulse": handleApplyImpulseEvent(scene, configuration.data); break; } })); }); eventsAnimation.setKeys([ { frame: 0, value: 0 }, { frame: maxFrame + 1, value: maxFrame + 1 } ]); result.addTargetedAnimation(eventsAnimation, dummyObject); } const node = track.defaultRenderingPipeline ? getDefaultRenderingPipeline() : track.node; if (!node || !track.propertyPath || !track.keyFrameAnimations) { return; } const value = getPropertyValue(node, track.propertyPath); const animationType = getAnimationTypeForObject(value); if (animationType === null) { return; } const animation = new Animation(track.propertyPath, track.propertyPath, 60, animationType, Animation.ANIMATIONLOOPMODE_CYCLE, false); const keys = []; track.keyFrameAnimations?.forEach((keyFrame) => { if (isCinematicKey(keyFrame)) { return keys.push(keyFrame); } if (isCinematicKeyCut(keyFrame)) { keys.push(keyFrame.key1); keys.push(keyFrame.key2); if (isCamera(node) && track.propertyPath === "position") { animation.addEvent(new AnimationEvent(keyFrame.key1.frame, () => { const motionBlur = getMotionBlurPostProcess(); if (!motionBlur) { return; } let motionStrength = motionBlur.motionStrength; motionBlur.motionStrength = 0; requestAnimationFrame(() => { motionBlur.motionStrength = motionStrength; }); })); } } }); animation.setKeys(keys); result.addTargetedAnimation(animation, node); }); result.normalize(); return result; } __name(generateCinematicAnimationGroup, "generateCinematicAnimationGroup"); // Users/michaelmainguy/WebstormProjects/space-game/gameEditor/src/scripts/box.ts init_math_vector(); var SceneComponent = class { constructor(mesh) { this.mesh = mesh; } static { __name(this, "SceneComponent"); } _speed = 0.04; onStart() { } onUpdate() { this.mesh.rotate(Vector3.UpReadOnly, this._speed * this.mesh.getScene().getAnimationRatio()); } }; __decorateClass([ visibleAsNumber("Speed", { min: 0, max: 0.1 }) ], SceneComponent.prototype, "_speed", 2);